ngram
listlengths
0
82k
[ "\\ self.subgraphs == other.subgraphs and \\ self.entities == other.entities and", "self._entities = entities @property def relationships(self): return self._relationships @relationships.setter def", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "== other.actions and \\ self.subgraphs == other.subgraphs and \\ self.entities", "may obtain # a copy of the License at #", "permissions and limitations # under the License. from collections import", "self._entities @entities.setter def entities(self, entities): self._entities = entities @property def", "limitations # under the License. from collections import namedtuple ActionSpecs", "@property def relationships(self): return self._relationships @relationships.setter def relationships(self, relationships): self._relationships", "Nokia # # Licensed under the Apache License, Version 2.0", "# # Licensed under the Apache License, Version 2.0 (the", "return self._template_type @template_type.setter def template_type(self, template_type): self._template_type = template_type @property", "scenarios): self.name = name self.template_type = template_type self.version = version", "agreed to in writing, software # distributed under the License", "self._relationships @relationships.setter def relationships(self, relationships): self._relationships = relationships @property def", "Unless required by applicable law or agreed to in writing,", "self.enabled = enabled def __eq__(self, other): return self.id == other.id", "def entities(self): return self._entities @entities.setter def entities(self, entities): self._entities =", "__init__(self, id, version, condition, actions, subgraphs, entities, relationships, enabled=False): self.id", "distributed under the License is distributed on an \"AS IS\"", "<reponame>HoonMinJeongUm/Hunmin-vitrage<filename>vitrage/evaluator/template_data.py # Copyright 2016 - Nokia # # Licensed under", "@property def version(self): return self._version @version.setter def version(self, version): self._version", "@relationships.setter def relationships(self, relationships): self._relationships = relationships @property def scenarios(self):", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "obtain # a copy of the License at # #", "def __init__(self, id, version, condition, actions, subgraphs, entities, relationships, enabled=False):", "== other.subgraphs and \\ self.entities == other.entities and \\ self.relationships", "relationships): self._relationships = relationships @property def scenarios(self): return self._scenarios @scenarios.setter", "applicable law or agreed to in writing, software # distributed", "the License. from collections import namedtuple ActionSpecs = namedtuple( 'ActionSpecs',", "# Copyright 2016 - Nokia # # Licensed under the", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "@entities.setter def entities(self, entities): self._entities = entities @property def relationships(self):", "= template_name @property def template_type(self): return self._template_type @template_type.setter def template_type(self,", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "name, template_type, version, entities, relationships, scenarios): self.name = name self.template_type", "'entity' RELATIONSHIP = 'relationship' class Scenario(object): def __init__(self, id, version,", "actions self.subgraphs = subgraphs self.entities = entities self.relationships = relationships", "self.entities == other.entities and \\ self.relationships == other.relationships # noinspection", "TemplateData(object): def __init__(self, name, template_type, version, entities, relationships, scenarios): self.name", "other.subgraphs and \\ self.entities == other.entities and \\ self.relationships ==", "def __init__(self, name, template_type, version, entities, relationships, scenarios): self.name =", "writing, software # distributed under the License is distributed on", "id, version, condition, actions, subgraphs, entities, relationships, enabled=False): self.id =", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "subgraphs, entities, relationships, enabled=False): self.id = id self.version = version", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "entities): self._entities = entities @property def relationships(self): return self._relationships @relationships.setter", "'target']) ENTITY = 'entity' RELATIONSHIP = 'relationship' class Scenario(object): def", "return self._name @name.setter def name(self, template_name): self._name = template_name @property", "__eq__(self, other): return self.id == other.id and \\ self.condition ==", "@name.setter def name(self, template_name): self._name = template_name @property def template_type(self):", "and limitations # under the License. from collections import namedtuple", "def relationships(self): return self._relationships @relationships.setter def relationships(self, relationships): self._relationships =", "the License. You may obtain # a copy of the", "PyAttributeOutsideInit class TemplateData(object): def __init__(self, name, template_type, version, entities, relationships,", "relationships(self): return self._relationships @relationships.setter def relationships(self, relationships): self._relationships = relationships", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "ActionSpecs = namedtuple( 'ActionSpecs', ['id', 'type', 'targets', 'properties']) EdgeDescription =", "You may obtain # a copy of the License at", "self.version = version self.condition = condition self.actions = actions self.subgraphs", "other.condition and \\ self.actions == other.actions and \\ self.subgraphs ==", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "self.condition = condition self.actions = actions self.subgraphs = subgraphs self.entities", "entities, relationships, scenarios): self.name = name self.template_type = template_type self.version", "self._name @name.setter def name(self, template_name): self._name = template_name @property def", "# under the License. from collections import namedtuple ActionSpecs =", "version(self, version): self._version = version @property def entities(self): return self._entities", "self._template_type @template_type.setter def template_type(self, template_type): self._template_type = template_type @property def", "template_type self.version = version self.entities = entities self.relationships = relationships", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "under the License. from collections import namedtuple ActionSpecs = namedtuple(", "relationships, scenarios): self.name = name self.template_type = template_type self.version =", "= relationships @property def scenarios(self): return self._scenarios @scenarios.setter def scenarios(self,", "== other.relationships # noinspection PyAttributeOutsideInit class TemplateData(object): def __init__(self, name,", "and \\ self.relationships == other.relationships # noinspection PyAttributeOutsideInit class TemplateData(object):", "@version.setter def version(self, version): self._version = version @property def entities(self):", "'type', 'targets', 'properties']) EdgeDescription = namedtuple('EdgeDescription', ['edge', 'source', 'target']) ENTITY", "either express or implied. See the # License for the", "namedtuple( 'ActionSpecs', ['id', 'type', 'targets', 'properties']) EdgeDescription = namedtuple('EdgeDescription', ['edge',", "def template_type(self, template_type): self._template_type = template_type @property def version(self): return", "__init__(self, name, template_type, version, entities, relationships, scenarios): self.name = name", "self.id = id self.version = version self.condition = condition self.actions", "under the License is distributed on an \"AS IS\" BASIS,", "other): return self.id == other.id and \\ self.condition == other.condition", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "= version self.condition = condition self.actions = actions self.subgraphs =", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "def entities(self, entities): self._entities = entities @property def relationships(self): return", "def scenarios(self): return self._scenarios @scenarios.setter def scenarios(self, scenarios): self._scenarios =", "may # not use this file except in compliance with", "and \\ self.condition == other.condition and \\ self.actions == other.actions", "name self.template_type = template_type self.version = version self.entities = entities", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "version, entities, relationships, scenarios): self.name = name self.template_type = template_type", "self.relationships = relationships self.scenarios = scenarios @property def name(self): return", "relationships self.scenarios = scenarios @property def name(self): return self._name @name.setter", "Scenario(object): def __init__(self, id, version, condition, actions, subgraphs, entities, relationships,", "self.scenarios = scenarios @property def name(self): return self._name @name.setter def", "version self.entities = entities self.relationships = relationships self.scenarios = scenarios", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "name(self, template_name): self._name = template_name @property def template_type(self): return self._template_type", "def version(self, version): self._version = version @property def entities(self): return", "enabled def __eq__(self, other): return self.id == other.id and \\", "= namedtuple( 'ActionSpecs', ['id', 'type', 'targets', 'properties']) EdgeDescription = namedtuple('EdgeDescription',", "namedtuple('EdgeDescription', ['edge', 'source', 'target']) ENTITY = 'entity' RELATIONSHIP = 'relationship'", "\\ self.relationships == other.relationships # noinspection PyAttributeOutsideInit class TemplateData(object): def", "self._version = version @property def entities(self): return self._entities @entities.setter def", "= version @property def entities(self): return self._entities @entities.setter def entities(self,", "you may # not use this file except in compliance", "ENTITY = 'entity' RELATIONSHIP = 'relationship' class Scenario(object): def __init__(self,", "entities self.relationships = relationships self.enabled = enabled def __eq__(self, other):", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "def relationships(self, relationships): self._relationships = relationships @property def scenarios(self): return", "self.relationships = relationships self.enabled = enabled def __eq__(self, other): return", "def name(self): return self._name @name.setter def name(self, template_name): self._name =", "- Nokia # # Licensed under the Apache License, Version", "Copyright 2016 - Nokia # # Licensed under the Apache", "relationships @property def scenarios(self): return self._scenarios @scenarios.setter def scenarios(self, scenarios):", "express or implied. See the # License for the specific", "and \\ self.subgraphs == other.subgraphs and \\ self.entities == other.entities", "this file except in compliance with the License. You may", "language governing permissions and limitations # under the License. from", "@property def scenarios(self): return self._scenarios @scenarios.setter def scenarios(self, scenarios): self._scenarios", "= entities @property def relationships(self): return self._relationships @relationships.setter def relationships(self,", "compliance with the License. You may obtain # a copy", "\\ self.actions == other.actions and \\ self.subgraphs == other.subgraphs and", "return self.id == other.id and \\ self.condition == other.condition and", "= template_type @property def version(self): return self._version @version.setter def version(self,", "the Apache License, Version 2.0 (the \"License\"); you may #", "template_type(self, template_type): self._template_type = template_type @property def version(self): return self._version", "= actions self.subgraphs = subgraphs self.entities = entities self.relationships =", "def __eq__(self, other): return self.id == other.id and \\ self.condition", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "2016 - Nokia # # Licensed under the Apache License,", "= 'relationship' class Scenario(object): def __init__(self, id, version, condition, actions,", "template_type @property def version(self): return self._version @version.setter def version(self, version):", "condition self.actions = actions self.subgraphs = subgraphs self.entities = entities", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "namedtuple ActionSpecs = namedtuple( 'ActionSpecs', ['id', 'type', 'targets', 'properties']) EdgeDescription", "scenarios(self): return self._scenarios @scenarios.setter def scenarios(self, scenarios): self._scenarios = scenarios", "See the # License for the specific language governing permissions", "= entities self.relationships = relationships self.scenarios = scenarios @property def", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "other.id and \\ self.condition == other.condition and \\ self.actions ==", "scenarios @property def name(self): return self._name @name.setter def name(self, template_name):", "@property def template_type(self): return self._template_type @template_type.setter def template_type(self, template_type): self._template_type", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "the # License for the specific language governing permissions and", "condition, actions, subgraphs, entities, relationships, enabled=False): self.id = id self.version", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "entities @property def relationships(self): return self._relationships @relationships.setter def relationships(self, relationships):", "= 'entity' RELATIONSHIP = 'relationship' class Scenario(object): def __init__(self, id,", "@property def entities(self): return self._entities @entities.setter def entities(self, entities): self._entities", "version self.condition = condition self.actions = actions self.subgraphs = subgraphs", "@property def name(self): return self._name @name.setter def name(self, template_name): self._name", "= relationships self.scenarios = scenarios @property def name(self): return self._name", "enabled=False): self.id = id self.version = version self.condition = condition", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "self._relationships = relationships @property def scenarios(self): return self._scenarios @scenarios.setter def", "file except in compliance with the License. You may obtain", "other.entities and \\ self.relationships == other.relationships # noinspection PyAttributeOutsideInit class", "self.subgraphs == other.subgraphs and \\ self.entities == other.entities and \\", "def name(self, template_name): self._name = template_name @property def template_type(self): return", "License. from collections import namedtuple ActionSpecs = namedtuple( 'ActionSpecs', ['id',", "and \\ self.entities == other.entities and \\ self.relationships == other.relationships", "EdgeDescription = namedtuple('EdgeDescription', ['edge', 'source', 'target']) ENTITY = 'entity' RELATIONSHIP", "@template_type.setter def template_type(self, template_type): self._template_type = template_type @property def version(self):", "'properties']) EdgeDescription = namedtuple('EdgeDescription', ['edge', 'source', 'target']) ENTITY = 'entity'", "= name self.template_type = template_type self.version = version self.entities =", "template_type): self._template_type = template_type @property def version(self): return self._version @version.setter", "for the specific language governing permissions and limitations # under", "['id', 'type', 'targets', 'properties']) EdgeDescription = namedtuple('EdgeDescription', ['edge', 'source', 'target'])", "law or agreed to in writing, software # distributed under", "other.actions and \\ self.subgraphs == other.subgraphs and \\ self.entities ==", "return self._relationships @relationships.setter def relationships(self, relationships): self._relationships = relationships @property", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "'relationship' class Scenario(object): def __init__(self, id, version, condition, actions, subgraphs,", "= entities self.relationships = relationships self.enabled = enabled def __eq__(self,", "relationships, enabled=False): self.id = id self.version = version self.condition =", "name(self): return self._name @name.setter def name(self, template_name): self._name = template_name", "entities, relationships, enabled=False): self.id = id self.version = version self.condition", "self.relationships == other.relationships # noinspection PyAttributeOutsideInit class TemplateData(object): def __init__(self,", "template_name @property def template_type(self): return self._template_type @template_type.setter def template_type(self, template_type):", "under the Apache License, Version 2.0 (the \"License\"); you may", "self.version = version self.entities = entities self.relationships = relationships self.scenarios", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "version @property def entities(self): return self._entities @entities.setter def entities(self, entities):", "implied. See the # License for the specific language governing", "return self._version @version.setter def version(self, version): self._version = version @property", "= version self.entities = entities self.relationships = relationships self.scenarios =", "import namedtuple ActionSpecs = namedtuple( 'ActionSpecs', ['id', 'type', 'targets', 'properties'])", "['edge', 'source', 'target']) ENTITY = 'entity' RELATIONSHIP = 'relationship' class", "and \\ self.actions == other.actions and \\ self.subgraphs == other.subgraphs", "= relationships self.enabled = enabled def __eq__(self, other): return self.id", "= subgraphs self.entities = entities self.relationships = relationships self.enabled =", "template_type, version, entities, relationships, scenarios): self.name = name self.template_type =", "def template_type(self): return self._template_type @template_type.setter def template_type(self, template_type): self._template_type =", "License. You may obtain # a copy of the License", "== other.entities and \\ self.relationships == other.relationships # noinspection PyAttributeOutsideInit", "== other.condition and \\ self.actions == other.actions and \\ self.subgraphs", "\\ self.entities == other.entities and \\ self.relationships == other.relationships #", "class TemplateData(object): def __init__(self, name, template_type, version, entities, relationships, scenarios):", "\\ self.condition == other.condition and \\ self.actions == other.actions and", "from collections import namedtuple ActionSpecs = namedtuple( 'ActionSpecs', ['id', 'type',", "= namedtuple('EdgeDescription', ['edge', 'source', 'target']) ENTITY = 'entity' RELATIONSHIP =", "class Scenario(object): def __init__(self, id, version, condition, actions, subgraphs, entities,", "actions, subgraphs, entities, relationships, enabled=False): self.id = id self.version =", "self.actions == other.actions and \\ self.subgraphs == other.subgraphs and \\", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "collections import namedtuple ActionSpecs = namedtuple( 'ActionSpecs', ['id', 'type', 'targets',", "'ActionSpecs', ['id', 'type', 'targets', 'properties']) EdgeDescription = namedtuple('EdgeDescription', ['edge', 'source',", "other.relationships # noinspection PyAttributeOutsideInit class TemplateData(object): def __init__(self, name, template_type,", "# Unless required by applicable law or agreed to in", "# noinspection PyAttributeOutsideInit class TemplateData(object): def __init__(self, name, template_type, version,", "self._template_type = template_type @property def version(self): return self._version @version.setter def", "return self._entities @entities.setter def entities(self, entities): self._entities = entities @property", "self.actions = actions self.subgraphs = subgraphs self.entities = entities self.relationships", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "self.entities = entities self.relationships = relationships self.scenarios = scenarios @property", "relationships self.enabled = enabled def __eq__(self, other): return self.id ==", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "RELATIONSHIP = 'relationship' class Scenario(object): def __init__(self, id, version, condition,", "self._version @version.setter def version(self, version): self._version = version @property def", "noinspection PyAttributeOutsideInit class TemplateData(object): def __init__(self, name, template_type, version, entities,", "self.template_type = template_type self.version = version self.entities = entities self.relationships", "= id self.version = version self.condition = condition self.actions =", "id self.version = version self.condition = condition self.actions = actions", "'source', 'target']) ENTITY = 'entity' RELATIONSHIP = 'relationship' class Scenario(object):", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "self._name = template_name @property def template_type(self): return self._template_type @template_type.setter def", "version(self): return self._version @version.setter def version(self, version): self._version = version", "relationships(self, relationships): self._relationships = relationships @property def scenarios(self): return self._scenarios", "def version(self): return self._version @version.setter def version(self, version): self._version =", "governing permissions and limitations # under the License. from collections", "= scenarios @property def name(self): return self._name @name.setter def name(self,", "entities(self): return self._entities @entities.setter def entities(self, entities): self._entities = entities", "or agreed to in writing, software # distributed under the", "== other.id and \\ self.condition == other.condition and \\ self.actions", "= template_type self.version = version self.entities = entities self.relationships =", "entities self.relationships = relationships self.scenarios = scenarios @property def name(self):", "template_name): self._name = template_name @property def template_type(self): return self._template_type @template_type.setter", "required by applicable law or agreed to in writing, software", "entities(self, entities): self._entities = entities @property def relationships(self): return self._relationships", "= condition self.actions = actions self.subgraphs = subgraphs self.entities =", "self.condition == other.condition and \\ self.actions == other.actions and \\", "= enabled def __eq__(self, other): return self.id == other.id and", "template_type(self): return self._template_type @template_type.setter def template_type(self, template_type): self._template_type = template_type", "self.id == other.id and \\ self.condition == other.condition and \\", "version, condition, actions, subgraphs, entities, relationships, enabled=False): self.id = id", "subgraphs self.entities = entities self.relationships = relationships self.enabled = enabled", "'targets', 'properties']) EdgeDescription = namedtuple('EdgeDescription', ['edge', 'source', 'target']) ENTITY =", "self.entities = entities self.relationships = relationships self.enabled = enabled def", "version): self._version = version @property def entities(self): return self._entities @entities.setter", "self.subgraphs = subgraphs self.entities = entities self.relationships = relationships self.enabled", "self.name = name self.template_type = template_type self.version = version self.entities", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "args.group not in ['ba', 'bcg', 'lef']: raise Exception(\"GROUPS must be", "[], 'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0} with", "SAMPLES[sample]['results']: for result in SAMPLES[sample]['results']: row = { 'sample': sample,", "on chromosome SAMPLES[row['accession']]['has_lethal'] = True else: SAMPLES[row['accession']]['has_lethal'] = False SAMPLES[row['accession']]['results']", "filter_kmers: parse = kmer in KMERS or reverse_complement(kmer) in KMERS", "0, 'tn': 0, 'fp': 0, 'fn': 0 } def parse_summary(summary):", "\"{0}/*-{1}.txt.gz\".format(path, args.group) )) for count_file in count_files: coverage = os.path.basename(count_file).split('-')[1]", "line.decode().rstrip().split() count = int(count) parse = True if filter_kmers: parse", "for coverage in coverages: KMERS[kmer][coverage] = { 'group_coverages': [], 'outgroup_coverages':", "kmer, 'simulated_coverage': coverage, 'group': args.group, 'hamming_distance': HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'], 'tn':", "total)) current += 1 count_files = sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path, args.group) ))", "'non_zero_min': min(non_zero_array) if non_zero else 0, 'non_zero_median': int(np.median(non_zero_array)) if non_zero", "parse_summary(summary): \"\"\"Parse Summary file.\"\"\" cols = None with open(summary, 'r')", "line = line.rstrip() if line.startswith('#'): cols = line.replace('#', '').split('\\t') else:", "SAMPLES[sample]['results']: row = { 'sample': sample, 'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'],", "if line.startswith('#'): cols = line.replace('#', '').split('\\t') else: row = dict(zip(cols,", "KMERS or reverse_complement(kmer) in KMERS elif not skip_kmers: if kmer", "coverage_stats = get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage, 'within_group': within_group, 'tp': sample_row['tp'],", "sample summaries.\"\"\" with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\") for", "b in seq[::-1]]) def parse_counts(counts, sample, coverage, group, skip_kmers=False, filter_kmers=False):", "'__main__': parser = ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve', description=(\"Summarize kmer counts of", "\"\"\"Return lines in a text file as a list.\"\"\" lines", "argparse as ap from collections import OrderedDict import glob import", "sample_row = {'coverages': [], 'tp': 0, 'tn': 0, 'fp': 0,", "'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], }) def parse_kmers(kmers, coverages, skip_kmers=False, has_hamming=True):", "distance = line.split(\"-\") if not has_hamming: distance = False KMERS[kmer]", "lef).') parser.add_argument('kmers', type=str, metavar=\"KMERS\", help='Group specific k-mers.') parser.add_argument('coverages', type=str, metavar=\"COVERAGES\",", "def get_group_status(sample, group): \"\"\"Return if a sample is within a", "help='Summary of Bacillus genomes.') parser.add_argument('directory', type=str, metavar=\"SIMUALTION_DIR\", help='Directory with group", "current += 1 count_files = sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path, args.group) )) for", "sequence.\"\"\" complement = { 'A': 'T', 'T': 'A', 'G': 'C',", "else: print(\"Parsing Kmers\") parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers, has_hamming=False if args.group ==", "'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'],", "str(row[col]) for col in SAMPLE_COLS ]))) output_handle.write(\"\\n\") def print_kmer_summary(file_output): \"\"\"Print", "'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min',", "}) def parse_kmers(kmers, coverages, skip_kmers=False, has_hamming=True): with open(kmers, 'r') as", "sample_row['fn'] += 1 else: if count: sample_row['fp'] += 1 else:", "KMER_COLS = [ 'kmer', 'simulated_coverage', 'group', 'hamming_distance', 'tp', 'tn', 'fp',", "line.split('\\t'))) SAMPLES[row['accession']] = row if row['accession'] == 'NZ_CP009941': # NZ_CP009941", "args.single_sample: samples = [args.single_sample] total = len(samples) for sample in", "True if SAMPLES[sample]['has_lethal'] else False return within_group def get_coverage_stats(coverage): \"\"\"Return", "kmer_handle: for line in kmer_handle: if line.startswith(\">\"): line = line.rstrip().replace(\">\",", "np_array = np.array(coverage) non_zero_array = np.array(non_zero) return { 'min': min(coverage)", "OrderedDict() SAMPLE_COLS = [ 'sample', 'is_bcg', 'is_ba', 'has_lethal', 'simulated_coverage', 'group',", "or lef).') parser.add_argument('kmers', type=str, metavar=\"KMERS\", help='Group specific k-mers.') parser.add_argument('coverages', type=str,", "within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if count: KMERS[kmer][coverage]['tp'] += 1 else: KMERS[kmer][coverage]['fn'] +=", "\"\"\"Return summary stats of a set of coverages.\"\"\" non_zero =", "0, 'fn': 0 } def parse_summary(summary): \"\"\"Parse Summary file.\"\"\" cols", "sys import time import numpy as np import multiprocessing as", "+= 1 else: KMERS[kmer][coverage]['fn'] += 1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count:", "'bcg': within_group = True if SAMPLES[sample]['is_bcg'] == 'True' else False", "output_handle.write(\"\\n\") def read_lines(input_file): \"\"\"Return lines in a text file as", "outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], } output_handle.write((\"\\t\".join([ str(row[col])", "= len(samples) for sample in samples: path = \"{0}/{1}\".format(args.directory, sample)", "specific kmer counts.\"\"\" import argparse as ap from collections import", "if non_zero else 0, 'non_zero_median': int(np.median(non_zero_array)) if non_zero else 0,", "group or not.\"\"\" within_group = None if group == 'ba':", "set of coverages.\"\"\" non_zero = [c for c in coverage", "'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], } output_handle.write((\"\\t\".join([ str(row[col]) for col in", "'fn': 0} with gzip.open(counts, 'r') as count_handle: for line in", "31-mer counts.') parser.add_argument('group', type=str, metavar=\"GROUP\", help='Which group to parse (ba,", "summary\") if args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format(", "True else: SAMPLES[row['accession']]['has_lethal'] = False SAMPLES[row['accession']]['results'] = [] def print_sample_summary(file_output):", "help=('Coverages to subsample to.')) parser.add_argument('outdir', type=str, metavar=\"OUTDIR\", help='Directory to output", "args.skip_kmers: print(\"Output kmer summary\") if args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group", "the final per kmer summaries.\"\"\" with open(file_output, 'w') as output_handle:", "coverage in coverages: within_group = get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] ) outgroup =", "print(\"Parsing Kmers\") parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers, has_hamming=False if args.group == 'lef'", "sample_row['tp'] += 1 else: sample_row['fn'] += 1 else: if count:", "if coverage else 0, 'median': int(np.median(np_array)) if coverage else 0,", "for result in SAMPLES[sample]['results']: row = { 'sample': sample, 'is_bcg':", "import os import sys import time import numpy as np", "summary_handle: line = line.rstrip() if line.startswith('#'): cols = line.replace('#', '').split('\\t')", "KMERS[kmer][coverage]['fp'] += 1 else: KMERS[kmer][coverage]['tn'] += 1 if parse: sample_row['coverages'].append(count)", "'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'],", "= dict(zip(cols, line.split('\\t'))) SAMPLES[row['accession']] = row if row['accession'] == 'NZ_CP009941':", "outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max':", "if coverage else 0, 'non_zero_min': min(non_zero_array) if non_zero else 0,", "lines def parse_filter_kmers(kmers): with open(kmers, 'r') as kmer_handle: for line", "KMERS[kmer][coverage]['tp'] += 1 else: KMERS[kmer][coverage]['fn'] += 1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if", "seq[::-1]]) def parse_counts(counts, sample, coverage, group, skip_kmers=False, filter_kmers=False): \"\"\"Parse kmer", "'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'],", "parse = True if filter_kmers: parse = kmer in KMERS", "or reverse_complement(kmer) in KMERS elif not skip_kmers: if kmer not", "not in KMERS: kmer = reverse_complement(kmer) if within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if", "coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], }) def parse_kmers(kmers, coverages, skip_kmers=False,", "ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve', description=(\"Summarize kmer counts of each simulation.\") )", "line in input_handle: lines.append(line.rstrip()) return lines def parse_filter_kmers(kmers): with open(kmers,", "of each simulation.\") ) parser.add_argument('summary', type=str, metavar=\"SUMMARY\", help='Summary of Bacillus", "to output to.') parser.add_argument('--cpu', default=1, type=int, metavar=\"INT\", help='Number of cores", "sample summary\") if args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else:", "KMERS[kmer] = OrderedDict() HAMMING[kmer] = distance if not skip_kmers: for", ")) if not args.skip_kmers: print(\"Output kmer summary\") if args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format(", "= row if row['accession'] == 'NZ_CP009941': # NZ_CP009941 - Bacillus", "based on input kmers.') args = parser.parse_args() if args.group not", "'t', 't': 'a', 'g': 'c', 'c': 'g' } return ''.join([complement[b]", "'C': 'G', 'a': 't', 't': 'a', 'g': 'c', 'c': 'g'", "line in kmer_handle: if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") kmer,", "'non_zero_outgroup_kmer_cov_max' ] def get_group_status(sample, group): \"\"\"Return if a sample is", "True if SAMPLES[sample]['is_ba'] == 'True' else False elif group ==", "non_zero else 0, } def reverse_complement(seq): \"\"\"Reverse complement a DNA", "type=str, metavar=\"KMERS\", help='Group specific k-mers.') parser.add_argument('coverages', type=str, metavar=\"COVERAGES\", help=('Coverages to", "complement a DNA sequence.\"\"\" complement = { 'A': 'T', 'T':", "[] with open(input_file, 'r') as input_handle: for line in input_handle:", "0, 'median': int(np.median(np_array)) if coverage else 0, 'mean': \"{0:.4f}\".format(np.mean(np_array)) if", "parse_counts(counts, sample, coverage, group, skip_kmers=False, filter_kmers=False): \"\"\"Parse kmer counts.\"\"\" within_group", "'median': int(np.median(np_array)) if coverage else 0, 'mean': \"{0:.4f}\".format(np.mean(np_array)) if coverage", "else 0, 'max': max(coverage) if coverage else 0, 'non_zero_min': min(non_zero_array)", "[], 'outgroup_coverages': [], 'tp': 0, 'tn': 0, 'fp': 0, 'fn':", "description for line in summary_handle: line = line.rstrip() if line.startswith('#'):", "result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] } output_handle.write((\"\\t\".join([ str(row[col]) for col", "else: KMERS[kmer][coverage]['tn'] += 1 if parse: sample_row['coverages'].append(count) if within_group: if", "import sys import time import numpy as np import multiprocessing", "sample, coverage, args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter) print(\"Output sample summary\") if args.single_sample:", "default=1, type=int, metavar=\"INT\", help='Number of cores to use (Default: 1)')", "parser.add_argument('summary', type=str, metavar=\"SUMMARY\", help='Summary of Bacillus genomes.') parser.add_argument('directory', type=str, metavar=\"SIMUALTION_DIR\",", "if within_group: if count: sample_row['tp'] += 1 else: sample_row['fn'] +=", "lines in a text file as a list.\"\"\" lines =", "a DNA sequence.\"\"\" complement = { 'A': 'T', 'T': 'A',", "'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], }) def parse_kmers(kmers, coverages,", "SAMPLES: if SAMPLES[sample]['results']: for result in SAMPLES[sample]['results']: row = {", "'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median',", "coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], })", "metavar=\"STR\", help='Process a single sample.') parser.add_argument('--skip_kmers', action='store_true', default=False, help='Skip kmer", "parser.add_argument('--skip_kmers', action='store_true', default=False, help='Skip kmer processing.') parser.add_argument('--filter', action='store_true', default=False, help='Filter", "coverage = os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample, coverage, args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter) print(\"Output", "'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], }) def", "0 } def parse_summary(summary): \"\"\"Parse Summary file.\"\"\" cols = None", "default=False, help='Skip kmer processing.') parser.add_argument('--filter', action='store_true', default=False, help='Filter counts based", "coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max':", "for col in KMER_COLS ]))) output_handle.write(\"\\n\") def read_lines(input_file): \"\"\"Return lines", "HAMMING[kmer] = distance if not skip_kmers: for coverage in coverages:", "= { 'kmer': kmer, 'simulated_coverage': coverage, 'group': args.group, 'hamming_distance': HAMMING[kmer],", "lines.append(line.rstrip()) return lines def parse_filter_kmers(kmers): with open(kmers, 'r') as kmer_handle:", "coverages in KMERS.items(): for coverage in coverages: within_group = get_coverage_stats(", "single sample.') parser.add_argument('--skip_kmers', action='store_true', default=False, help='Skip kmer processing.') parser.add_argument('--filter', action='store_true',", "help='Directory to output to.') parser.add_argument('--cpu', default=1, type=int, metavar=\"INT\", help='Number of", "int(round(np.mean(non_zero_array))) if non_zero else 0, 'non_zero_max': max(non_zero_array) if non_zero else", "group): \"\"\"Return if a sample is within a group or", "non_zero else 0, 'non_zero_max': max(non_zero_array) if non_zero else 0, }", "'r') as input_handle: for line in input_handle: lines.append(line.rstrip()) return lines", "a single sample.') parser.add_argument('--skip_kmers', action='store_true', default=False, help='Skip kmer processing.') parser.add_argument('--filter',", "[ 'kmer', 'simulated_coverage', 'group', 'hamming_distance', 'tp', 'tn', 'fp', 'fn', 'group_kmer_cov_min',", "} def parse_summary(summary): \"\"\"Parse Summary file.\"\"\" cols = None with", "== '__main__': parser = ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve', description=(\"Summarize kmer counts", "== 'bcg': within_group = True if SAMPLES[sample]['is_bcg'] == 'True' else", "if coverage else 0, 'mean': \"{0:.4f}\".format(np.mean(np_array)) if coverage else 0,", "col in KMER_COLS ]))) output_handle.write(\"\\n\") def read_lines(input_file): \"\"\"Return lines in", "if SAMPLES[sample]['has_lethal'] else False return within_group def get_coverage_stats(coverage): \"\"\"Return summary", "result['fn'], 'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min':", "'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0} with gzip.open(counts,", "count_handle: for line in count_handle: kmer, count = line.decode().rstrip().split() count", "skip_kmers=args.skip_kmers, filter_kmers=args.filter) print(\"Output sample summary\") if args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir, args.single_sample,", "if args.group == 'lef' else True) total_kmers = len(KMERS) current", "'is_ba', 'has_lethal', 'simulated_coverage', 'group', 'total_kmers', 'tp', 'tn', 'fp', 'fn', 'kmer_cov_min',", "in KMER_COLS ]))) output_handle.write(\"\\n\") def read_lines(input_file): \"\"\"Return lines in a", "({1} of {2})\".format(sample, current, total)) current += 1 count_files =", "= line.replace('#', '').split('\\t') else: row = dict(zip(cols, line.split('\\t'))) SAMPLES[row['accession']] =", "np import multiprocessing as mp SAMPLES = OrderedDict() KMERS =", "1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count: KMERS[kmer][coverage]['fp'] += 1 else: KMERS[kmer][coverage]['tn']", "each simulation.\") ) parser.add_argument('summary', type=str, metavar=\"SUMMARY\", help='Summary of Bacillus genomes.')", "if filter_kmers: parse = kmer in KMERS or reverse_complement(kmer) in", "1 else: KMERS[kmer][coverage]['fn'] += 1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count: KMERS[kmer][coverage]['fp']", "print(\"Output sample summary\") if args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group ))", "'T', 'T': 'A', 'G': 'C', 'C': 'G', 'a': 't', 't':", "'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max': within_group['max'],", "metavar=\"COVERAGES\", help=('Coverages to subsample to.')) parser.add_argument('outdir', type=str, metavar=\"OUTDIR\", help='Directory to", "= False KMERS[kmer] = OrderedDict() HAMMING[kmer] = distance if not", "group == 'bcg': within_group = True if SAMPLES[sample]['is_bcg'] == 'True'", "coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], }) def parse_kmers(kmers,", "'sample', 'is_bcg', 'is_ba', 'has_lethal', 'simulated_coverage', 'group', 'total_kmers', 'tp', 'tn', 'fp',", "sample.') parser.add_argument('--skip_kmers', action='store_true', default=False, help='Skip kmer processing.') parser.add_argument('--filter', action='store_true', default=False,", "as ap from collections import OrderedDict import glob import gzip", "parser.add_argument('--cpu', default=1, type=int, metavar=\"INT\", help='Number of cores to use (Default:", "args.group )) else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir, args.group )) if not args.skip_kmers:", "KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min':", "output_handle: output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\") for kmer, coverages in KMERS.items(): for coverage", "coverages, skip_kmers=args.skip_kmers, has_hamming=False if args.group == 'lef' else True) total_kmers", "cols = None with open(summary, 'r') as summary_handle: # Column", "0, 'max': max(coverage) if coverage else 0, 'non_zero_min': min(non_zero_array) if", "1 count_files = sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path, args.group) )) for count_file in", "'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ] KMER_COLS", "coverage, group, skip_kmers=False, filter_kmers=False): \"\"\"Parse kmer counts.\"\"\" within_group = get_group_status(sample,", "= parser.parse_args() if args.group not in ['ba', 'bcg', 'lef']: raise", "args.single_sample, args.group )) else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir, args.group )) if not", "== 'True' else False else: # lef within_group = True", "count: sample_row['tp'] += 1 else: sample_row['fn'] += 1 else: if", "specific k-mers.') parser.add_argument('coverages', type=str, metavar=\"COVERAGES\", help=('Coverages to subsample to.')) parser.add_argument('outdir',", "if __name__ == '__main__': parser = ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve', description=(\"Summarize", "within_group def get_coverage_stats(coverage): \"\"\"Return summary stats of a set of", "args = parser.parse_args() if args.group not in ['ba', 'bcg', 'lef']:", "= None with open(summary, 'r') as summary_handle: # Column Names:", "output to.') parser.add_argument('--cpu', default=1, type=int, metavar=\"INT\", help='Number of cores to", "else 0, 'non_zero_median': int(np.median(non_zero_array)) if non_zero else 0, 'non_zero_mean': int(round(np.mean(non_zero_array)))", "return within_group def get_coverage_stats(coverage): \"\"\"Return summary stats of a set", "line = line.rstrip().replace(\">\", \"\") kmer, distance = line.split(\"-\") if not", "if SAMPLES[sample]['results']: for result in SAMPLES[sample]['results']: row = { 'sample':", "non_zero else 0, 'non_zero_median': int(np.median(non_zero_array)) if non_zero else 0, 'non_zero_mean':", "per kmer summaries.\"\"\" with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\")", "action='store_true', default=False, help='Filter counts based on input kmers.') args =", "import OrderedDict import glob import gzip import os import sys", "skip_kmers=args.skip_kmers, has_hamming=False if args.group == 'lef' else True) total_kmers =", "SAMPLES[sample]['has_lethal'] else False return within_group def get_coverage_stats(coverage): \"\"\"Return summary stats", "'').split('\\t') else: row = dict(zip(cols, line.split('\\t'))) SAMPLES[row['accession']] = row if", "'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], } output_handle.write((\"\\t\".join([", "in a text file as a list.\"\"\" lines = []", "== 'lef' else True) total_kmers = len(KMERS) current = 1", "def reverse_complement(seq): \"\"\"Reverse complement a DNA sequence.\"\"\" complement = {", "for b in seq[::-1]]) def parse_counts(counts, sample, coverage, group, skip_kmers=False,", "within_group, 'tp': sample_row['tp'], 'tn': sample_row['tn'], 'fp': sample_row['fp'], 'fn': sample_row['fn'], 'kmer_cov_min':", "= {'coverages': [], 'tp': 0, 'tn': 0, 'fp': 0, 'fn':", "current = 1 samples = list(SAMPLES.keys()) if args.single_sample: samples =", "args.outdir, args.single_sample, args.group )) else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir, args.group )) if", "skip_kmers: if kmer not in KMERS: kmer = reverse_complement(kmer) if", "'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'],", "+= 1 else: if count: sample_row['fp'] += 1 else: sample_row['tn']", "'fp', 'fn', 'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max'", "else 0, 'non_zero_min': min(non_zero_array) if non_zero else 0, 'non_zero_median': int(np.median(non_zero_array))", "if count: KMERS[kmer][coverage]['fp'] += 1 else: KMERS[kmer][coverage]['tn'] += 1 if", "list(SAMPLES.keys()) if args.single_sample: samples = [args.single_sample] total = len(samples) for", "mp SAMPLES = OrderedDict() KMERS = {} HAMMING = OrderedDict()", "} def reverse_complement(seq): \"\"\"Reverse complement a DNA sequence.\"\"\" complement =", "'tn', 'fp', 'fn', 'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median',", "'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0 } def", "[] def print_sample_summary(file_output): \"\"\"Print the final per sample summaries.\"\"\" with", "text file as a list.\"\"\" lines = [] with open(input_file,", "in KMERS elif not skip_kmers: if kmer not in KMERS:", "- Bacillus cereus w/ lef on chromosome SAMPLES[row['accession']]['has_lethal'] = True", "True if __name__ == '__main__': parser = ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve',", "= sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path, args.group) )) for count_file in count_files: coverage", "as a list.\"\"\" lines = [] with open(input_file, 'r') as", "'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max'", "within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max':", "result in SAMPLES[sample]['results']: row = { 'sample': sample, 'is_bcg': SAMPLES[sample]['is_bcg'],", "'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'],", "distance if not skip_kmers: for coverage in coverages: KMERS[kmer][coverage] =", "reverse_complement(kmer) in KMERS elif not skip_kmers: if kmer not in", "line.startswith('#'): cols = line.replace('#', '').split('\\t') else: row = dict(zip(cols, line.split('\\t')))", "'within_group': within_group, 'tp': sample_row['tp'], 'tn': sample_row['tn'], 'fp': sample_row['fp'], 'fn': sample_row['fn'],", "Names: # accession, gi, is_bcg, is_ba, species, genome_size, description for", "line in kmer_handle: if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") KMERS[line.split(\"-\")[0]]", "+= 1 if parse: sample_row['coverages'].append(count) if within_group: if count: sample_row['tp']", "not skip_kmers: if kmer not in KMERS: kmer = reverse_complement(kmer)", "'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min',", "= get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] ) row = { 'kmer': kmer, 'simulated_coverage':", "SAMPLE_COLS ]))) output_handle.write(\"\\n\") def print_kmer_summary(file_output): \"\"\"Print the final per kmer", "input kmers.') args = parser.parse_args() if args.group not in ['ba',", "+= 1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count: KMERS[kmer][coverage]['fp'] += 1 else:", "= True if __name__ == '__main__': parser = ap.ArgumentParser( prog='summarize-kmer-counts.py',", "print(\"Filtering Kmers\") args.skip_kmers = True parse_filter_kmers(args.kmers) else: print(\"Parsing Kmers\") parse_kmers(args.kmers,", "SAMPLES[sample]['is_ba'] == 'True' else False elif group == 'bcg': within_group", "(Default: 1)') parser.add_argument('--single_sample', type=str, metavar=\"STR\", help='Process a single sample.') parser.add_argument('--skip_kmers',", "'c', 'c': 'g' } return ''.join([complement[b] for b in seq[::-1]])", "else: SAMPLES[row['accession']]['has_lethal'] = False SAMPLES[row['accession']]['results'] = [] def print_sample_summary(file_output): \"\"\"Print", "for count_file in count_files: coverage = os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample, coverage,", "samples: path = \"{0}/{1}\".format(args.directory, sample) if os.path.exists(path): print(\"Working on {0}", "line.rstrip() if line.startswith('#'): cols = line.replace('#', '').split('\\t') else: row =", "if a sample is within a group or not.\"\"\" within_group", "if group == 'ba': within_group = True if SAMPLES[sample]['is_ba'] ==", "'tn': 0, 'fp': 0, 'fn': 0 } def parse_summary(summary): \"\"\"Parse", "to use (Default: 1)') parser.add_argument('--single_sample', type=str, metavar=\"STR\", help='Process a single", "group) sample_row = {'coverages': [], 'tp': 0, 'tn': 0, 'fp':", "] KMER_COLS = [ 'kmer', 'simulated_coverage', 'group', 'hamming_distance', 'tp', 'tn',", "'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'],", "{ 'kmer': kmer, 'simulated_coverage': coverage, 'group': args.group, 'hamming_distance': HAMMING[kmer], 'tp':", "'tn': KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean': within_group['mean'],", "= [] with open(input_file, 'r') as input_handle: for line in", "(ba, bcg or lef).') parser.add_argument('kmers', type=str, metavar=\"KMERS\", help='Group specific k-mers.')", "else True) total_kmers = len(KMERS) current = 1 samples =", "{2})\".format(sample, current, total)) current += 1 count_files = sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path,", "KMERS: kmer = reverse_complement(kmer) if within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if count: KMERS[kmer][coverage]['tp']", "KMERS[kmer][coverage]['tn'] += 1 if parse: sample_row['coverages'].append(count) if within_group: if count:", "parse_summary(args.summary) print(\"Parsing Kmers\") if args.filter: print(\"Filtering Kmers\") args.skip_kmers = True", "a group or not.\"\"\" within_group = None if group ==", "result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max':", "# accession, gi, is_bcg, is_ba, species, genome_size, description for line", "= True else: SAMPLES[row['accession']]['has_lethal'] = False SAMPLES[row['accession']]['results'] = [] def", "return lines def parse_filter_kmers(kmers): with open(kmers, 'r') as kmer_handle: for", "in coverage if c] np_array = np.array(coverage) non_zero_array = np.array(non_zero)", "as np import multiprocessing as mp SAMPLES = OrderedDict() KMERS", "type=str, metavar=\"SIMUALTION_DIR\", help='Directory with group specific 31-mer counts.') parser.add_argument('group', type=str,", "False return within_group def get_coverage_stats(coverage): \"\"\"Return summary stats of a", "get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] ) outgroup = get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] ) row =", "= OrderedDict() KMERS = {} HAMMING = OrderedDict() SAMPLE_COLS =", "= list(SAMPLES.keys()) if args.single_sample: samples = [args.single_sample] total = len(samples)", "[args.single_sample] total = len(samples) for sample in samples: path =", "kmer = reverse_complement(kmer) if within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if count: KMERS[kmer][coverage]['tp'] +=", "'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean',", "has_hamming=True): with open(kmers, 'r') as kmer_handle: for line in kmer_handle:", "in summary_handle: line = line.rstrip() if line.startswith('#'): cols = line.replace('#',", "== 'NZ_CP009941': # NZ_CP009941 - Bacillus cereus w/ lef on", "line.replace('#', '').split('\\t') else: row = dict(zip(cols, line.split('\\t'))) SAMPLES[row['accession']] = row", "if args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else: print_kmer_summary(\"{0}/count-summary-kmer-{1}.txt\".format( args.outdir,", "parse_kmers(kmers, coverages, skip_kmers=False, has_hamming=True): with open(kmers, 'r') as kmer_handle: for", "a sample is within a group or not.\"\"\" within_group =", "with open(kmers, 'r') as kmer_handle: for line in kmer_handle: if", "'total_kmers', 'tp', 'tn', 'fp', 'fn', 'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min',", "else False elif group == 'bcg': within_group = True if", "counts.') parser.add_argument('group', type=str, metavar=\"GROUP\", help='Which group to parse (ba, bcg", "a set of coverages.\"\"\" non_zero = [c for c in", "skip_kmers: for coverage in coverages: KMERS[kmer][coverage] = { 'group_coverages': [],", "print_kmer_summary(file_output): \"\"\"Print the final per kmer summaries.\"\"\" with open(file_output, 'w')", "'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'],", "processing.') parser.add_argument('--filter', action='store_true', default=False, help='Filter counts based on input kmers.')", "int(np.median(np_array)) if coverage else 0, 'mean': \"{0:.4f}\".format(np.mean(np_array)) if coverage else", "'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ] def get_group_status(sample, group):", "in count_handle: kmer, count = line.decode().rstrip().split() count = int(count) parse", "metavar=\"SUMMARY\", help='Summary of Bacillus genomes.') parser.add_argument('directory', type=str, metavar=\"SIMUALTION_DIR\", help='Directory with", "'simulated_coverage': coverage, 'within_group': within_group, 'tp': sample_row['tp'], 'tn': sample_row['tn'], 'fp': sample_row['fp'],", "False KMERS[kmer] = OrderedDict() HAMMING[kmer] = distance if not skip_kmers:", "'fp': 0, 'fn': 0 } def parse_summary(summary): \"\"\"Parse Summary file.\"\"\"", "False else: # lef within_group = True if SAMPLES[sample]['has_lethal'] else", "sample_row['tn'] += 1 coverage_stats = get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage, 'within_group':", "for col in SAMPLE_COLS ]))) output_handle.write(\"\\n\") def print_kmer_summary(file_output): \"\"\"Print the", "sample_row['coverages'].append(count) if within_group: if count: sample_row['tp'] += 1 else: sample_row['fn']", "len(KMERS) current = 1 samples = list(SAMPLES.keys()) if args.single_sample: samples", "else 0, 'median': int(np.median(np_array)) if coverage else 0, 'mean': \"{0:.4f}\".format(np.mean(np_array))", "'mean': \"{0:.4f}\".format(np.mean(np_array)) if coverage else 0, 'max': max(coverage) if coverage", "open(kmers, 'r') as kmer_handle: for line in kmer_handle: if line.startswith(\">\"):", "final per kmer summaries.\"\"\" with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(KMER_COLS)))", "within_group = True if SAMPLES[sample]['is_ba'] == 'True' else False elif", "within_group = True if SAMPLES[sample]['is_bcg'] == 'True' else False else:", "for c in coverage if c] np_array = np.array(coverage) non_zero_array", "0, 'mean': \"{0:.4f}\".format(np.mean(np_array)) if coverage else 0, 'max': max(coverage) if", "0, 'tn': 0, 'fp': 0, 'fn': 0} with gzip.open(counts, 'r')", "reverse_complement(seq): \"\"\"Reverse complement a DNA sequence.\"\"\" complement = { 'A':", "if SAMPLES[sample]['is_ba'] == 'True' else False elif group == 'bcg':", "Summary file.\"\"\" cols = None with open(summary, 'r') as summary_handle:", "+= 1 else: KMERS[kmer][coverage]['tn'] += 1 if parse: sample_row['coverages'].append(count) if", "kmer_handle: if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") kmer, distance =", "'w') as output_handle: output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\") for kmer, coverages in KMERS.items():", "{} HAMMING = OrderedDict() SAMPLE_COLS = [ 'sample', 'is_bcg', 'is_ba',", "if not has_hamming: distance = False KMERS[kmer] = OrderedDict() HAMMING[kmer]", "open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\") for sample in SAMPLES:", "be 'ba', 'bcg' or 'lef'\") coverages = read_lines(args.coverages) print(\"Parsing Summary\")", "coverage else 0, 'median': int(np.median(np_array)) if coverage else 0, 'mean':", "coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean':", "not.\"\"\" within_group = None if group == 'ba': within_group =", "help='Skip kmer processing.') parser.add_argument('--filter', action='store_true', default=False, help='Filter counts based on", "'g' } return ''.join([complement[b] for b in seq[::-1]]) def parse_counts(counts,", "= \"{0}/{1}\".format(args.directory, sample) if os.path.exists(path): print(\"Working on {0} ({1} of", "result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean':", "input_handle: lines.append(line.rstrip()) return lines def parse_filter_kmers(kmers): with open(kmers, 'r') as", "'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] } output_handle.write((\"\\t\".join([", "outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean':", "print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir, args.group )) if not args.skip_kmers: print(\"Output kmer summary\")", "within_group['median'], 'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max':", "within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min':", "'G', 'a': 't', 't': 'a', 'g': 'c', 'c': 'g' }", "sample in SAMPLES: if SAMPLES[sample]['results']: for result in SAMPLES[sample]['results']: row", "if non_zero else 0, 'non_zero_mean': int(round(np.mean(non_zero_array))) if non_zero else 0,", "if c] np_array = np.array(coverage) non_zero_array = np.array(non_zero) return {", "sample, coverage, group, skip_kmers=False, filter_kmers=False): \"\"\"Parse kmer counts.\"\"\" within_group =", "]))) output_handle.write(\"\\n\") def print_kmer_summary(file_output): \"\"\"Print the final per kmer summaries.\"\"\"", "a text file as a list.\"\"\" lines = [] with", "metavar=\"KMERS\", help='Group specific k-mers.') parser.add_argument('coverages', type=str, metavar=\"COVERAGES\", help=('Coverages to subsample", "w/ lef on chromosome SAMPLES[row['accession']]['has_lethal'] = True else: SAMPLES[row['accession']]['has_lethal'] =", "def parse_kmers(kmers, coverages, skip_kmers=False, has_hamming=True): with open(kmers, 'r') as kmer_handle:", "'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ] def get_group_status(sample, group): \"\"\"Return if", "dict(zip(cols, line.split('\\t'))) SAMPLES[row['accession']] = row if row['accession'] == 'NZ_CP009941': #", "coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median':", "'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'], 'group': args.group, 'within_group': result['within_group'], 'total_kmers': total_kmers,", "input_handle: for line in input_handle: lines.append(line.rstrip()) return lines def parse_filter_kmers(kmers):", "for line in kmer_handle: if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\")", "of coverages.\"\"\" non_zero = [c for c in coverage if", "= [ 'kmer', 'simulated_coverage', 'group', 'hamming_distance', 'tp', 'tn', 'fp', 'fn',", "True parse_filter_kmers(args.kmers) else: print(\"Parsing Kmers\") parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers, has_hamming=False if", "path = \"{0}/{1}\".format(args.directory, sample) if os.path.exists(path): print(\"Working on {0} ({1}", "elif group == 'bcg': within_group = True if SAMPLES[sample]['is_bcg'] ==", "= line.split(\"-\") if not has_hamming: distance = False KMERS[kmer] =", "+= 1 else: sample_row['tn'] += 1 coverage_stats = get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({", "as kmer_handle: for line in kmer_handle: if line.startswith(\">\"): line =", "output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\") for kmer, coverages in KMERS.items(): for coverage in", "if args.group not in ['ba', 'bcg', 'lef']: raise Exception(\"GROUPS must", "from collections import OrderedDict import glob import gzip import os", "for sample in samples: path = \"{0}/{1}\".format(args.directory, sample) if os.path.exists(path):", "+= 1 coverage_stats = get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage, 'within_group': within_group,", "= {} HAMMING = OrderedDict() SAMPLE_COLS = [ 'sample', 'is_bcg',", "'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ]", "type=str, metavar=\"COVERAGES\", help=('Coverages to subsample to.')) parser.add_argument('outdir', type=str, metavar=\"OUTDIR\", help='Directory", "genomes.') parser.add_argument('directory', type=str, metavar=\"SIMUALTION_DIR\", help='Directory with group specific 31-mer counts.')", "KMERS[kmer][coverage]['outgroup_coverages'] ) row = { 'kmer': kmer, 'simulated_coverage': coverage, 'group':", "non_zero = [c for c in coverage if c] np_array", "gzip.open(counts, 'r') as count_handle: for line in count_handle: kmer, count", "elif not skip_kmers: if kmer not in KMERS: kmer =", "sample is within a group or not.\"\"\" within_group = None", "SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'], 'group': args.group, 'within_group':", "with open(input_file, 'r') as input_handle: for line in input_handle: lines.append(line.rstrip())", "type=str, metavar=\"OUTDIR\", help='Directory to output to.') parser.add_argument('--cpu', default=1, type=int, metavar=\"INT\",", "in count_files: coverage = os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample, coverage, args.group, skip_kmers=args.skip_kmers,", "count: sample_row['fp'] += 1 else: sample_row['tn'] += 1 coverage_stats =", "'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ] def get_group_status(sample, group): \"\"\"Return", "output_handle.write(\"\\n\") for kmer, coverages in KMERS.items(): for coverage in coverages:", "{ 'group_coverages': [], 'outgroup_coverages': [], 'tp': 0, 'tn': 0, 'fp':", "= True parse_filter_kmers(args.kmers) else: print(\"Parsing Kmers\") parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers, has_hamming=False", "for line in input_handle: lines.append(line.rstrip()) return lines def parse_filter_kmers(kmers): with", "is within a group or not.\"\"\" within_group = None if", "= ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve', description=(\"Summarize kmer counts of each simulation.\")", "bcg or lef).') parser.add_argument('kmers', type=str, metavar=\"KMERS\", help='Group specific k-mers.') parser.add_argument('coverages',", "the simulated sequencing group specific kmer counts.\"\"\" import argparse as", "raise Exception(\"GROUPS must be 'ba', 'bcg' or 'lef'\") coverages =", "os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample, coverage, args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter) print(\"Output sample summary\")", "OrderedDict() HAMMING[kmer] = distance if not skip_kmers: for coverage in", "complement = { 'A': 'T', 'T': 'A', 'G': 'C', 'C':", "for line in summary_handle: line = line.rstrip() if line.startswith('#'): cols", "else False return within_group def get_coverage_stats(coverage): \"\"\"Return summary stats of", "row if row['accession'] == 'NZ_CP009941': # NZ_CP009941 - Bacillus cereus", "sequencing group specific kmer counts.\"\"\" import argparse as ap from", "of cores to use (Default: 1)') parser.add_argument('--single_sample', type=str, metavar=\"STR\", help='Process", "'tp': KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'],", "def get_coverage_stats(coverage): \"\"\"Return summary stats of a set of coverages.\"\"\"", "has_hamming=False if args.group == 'lef' else True) total_kmers = len(KMERS)", "as mp SAMPLES = OrderedDict() KMERS = {} HAMMING =", "counts based on input kmers.') args = parser.parse_args() if args.group", "with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\") for kmer, coverages", "print(\"Parsing Summary\") parse_summary(args.summary) print(\"Parsing Kmers\") if args.filter: print(\"Filtering Kmers\") args.skip_kmers", "'kmer': kmer, 'simulated_coverage': coverage, 'group': args.group, 'hamming_distance': HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'],", "line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") kmer, distance = line.split(\"-\") if", "'r') as kmer_handle: for line in kmer_handle: if line.startswith(\">\"): line", "time import numpy as np import multiprocessing as mp SAMPLES", "'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'], 'group': args.group, 'within_group': result['within_group'],", "as count_handle: for line in count_handle: kmer, count = line.decode().rstrip().split()", "args.outdir, args.group )) if not args.skip_kmers: print(\"Output kmer summary\") if", "'fp': 0, 'fn': 0} with gzip.open(counts, 'r') as count_handle: for", "{ 'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'a':", "file as a list.\"\"\" lines = [] with open(input_file, 'r')", "= get_group_status(sample, group) sample_row = {'coverages': [], 'tp': 0, 'tn':", "if count: sample_row['fp'] += 1 else: sample_row['tn'] += 1 coverage_stats", "#! /usr/bin/env python3 \"\"\"Parse through the simulated sequencing group specific", "KMERS elif not skip_kmers: if kmer not in KMERS: kmer", "coverage, 'group': args.group, 'hamming_distance': HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'], 'fp':", "] def get_group_status(sample, group): \"\"\"Return if a sample is within", "coverages: within_group = get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] ) outgroup = get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages']", "def parse_filter_kmers(kmers): with open(kmers, 'r') as kmer_handle: for line in", "'non_zero_max': max(non_zero_array) if non_zero else 0, } def reverse_complement(seq): \"\"\"Reverse", "if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") KMERS[line.split(\"-\")[0]] = True if", "not in ['ba', 'bcg', 'lef']: raise Exception(\"GROUPS must be 'ba',", "parse_counts(count_file, sample, coverage, args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter) print(\"Output sample summary\") if", "= OrderedDict() HAMMING[kmer] = distance if not skip_kmers: for coverage", "if count: KMERS[kmer][coverage]['tp'] += 1 else: KMERS[kmer][coverage]['fn'] += 1 else:", "outgroup = get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] ) row = { 'kmer': kmer,", "genome_size, description for line in summary_handle: line = line.rstrip() if", "None if group == 'ba': within_group = True if SAMPLES[sample]['is_ba']", "'tp': sample_row['tp'], 'tn': sample_row['tn'], 'fp': sample_row['fp'], 'fn': sample_row['fn'], 'kmer_cov_min': coverage_stats['min'],", "'simulated_coverage', 'group', 'total_kmers', 'tp', 'tn', 'fp', 'fn', 'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median',", "with group specific 31-mer counts.') parser.add_argument('group', type=str, metavar=\"GROUP\", help='Which group", "'non_zero_mean': int(round(np.mean(non_zero_array))) if non_zero else 0, 'non_zero_max': max(non_zero_array) if non_zero", "output_handle.write((\"\\t\".join([ str(row[col]) for col in KMER_COLS ]))) output_handle.write(\"\\n\") def read_lines(input_file):", "'G': 'C', 'C': 'G', 'a': 't', 't': 'a', 'g': 'c',", "parser.parse_args() if args.group not in ['ba', 'bcg', 'lef']: raise Exception(\"GROUPS", "OrderedDict() KMERS = {} HAMMING = OrderedDict() SAMPLE_COLS = [", "parse_filter_kmers(args.kmers) else: print(\"Parsing Kmers\") parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers, has_hamming=False if args.group", "'tn', 'fp', 'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median',", "use (Default: 1)') parser.add_argument('--single_sample', type=str, metavar=\"STR\", help='Process a single sample.')", "args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir, args.group", "args.skip_kmers = True parse_filter_kmers(args.kmers) else: print(\"Parsing Kmers\") parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers,", "os import sys import time import numpy as np import", "parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers, has_hamming=False if args.group == 'lef' else True)", "outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], } output_handle.write((\"\\t\".join([ str(row[col]) for col in KMER_COLS", "'fn': result['fn'], 'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'],", "+= 1 count_files = sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path, args.group) )) for count_file", "'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], } output_handle.write((\"\\t\".join([ str(row[col]) for", "SAMPLES[row['accession']]['results'] = [] def print_sample_summary(file_output): \"\"\"Print the final per sample", "= { 'sample': sample, 'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'],", "'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean',", "not skip_kmers: for coverage in coverages: KMERS[kmer][coverage] = { 'group_coverages':", "import numpy as np import multiprocessing as mp SAMPLES =", "= 1 samples = list(SAMPLES.keys()) if args.single_sample: samples = [args.single_sample]", "output_handle.write(\"\\n\") for sample in SAMPLES: if SAMPLES[sample]['results']: for result in", "\"{0}/{1}\".format(args.directory, sample) if os.path.exists(path): print(\"Working on {0} ({1} of {2})\".format(sample,", "else: sample_row['fn'] += 1 else: if count: sample_row['fp'] += 1", "True if SAMPLES[sample]['is_bcg'] == 'True' else False else: # lef", "result['non_zero_kmer_cov_max'] } output_handle.write((\"\\t\".join([ str(row[col]) for col in SAMPLE_COLS ]))) output_handle.write(\"\\n\")", "help='Group specific k-mers.') parser.add_argument('coverages', type=str, metavar=\"COVERAGES\", help=('Coverages to subsample to.'))", "filter_kmers=False): \"\"\"Parse kmer counts.\"\"\" within_group = get_group_status(sample, group) sample_row =", "'min': min(coverage) if coverage else 0, 'median': int(np.median(np_array)) if coverage", "'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'],", "group == 'ba': within_group = True if SAMPLES[sample]['is_ba'] == 'True'", "= True if SAMPLES[sample]['is_ba'] == 'True' else False elif group", "1 else: if count: sample_row['fp'] += 1 else: sample_row['tn'] +=", "'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'],", "'A', 'G': 'C', 'C': 'G', 'a': 't', 't': 'a', 'g':", "final per sample summaries.\"\"\" with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS)))", "parser.add_argument('--single_sample', type=str, metavar=\"STR\", help='Process a single sample.') parser.add_argument('--skip_kmers', action='store_true', default=False,", "'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ] KMER_COLS = [ 'kmer',", "get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage, 'within_group': within_group, 'tp': sample_row['tp'], 'tn': sample_row['tn'],", "as output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\") for sample in SAMPLES: if SAMPLES[sample]['results']:", "line in summary_handle: line = line.rstrip() if line.startswith('#'): cols =", "'within_group': result['within_group'], 'total_kmers': total_kmers, 'tp': result['tp'], 'tn': result['tn'], 'fp': result['fp'],", "0, 'fp': 0, 'fn': 0 } def parse_summary(summary): \"\"\"Parse Summary", "open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\") for kmer, coverages in", "KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean':", "'ba', 'bcg' or 'lef'\") coverages = read_lines(args.coverages) print(\"Parsing Summary\") parse_summary(args.summary)", "'NZ_CP009941': # NZ_CP009941 - Bacillus cereus w/ lef on chromosome", "if args.single_sample: samples = [args.single_sample] total = len(samples) for sample", "on input kmers.') args = parser.parse_args() if args.group not in", "= read_lines(args.coverages) print(\"Parsing Summary\") parse_summary(args.summary) print(\"Parsing Kmers\") if args.filter: print(\"Filtering", "parser.add_argument('directory', type=str, metavar=\"SIMUALTION_DIR\", help='Directory with group specific 31-mer counts.') parser.add_argument('group',", "output_handle.write(\"\\n\") def print_kmer_summary(file_output): \"\"\"Print the final per kmer summaries.\"\"\" with", "True if filter_kmers: parse = kmer in KMERS or reverse_complement(kmer)", "sample_row['tp'], 'tn': sample_row['tn'], 'fp': sample_row['fp'], 'fn': sample_row['fn'], 'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean':", "'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'],", "len(samples) for sample in samples: path = \"{0}/{1}\".format(args.directory, sample) if", "0} with gzip.open(counts, 'r') as count_handle: for line in count_handle:", "list.\"\"\" lines = [] with open(input_file, 'r') as input_handle: for", "\"\") kmer, distance = line.split(\"-\") if not has_hamming: distance =", "= True if SAMPLES[sample]['is_bcg'] == 'True' else False else: #", "species, genome_size, description for line in summary_handle: line = line.rstrip()", "within_group = True if SAMPLES[sample]['has_lethal'] else False return within_group def", "KMERS[kmer][coverage] = { 'group_coverages': [], 'outgroup_coverages': [], 'tp': 0, 'tn':", "= np.array(coverage) non_zero_array = np.array(non_zero) return { 'min': min(coverage) if", "total_kmers, 'tp': result['tp'], 'tn': result['tn'], 'fp': result['fp'], 'fn': result['fn'], 'kmer_cov_min':", "parser.add_argument('outdir', type=str, metavar=\"OUTDIR\", help='Directory to output to.') parser.add_argument('--cpu', default=1, type=int,", "= os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample, coverage, args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter) print(\"Output sample", "= True if SAMPLES[sample]['has_lethal'] else False return within_group def get_coverage_stats(coverage):", "False SAMPLES[row['accession']]['results'] = [] def print_sample_summary(file_output): \"\"\"Print the final per", "1 if parse: sample_row['coverages'].append(count) if within_group: if count: sample_row['tp'] +=", "outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median':", "outgroup['non_zero_max'], } output_handle.write((\"\\t\".join([ str(row[col]) for col in KMER_COLS ]))) output_handle.write(\"\\n\")", "'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], } output_handle.write((\"\\t\".join([ str(row[col]) for col in KMER_COLS ])))", "parse_filter_kmers(kmers): with open(kmers, 'r') as kmer_handle: for line in kmer_handle:", "help='Filter counts based on input kmers.') args = parser.parse_args() if", "sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path, args.group) )) for count_file in count_files: coverage =", "str(row[col]) for col in KMER_COLS ]))) output_handle.write(\"\\n\") def read_lines(input_file): \"\"\"Return", "for kmer, coverages in KMERS.items(): for coverage in coverages: within_group", "line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") KMERS[line.split(\"-\")[0]] = True if __name__", "counts of each simulation.\") ) parser.add_argument('summary', type=str, metavar=\"SUMMARY\", help='Summary of", "KMERS.items(): for coverage in coverages: within_group = get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] )", "'is_bcg', 'is_ba', 'has_lethal', 'simulated_coverage', 'group', 'total_kmers', 'tp', 'tn', 'fp', 'fn',", "'simulated_coverage', 'group', 'hamming_distance', 'tp', 'tn', 'fp', 'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median',", "result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] } output_handle.write((\"\\t\".join([ str(row[col]) for col in SAMPLE_COLS", "kmer_handle: if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") KMERS[line.split(\"-\")[0]] = True", "conflict_handler='resolve', description=(\"Summarize kmer counts of each simulation.\") ) parser.add_argument('summary', type=str,", "kmer, coverages in KMERS.items(): for coverage in coverages: within_group =", "line.split(\"-\") if not has_hamming: distance = False KMERS[kmer] = OrderedDict()", "result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] }", "Summary\") parse_summary(args.summary) print(\"Parsing Kmers\") if args.filter: print(\"Filtering Kmers\") args.skip_kmers =", "KMERS[kmer][coverage]['fn'] += 1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count: KMERS[kmer][coverage]['fp'] += 1", "with gzip.open(counts, 'r') as count_handle: for line in count_handle: kmer,", "coverage else 0, 'max': max(coverage) if coverage else 0, 'non_zero_min':", "'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median',", "'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ] def", "kmer, distance = line.split(\"-\") if not has_hamming: distance = False", "\"\"\"Return if a sample is within a group or not.\"\"\"", "0, 'non_zero_median': int(np.median(non_zero_array)) if non_zero else 0, 'non_zero_mean': int(round(np.mean(non_zero_array))) if", "current, total)) current += 1 count_files = sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path, args.group)", "} output_handle.write((\"\\t\".join([ str(row[col]) for col in KMER_COLS ]))) output_handle.write(\"\\n\") def", "row = { 'kmer': kmer, 'simulated_coverage': coverage, 'group': args.group, 'hamming_distance':", "if count: sample_row['tp'] += 1 else: sample_row['fn'] += 1 else:", "count_file in count_files: coverage = os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample, coverage, args.group,", "'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] } output_handle.write((\"\\t\".join([ str(row[col]) for", "'lef'\") coverages = read_lines(args.coverages) print(\"Parsing Summary\") parse_summary(args.summary) print(\"Parsing Kmers\") if", "# NZ_CP009941 - Bacillus cereus w/ lef on chromosome SAMPLES[row['accession']]['has_lethal']", "'max': max(coverage) if coverage else 0, 'non_zero_min': min(non_zero_array) if non_zero", "'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'],", "# Column Names: # accession, gi, is_bcg, is_ba, species, genome_size,", "for coverage in coverages: within_group = get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] ) outgroup", "\"\"\"Print the final per kmer summaries.\"\"\" with open(file_output, 'w') as", "NZ_CP009941 - Bacillus cereus w/ lef on chromosome SAMPLES[row['accession']]['has_lethal'] =", "np.array(non_zero) return { 'min': min(coverage) if coverage else 0, 'median':", "= [args.single_sample] total = len(samples) for sample in samples: path", "within a group or not.\"\"\" within_group = None if group", "= True if filter_kmers: parse = kmer in KMERS or", "= np.array(non_zero) return { 'min': min(coverage) if coverage else 0,", "open(input_file, 'r') as input_handle: for line in input_handle: lines.append(line.rstrip()) return", "= get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage, 'within_group': within_group, 'tp': sample_row['tp'], 'tn':", "os.path.exists(path): print(\"Working on {0} ({1} of {2})\".format(sample, current, total)) current", "else: KMERS[kmer][coverage]['fn'] += 1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count: KMERS[kmer][coverage]['fp'] +=", "0, 'fp': 0, 'fn': 0} with gzip.open(counts, 'r') as count_handle:", "a list.\"\"\" lines = [] with open(input_file, 'r') as input_handle:", "KMERS[line.split(\"-\")[0]] = True if __name__ == '__main__': parser = ap.ArgumentParser(", "'non_zero_kmer_cov_max' ] KMER_COLS = [ 'kmer', 'simulated_coverage', 'group', 'hamming_distance', 'tp',", "'total_kmers': total_kmers, 'tp': result['tp'], 'tn': result['tn'], 'fp': result['fp'], 'fn': result['fn'],", "args.group, 'hamming_distance': HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'], 'fn':", "to parse (ba, bcg or lef).') parser.add_argument('kmers', type=str, metavar=\"KMERS\", help='Group", "args.group, 'within_group': result['within_group'], 'total_kmers': total_kmers, 'tp': result['tp'], 'tn': result['tn'], 'fp':", "in SAMPLE_COLS ]))) output_handle.write(\"\\n\") def print_kmer_summary(file_output): \"\"\"Print the final per", "chromosome SAMPLES[row['accession']]['has_lethal'] = True else: SAMPLES[row['accession']]['has_lethal'] = False SAMPLES[row['accession']]['results'] =", "to.')) parser.add_argument('outdir', type=str, metavar=\"OUTDIR\", help='Directory to output to.') parser.add_argument('--cpu', default=1,", "if non_zero else 0, } def reverse_complement(seq): \"\"\"Reverse complement a", "simulated sequencing group specific kmer counts.\"\"\" import argparse as ap", "for sample in SAMPLES: if SAMPLES[sample]['results']: for result in SAMPLES[sample]['results']:", "= get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] ) outgroup = get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] ) row", "kmers.') args = parser.parse_args() if args.group not in ['ba', 'bcg',", "within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean':", "'outgroup_coverages': [], 'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0", "0, 'non_zero_min': min(non_zero_array) if non_zero else 0, 'non_zero_median': int(np.median(non_zero_array)) if", "import glob import gzip import os import sys import time", "{ 'min': min(coverage) if coverage else 0, 'median': int(np.median(np_array)) if", "result['within_group'], 'total_kmers': total_kmers, 'tp': result['tp'], 'tn': result['tn'], 'fp': result['fp'], 'fn':", "Kmers\") if args.filter: print(\"Filtering Kmers\") args.skip_kmers = True parse_filter_kmers(args.kmers) else:", "coverages.\"\"\" non_zero = [c for c in coverage if c]", "'tp', 'tn', 'fp', 'fn', 'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean',", "read_lines(input_file): \"\"\"Return lines in a text file as a list.\"\"\"", "in SAMPLES: if SAMPLES[sample]['results']: for result in SAMPLES[sample]['results']: row =", "print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else: print_kmer_summary(\"{0}/count-summary-kmer-{1}.txt\".format( args.outdir, args.group ))", "'tn': sample_row['tn'], 'fp': sample_row['fp'], 'fn': sample_row['fn'], 'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'],", "through the simulated sequencing group specific kmer counts.\"\"\" import argparse", "\"\") KMERS[line.split(\"-\")[0]] = True if __name__ == '__main__': parser =", "__name__ == '__main__': parser = ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve', description=(\"Summarize kmer", "else 0, 'non_zero_max': max(non_zero_array) if non_zero else 0, } def", "return { 'min': min(coverage) if coverage else 0, 'median': int(np.median(np_array))", "description=(\"Summarize kmer counts of each simulation.\") ) parser.add_argument('summary', type=str, metavar=\"SUMMARY\",", "= len(KMERS) current = 1 samples = list(SAMPLES.keys()) if args.single_sample:", "gzip import os import sys import time import numpy as", "'sample': sample, 'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'],", "in kmer_handle: if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") KMERS[line.split(\"-\")[0]] =", "coverages, skip_kmers=False, has_hamming=True): with open(kmers, 'r') as kmer_handle: for line", "per sample summaries.\"\"\" with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\")", "'hamming_distance', 'tp', 'tn', 'fp', 'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min',", "lines = [] with open(input_file, 'r') as input_handle: for line", "line = line.rstrip().replace(\">\", \"\") KMERS[line.split(\"-\")[0]] = True if __name__ ==", "OrderedDict import glob import gzip import os import sys import", "= { 'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G',", "within_group: if count: sample_row['tp'] += 1 else: sample_row['fn'] += 1", "HAMMING = OrderedDict() SAMPLE_COLS = [ 'sample', 'is_bcg', 'is_ba', 'has_lethal',", "KMERS = {} HAMMING = OrderedDict() SAMPLE_COLS = [ 'sample',", "'group': args.group, 'within_group': result['within_group'], 'total_kmers': total_kmers, 'tp': result['tp'], 'tn': result['tn'],", "'tp': result['tp'], 'tn': result['tn'], 'fp': result['fp'], 'fn': result['fn'], 'kmer_cov_min': result['kmer_cov_min'],", "'kmer', 'simulated_coverage', 'group', 'hamming_distance', 'tp', 'tn', 'fp', 'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean',", "kmer processing.') parser.add_argument('--filter', action='store_true', default=False, help='Filter counts based on input", "'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'],", "file.\"\"\" cols = None with open(summary, 'r') as summary_handle: #", ") outgroup = get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] ) row = { 'kmer':", "def read_lines(input_file): \"\"\"Return lines in a text file as a", ") row = { 'kmer': kmer, 'simulated_coverage': coverage, 'group': args.group,", "parser = ap.ArgumentParser( prog='summarize-kmer-counts.py', conflict_handler='resolve', description=(\"Summarize kmer counts of each", "'C', 'C': 'G', 'a': 't', 't': 'a', 'g': 'c', 'c':", "import argparse as ap from collections import OrderedDict import glob", "row = dict(zip(cols, line.split('\\t'))) SAMPLES[row['accession']] = row if row['accession'] ==", "np.array(coverage) non_zero_array = np.array(non_zero) return { 'min': min(coverage) if coverage", "'lef']: raise Exception(\"GROUPS must be 'ba', 'bcg' or 'lef'\") coverages", "[], 'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0 }", "1 else: sample_row['fn'] += 1 else: if count: sample_row['fp'] +=", "coverage_stats['non_zero_median'], 'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], }) def parse_kmers(kmers, coverages, skip_kmers=False, has_hamming=True): with", "1)') parser.add_argument('--single_sample', type=str, metavar=\"STR\", help='Process a single sample.') parser.add_argument('--skip_kmers', action='store_true',", "SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage, 'within_group': within_group, 'tp': sample_row['tp'], 'tn': sample_row['tn'], 'fp':", "SAMPLES[row['accession']]['has_lethal'] = False SAMPLES[row['accession']]['results'] = [] def print_sample_summary(file_output): \"\"\"Print the", "'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'],", "to subsample to.')) parser.add_argument('outdir', type=str, metavar=\"OUTDIR\", help='Directory to output to.')", "'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ] KMER_COLS = [", "'simulated_coverage': result['simulated_coverage'], 'group': args.group, 'within_group': result['within_group'], 'total_kmers': total_kmers, 'tp': result['tp'],", "else 0, 'non_zero_mean': int(round(np.mean(non_zero_array))) if non_zero else 0, 'non_zero_max': max(non_zero_array)", "of {2})\".format(sample, current, total)) current += 1 count_files = sorted(glob.glob(", "sample_row['fn'], 'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min':", "if row['accession'] == 'NZ_CP009941': # NZ_CP009941 - Bacillus cereus w/", "= False SAMPLES[row['accession']]['results'] = [] def print_sample_summary(file_output): \"\"\"Print the final", "'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max']", "kmer, count = line.decode().rstrip().split() count = int(count) parse = True", "'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ] def get_group_status(sample, group): \"\"\"Return if a", "skip_kmers=False, filter_kmers=False): \"\"\"Parse kmer counts.\"\"\" within_group = get_group_status(sample, group) sample_row", "in KMERS: kmer = reverse_complement(kmer) if within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if count:", "on {0} ({1} of {2})\".format(sample, current, total)) current += 1", "open(summary, 'r') as summary_handle: # Column Names: # accession, gi,", "count: KMERS[kmer][coverage]['fp'] += 1 else: KMERS[kmer][coverage]['tn'] += 1 if parse:", "SAMPLES[sample]['is_bcg'] == 'True' else False else: # lef within_group =", "summary stats of a set of coverages.\"\"\" non_zero = [c", "not has_hamming: distance = False KMERS[kmer] = OrderedDict() HAMMING[kmer] =", "'fp': sample_row['fp'], 'fn': sample_row['fn'], 'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'],", "result['fp'], 'fn': result['fn'], 'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max':", "import gzip import os import sys import time import numpy", "count = int(count) parse = True if filter_kmers: parse =", "]))) output_handle.write(\"\\n\") def read_lines(input_file): \"\"\"Return lines in a text file", "Exception(\"GROUPS must be 'ba', 'bcg' or 'lef'\") coverages = read_lines(args.coverages)", "or 'lef'\") coverages = read_lines(args.coverages) print(\"Parsing Summary\") parse_summary(args.summary) print(\"Parsing Kmers\")", "count_files: coverage = os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample, coverage, args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter)", "the final per sample summaries.\"\"\" with open(file_output, 'w') as output_handle:", "in KMERS or reverse_complement(kmer) in KMERS elif not skip_kmers: if", "'fn': 0 } def parse_summary(summary): \"\"\"Parse Summary file.\"\"\" cols =", "= line.rstrip() if line.startswith('#'): cols = line.replace('#', '').split('\\t') else: row", "if kmer not in KMERS: kmer = reverse_complement(kmer) if within_group:", "DNA sequence.\"\"\" complement = { 'A': 'T', 'T': 'A', 'G':", "lef within_group = True if SAMPLES[sample]['has_lethal'] else False return within_group", "type=str, metavar=\"SUMMARY\", help='Summary of Bacillus genomes.') parser.add_argument('directory', type=str, metavar=\"SIMUALTION_DIR\", help='Directory", "Column Names: # accession, gi, is_bcg, is_ba, species, genome_size, description", "= OrderedDict() SAMPLE_COLS = [ 'sample', 'is_bcg', 'is_ba', 'has_lethal', 'simulated_coverage',", "parser.add_argument('--filter', action='store_true', default=False, help='Filter counts based on input kmers.') args", "summary\") if args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else: print_kmer_summary(\"{0}/count-summary-kmer-{1}.txt\".format(", "1 else: KMERS[kmer][coverage]['tn'] += 1 if parse: sample_row['coverages'].append(count) if within_group:", "ap from collections import OrderedDict import glob import gzip import", "= distance if not skip_kmers: for coverage in coverages: KMERS[kmer][coverage]", "group, skip_kmers=False, filter_kmers=False): \"\"\"Parse kmer counts.\"\"\" within_group = get_group_status(sample, group)", "'non_zero_kmer_cov_max': coverage_stats['non_zero_max'], }) def parse_kmers(kmers, coverages, skip_kmers=False, has_hamming=True): with open(kmers,", "count_handle: kmer, count = line.decode().rstrip().split() count = int(count) parse =", "group specific kmer counts.\"\"\" import argparse as ap from collections", "get_group_status(sample, group) sample_row = {'coverages': [], 'tp': 0, 'tn': 0,", "SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'], 'group': args.group, 'within_group': result['within_group'], 'total_kmers': total_kmers, 'tp':", "glob import gzip import os import sys import time import", "get_group_status(sample, group): \"\"\"Return if a sample is within a group", "args.group) )) for count_file in count_files: coverage = os.path.basename(count_file).split('-')[1] parse_counts(count_file,", "} output_handle.write((\"\\t\".join([ str(row[col]) for col in SAMPLE_COLS ]))) output_handle.write(\"\\n\") def", "as input_handle: for line in input_handle: lines.append(line.rstrip()) return lines def", "min(coverage) if coverage else 0, 'median': int(np.median(np_array)) if coverage else", "def parse_counts(counts, sample, coverage, group, skip_kmers=False, filter_kmers=False): \"\"\"Parse kmer counts.\"\"\"", "'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ] KMER_COLS = [ 'kmer', 'simulated_coverage',", "lef on chromosome SAMPLES[row['accession']]['has_lethal'] = True else: SAMPLES[row['accession']]['has_lethal'] = False", "True) total_kmers = len(KMERS) current = 1 samples = list(SAMPLES.keys())", "'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'],", "as summary_handle: # Column Names: # accession, gi, is_bcg, is_ba,", "else 0, 'mean': \"{0:.4f}\".format(np.mean(np_array)) if coverage else 0, 'max': max(coverage)", "sample in samples: path = \"{0}/{1}\".format(args.directory, sample) if os.path.exists(path): print(\"Working", "0, 'non_zero_mean': int(round(np.mean(non_zero_array))) if non_zero else 0, 'non_zero_max': max(non_zero_array) if", "else: row = dict(zip(cols, line.split('\\t'))) SAMPLES[row['accession']] = row if row['accession']", "count: KMERS[kmer][coverage]['tp'] += 1 else: KMERS[kmer][coverage]['fn'] += 1 else: KMERS[kmer][coverage]['outgroup_coverages'].append(count)", "max(coverage) if coverage else 0, 'non_zero_min': min(non_zero_array) if non_zero else", "\"\"\"Parse Summary file.\"\"\" cols = None with open(summary, 'r') as", "== 'True' else False elif group == 'bcg': within_group =", "counts.\"\"\" within_group = get_group_status(sample, group) sample_row = {'coverages': [], 'tp':", "import multiprocessing as mp SAMPLES = OrderedDict() KMERS = {}", "'group', 'total_kmers', 'tp', 'tn', 'fp', 'fn', 'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max',", "cols = line.replace('#', '').split('\\t') else: row = dict(zip(cols, line.split('\\t'))) SAMPLES[row['accession']]", "1 else: sample_row['tn'] += 1 coverage_stats = get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage':", "'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'],", "'r') as summary_handle: # Column Names: # accession, gi, is_bcg,", "read_lines(args.coverages) print(\"Parsing Summary\") parse_summary(args.summary) print(\"Parsing Kmers\") if args.filter: print(\"Filtering Kmers\")", "+= 1 else: sample_row['fn'] += 1 else: if count: sample_row['fp']", "else: if count: sample_row['fp'] += 1 else: sample_row['tn'] += 1", "type=str, metavar=\"GROUP\", help='Which group to parse (ba, bcg or lef).')", "else 0, } def reverse_complement(seq): \"\"\"Reverse complement a DNA sequence.\"\"\"", "'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'], 'group': args.group,", "max(non_zero_array) if non_zero else 0, } def reverse_complement(seq): \"\"\"Reverse complement", "= int(count) parse = True if filter_kmers: parse = kmer", "def print_sample_summary(file_output): \"\"\"Print the final per sample summaries.\"\"\" with open(file_output,", "within_group['min'], 'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean':", "'r') as count_handle: for line in count_handle: kmer, count =", "within_group = get_group_status(sample, group) sample_row = {'coverages': [], 'tp': 0,", "= reverse_complement(kmer) if within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if count: KMERS[kmer][coverage]['tp'] += 1", "{ 'sample': sample, 'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage':", "'lef' else True) total_kmers = len(KMERS) current = 1 samples", "output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\") for sample in SAMPLES: if SAMPLES[sample]['results']: for", "or not.\"\"\" within_group = None if group == 'ba': within_group", "to.') parser.add_argument('--cpu', default=1, type=int, metavar=\"INT\", help='Number of cores to use", "'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max', 'outgroup_kmer_cov_min', 'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max',", "['ba', 'bcg', 'lef']: raise Exception(\"GROUPS must be 'ba', 'bcg' or", "= [c for c in coverage if c] np_array =", "outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], } output_handle.write((\"\\t\".join([ str(row[col]) for col", "if SAMPLES[sample]['is_bcg'] == 'True' else False else: # lef within_group", "coverages: KMERS[kmer][coverage] = { 'group_coverages': [], 'outgroup_coverages': [], 'tp': 0,", "def print_kmer_summary(file_output): \"\"\"Print the final per kmer summaries.\"\"\" with open(file_output,", "of a set of coverages.\"\"\" non_zero = [c for c", "Bacillus genomes.') parser.add_argument('directory', type=str, metavar=\"SIMUALTION_DIR\", help='Directory with group specific 31-mer", "within_group = None if group == 'ba': within_group = True", "in samples: path = \"{0}/{1}\".format(args.directory, sample) if os.path.exists(path): print(\"Working on", "'outgroup_kmer_cov_mean', 'outgroup_kmer_cov_median', 'outgroup_kmer_cov_max', 'non_zero_outgroup_kmer_cov_min', 'non_zero_outgroup_kmer_cov_mean', 'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ] def get_group_status(sample,", "print_sample_summary(file_output): \"\"\"Print the final per sample summaries.\"\"\" with open(file_output, 'w')", "kmer summaries.\"\"\" with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\") for", "metavar=\"INT\", help='Number of cores to use (Default: 1)') parser.add_argument('--single_sample', type=str,", "action='store_true', default=False, help='Skip kmer processing.') parser.add_argument('--filter', action='store_true', default=False, help='Filter counts", "sample) if os.path.exists(path): print(\"Working on {0} ({1} of {2})\".format(sample, current,", "0, 'fn': 0} with gzip.open(counts, 'r') as count_handle: for line", "'group_coverages': [], 'outgroup_coverages': [], 'tp': 0, 'tn': 0, 'fp': 0,", "subsample to.')) parser.add_argument('outdir', type=str, metavar=\"OUTDIR\", help='Directory to output to.') parser.add_argument('--cpu',", "coverage else 0, 'mean': \"{0:.4f}\".format(np.mean(np_array)) if coverage else 0, 'max':", "'c': 'g' } return ''.join([complement[b] for b in seq[::-1]]) def", "min(non_zero_array) if non_zero else 0, 'non_zero_median': int(np.median(non_zero_array)) if non_zero else", "as output_handle: output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\") for kmer, coverages in KMERS.items(): for", "'ba': within_group = True if SAMPLES[sample]['is_ba'] == 'True' else False", "non_zero else 0, 'non_zero_mean': int(round(np.mean(non_zero_array))) if non_zero else 0, 'non_zero_max':", "\"\"\"Parse kmer counts.\"\"\" within_group = get_group_status(sample, group) sample_row = {'coverages':", "skip_kmers=False, has_hamming=True): with open(kmers, 'r') as kmer_handle: for line in", "'simulated_coverage': coverage, 'group': args.group, 'hamming_distance': HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'],", "import time import numpy as np import multiprocessing as mp", "in coverages: within_group = get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] ) outgroup = get_coverage_stats(", "result['tp'], 'tn': result['tn'], 'fp': result['fp'], 'fn': result['fn'], 'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean':", "'fn', 'kmer_cov_min', 'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ]", "parse: sample_row['coverages'].append(count) if within_group: if count: sample_row['tp'] += 1 else:", "cereus w/ lef on chromosome SAMPLES[row['accession']]['has_lethal'] = True else: SAMPLES[row['accession']]['has_lethal']", "'w') as output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\") for sample in SAMPLES: if", "prog='summarize-kmer-counts.py', conflict_handler='resolve', description=(\"Summarize kmer counts of each simulation.\") ) parser.add_argument('summary',", "print(\"Parsing Kmers\") if args.filter: print(\"Filtering Kmers\") args.skip_kmers = True parse_filter_kmers(args.kmers)", "'non_zero_outgroup_kmer_cov_median', 'non_zero_outgroup_kmer_cov_max' ] def get_group_status(sample, group): \"\"\"Return if a sample", "coverage in coverages: KMERS[kmer][coverage] = { 'group_coverages': [], 'outgroup_coverages': [],", "coverages = read_lines(args.coverages) print(\"Parsing Summary\") parse_summary(args.summary) print(\"Parsing Kmers\") if args.filter:", "if os.path.exists(path): print(\"Working on {0} ({1} of {2})\".format(sample, current, total))", "collections import OrderedDict import glob import gzip import os import", "with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\") for sample in", ")) for count_file in count_files: coverage = os.path.basename(count_file).split('-')[1] parse_counts(count_file, sample,", "int(np.median(non_zero_array)) if non_zero else 0, 'non_zero_mean': int(round(np.mean(non_zero_array))) if non_zero else", "None with open(summary, 'r') as summary_handle: # Column Names: #", "distance = False KMERS[kmer] = OrderedDict() HAMMING[kmer] = distance if", "count = line.decode().rstrip().split() count = int(count) parse = True if", "args.group )) if not args.skip_kmers: print(\"Output kmer summary\") if args.single_sample:", "args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter) print(\"Output sample summary\") if args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir,", "sample_row['fp'], 'fn': sample_row['fn'], 'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max':", "gi, is_bcg, is_ba, species, genome_size, description for line in summary_handle:", "= [ 'sample', 'is_bcg', 'is_ba', 'has_lethal', 'simulated_coverage', 'group', 'total_kmers', 'tp',", "'g': 'c', 'c': 'g' } return ''.join([complement[b] for b in", "get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] ) row = { 'kmer': kmer, 'simulated_coverage': coverage,", "Kmers\") args.skip_kmers = True parse_filter_kmers(args.kmers) else: print(\"Parsing Kmers\") parse_kmers(args.kmers, coverages,", "parse = kmer in KMERS or reverse_complement(kmer) in KMERS elif", "summaries.\"\"\" with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(KMER_COLS))) output_handle.write(\"\\n\") for kmer,", "metavar=\"OUTDIR\", help='Directory to output to.') parser.add_argument('--cpu', default=1, type=int, metavar=\"INT\", help='Number", "coverage_stats['non_zero_max'], }) def parse_kmers(kmers, coverages, skip_kmers=False, has_hamming=True): with open(kmers, 'r')", "if args.filter: print(\"Filtering Kmers\") args.skip_kmers = True parse_filter_kmers(args.kmers) else: print(\"Parsing", "'kmer_cov_mean', 'kmer_cov_median', 'kmer_cov_max', 'non_zero_kmer_cov_min', 'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ] KMER_COLS =", "group specific 31-mer counts.') parser.add_argument('group', type=str, metavar=\"GROUP\", help='Which group to", "HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min':", "KMERS[kmer][coverage]['group_coverages'].append(count) if count: KMERS[kmer][coverage]['tp'] += 1 else: KMERS[kmer][coverage]['fn'] += 1", "\"{0:.4f}\".format(np.mean(np_array)) if coverage else 0, 'max': max(coverage) if coverage else", "'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'],", "python3 \"\"\"Parse through the simulated sequencing group specific kmer counts.\"\"\"", "{0} ({1} of {2})\".format(sample, current, total)) current += 1 count_files", "result['simulated_coverage'], 'group': args.group, 'within_group': result['within_group'], 'total_kmers': total_kmers, 'tp': result['tp'], 'tn':", "count_files = sorted(glob.glob( \"{0}/*-{1}.txt.gz\".format(path, args.group) )) for count_file in count_files:", "help='Process a single sample.') parser.add_argument('--skip_kmers', action='store_true', default=False, help='Skip kmer processing.')", "coverage if c] np_array = np.array(coverage) non_zero_array = np.array(non_zero) return", "kmer not in KMERS: kmer = reverse_complement(kmer) if within_group: KMERS[kmer][coverage]['group_coverages'].append(count)", "parse (ba, bcg or lef).') parser.add_argument('kmers', type=str, metavar=\"KMERS\", help='Group specific", "coverage, 'within_group': within_group, 'tp': sample_row['tp'], 'tn': sample_row['tn'], 'fp': sample_row['fp'], 'fn':", "if non_zero else 0, 'non_zero_max': max(non_zero_array) if non_zero else 0,", "row['accession'] == 'NZ_CP009941': # NZ_CP009941 - Bacillus cereus w/ lef", "'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ] KMER_COLS = [ 'kmer', 'simulated_coverage', 'group', 'hamming_distance',", "# lef within_group = True if SAMPLES[sample]['has_lethal'] else False return", "1 coverage_stats = get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage, 'within_group': within_group, 'tp':", "'non_zero_median': int(np.median(non_zero_array)) if non_zero else 0, 'non_zero_mean': int(round(np.mean(non_zero_array))) if non_zero", "kmer in KMERS or reverse_complement(kmer) in KMERS elif not skip_kmers:", "type=str, metavar=\"STR\", help='Process a single sample.') parser.add_argument('--skip_kmers', action='store_true', default=False, help='Skip", "Kmers\") parse_kmers(args.kmers, coverages, skip_kmers=args.skip_kmers, has_hamming=False if args.group == 'lef' else", "'hamming_distance': HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'],", "counts.\"\"\" import argparse as ap from collections import OrderedDict import", "'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'a': 't',", "summary_handle: # Column Names: # accession, gi, is_bcg, is_ba, species,", "SAMPLES[row['accession']]['has_lethal'] = True else: SAMPLES[row['accession']]['has_lethal'] = False SAMPLES[row['accession']]['results'] = []", "group to parse (ba, bcg or lef).') parser.add_argument('kmers', type=str, metavar=\"KMERS\",", "filter_kmers=args.filter) print(\"Output sample summary\") if args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group", "'non_zero_kmer_cov_mean', 'non_zero_kmer_cov_median', 'non_zero_kmer_cov_max' ] KMER_COLS = [ 'kmer', 'simulated_coverage', 'group',", "if within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if count: KMERS[kmer][coverage]['tp'] += 1 else: KMERS[kmer][coverage]['fn']", "= line.decode().rstrip().split() count = int(count) parse = True if filter_kmers:", "if coverage else 0, 'max': max(coverage) if coverage else 0,", "for line in count_handle: kmer, count = line.decode().rstrip().split() count =", "else False else: # lef within_group = True if SAMPLES[sample]['has_lethal']", "sample, 'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'], 'group':", ")) else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir, args.group )) if not args.skip_kmers: print(\"Output", "in seq[::-1]]) def parse_counts(counts, sample, coverage, group, skip_kmers=False, filter_kmers=False): \"\"\"Parse", "'group', 'hamming_distance', 'tp', 'tn', 'fp', 'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max',", "0, 'non_zero_max': max(non_zero_array) if non_zero else 0, } def reverse_complement(seq):", "cores to use (Default: 1)') parser.add_argument('--single_sample', type=str, metavar=\"STR\", help='Process a", "stats of a set of coverages.\"\"\" non_zero = [c for", "'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] } output_handle.write((\"\\t\".join([ str(row[col]) for col in", "simulation.\") ) parser.add_argument('summary', type=str, metavar=\"SUMMARY\", help='Summary of Bacillus genomes.') parser.add_argument('directory',", "samples = list(SAMPLES.keys()) if args.single_sample: samples = [args.single_sample] total =", "in ['ba', 'bcg', 'lef']: raise Exception(\"GROUPS must be 'ba', 'bcg'", "print(\"Output kmer summary\") if args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group ))", "'fp': result['fp'], 'fn': result['fn'], 'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'],", "args.group == 'lef' else True) total_kmers = len(KMERS) current =", "metavar=\"GROUP\", help='Which group to parse (ba, bcg or lef).') parser.add_argument('kmers',", "'a', 'g': 'c', 'c': 'g' } return ''.join([complement[b] for b", "in KMERS.items(): for coverage in coverages: within_group = get_coverage_stats( KMERS[kmer][coverage]['group_coverages']", "help='Directory with group specific 31-mer counts.') parser.add_argument('group', type=str, metavar=\"GROUP\", help='Which", "result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median': result['non_zero_kmer_cov_median'], 'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] } output_handle.write((\"\\t\".join([ str(row[col])", "within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median':", "not args.skip_kmers: print(\"Output kmer summary\") if args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir, args.single_sample,", "output_handle.write((\"\\t\".join([ str(row[col]) for col in SAMPLE_COLS ]))) output_handle.write(\"\\n\") def print_kmer_summary(file_output):", "samples = [args.single_sample] total = len(samples) for sample in samples:", "= None if group == 'ba': within_group = True if", "accession, gi, is_bcg, is_ba, species, genome_size, description for line in", "'t': 'a', 'g': 'c', 'c': 'g' } return ''.join([complement[b] for", "reverse_complement(kmer) if within_group: KMERS[kmer][coverage]['group_coverages'].append(count) if count: KMERS[kmer][coverage]['tp'] += 1 else:", "''.join([complement[b] for b in seq[::-1]]) def parse_counts(counts, sample, coverage, group,", "numpy as np import multiprocessing as mp SAMPLES = OrderedDict()", "\"\"\"Print the final per sample summaries.\"\"\" with open(file_output, 'w') as", "KMERS[kmer][coverage]['group_coverages'] ) outgroup = get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] ) row = {", "total_kmers = len(KMERS) current = 1 samples = list(SAMPLES.keys()) if", "multiprocessing as mp SAMPLES = OrderedDict() KMERS = {} HAMMING", "c in coverage if c] np_array = np.array(coverage) non_zero_array =", "0, } def reverse_complement(seq): \"\"\"Reverse complement a DNA sequence.\"\"\" complement", "is_bcg, is_ba, species, genome_size, description for line in summary_handle: line", "kmer counts of each simulation.\") ) parser.add_argument('summary', type=str, metavar=\"SUMMARY\", help='Summary", "Bacillus cereus w/ lef on chromosome SAMPLES[row['accession']]['has_lethal'] = True else:", "'tn': result['tn'], 'fp': result['fp'], 'fn': result['fn'], 'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'],", "row = { 'sample': sample, 'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba': SAMPLES[sample]['is_ba'], 'has_lethal':", "else: KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count: KMERS[kmer][coverage]['fp'] += 1 else: KMERS[kmer][coverage]['tn'] +=", "within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min':", "sample_row['fp'] += 1 else: sample_row['tn'] += 1 coverage_stats = get_coverage_stats(sample_row['coverages'])", "kmer counts.\"\"\" within_group = get_group_status(sample, group) sample_row = {'coverages': [],", "{'coverages': [], 'tp': 0, 'tn': 0, 'fp': 0, 'fn': 0}", "within_group = get_coverage_stats( KMERS[kmer][coverage]['group_coverages'] ) outgroup = get_coverage_stats( KMERS[kmer][coverage]['outgroup_coverages'] )", "'fp', 'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean', 'non_zero_group_kmer_cov_median', 'non_zero_group_kmer_cov_max',", "'T': 'A', 'G': 'C', 'C': 'G', 'a': 't', 't': 'a',", "args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else: print_kmer_summary(\"{0}/count-summary-kmer-{1}.txt\".format( args.outdir, args.group", "total = len(samples) for sample in samples: path = \"{0}/{1}\".format(args.directory,", "= line.rstrip().replace(\">\", \"\") kmer, distance = line.split(\"-\") if not has_hamming:", "of Bacillus genomes.') parser.add_argument('directory', type=str, metavar=\"SIMUALTION_DIR\", help='Directory with group specific", "'non_zero_kmer_cov_max': result['non_zero_kmer_cov_max'] } output_handle.write((\"\\t\".join([ str(row[col]) for col in SAMPLE_COLS ])))", "'outgroup_kmer_cov_mean': outgroup['mean'], 'outgroup_kmer_cov_median': outgroup['median'], 'outgroup_kmer_cov_max': outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'],", "KMER_COLS ]))) output_handle.write(\"\\n\") def read_lines(input_file): \"\"\"Return lines in a text", "output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\") for sample in SAMPLES: if SAMPLES[sample]['results']: for result", "return ''.join([complement[b] for b in seq[::-1]]) def parse_counts(counts, sample, coverage,", "kmer counts.\"\"\" import argparse as ap from collections import OrderedDict", "/usr/bin/env python3 \"\"\"Parse through the simulated sequencing group specific kmer", "if not skip_kmers: for coverage in coverages: KMERS[kmer][coverage] = {", "type=int, metavar=\"INT\", help='Number of cores to use (Default: 1)') parser.add_argument('--single_sample',", "default=False, help='Filter counts based on input kmers.') args = parser.parse_args()", "if parse: sample_row['coverages'].append(count) if within_group: if count: sample_row['tp'] += 1", "= kmer in KMERS or reverse_complement(kmer) in KMERS elif not", "in SAMPLES[sample]['results']: row = { 'sample': sample, 'is_bcg': SAMPLES[sample]['is_bcg'], 'is_ba':", "'group': args.group, 'hamming_distance': HAMMING[kmer], 'tp': KMERS[kmer][coverage]['tp'], 'tn': KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'],", "= { 'group_coverages': [], 'outgroup_coverages': [], 'tp': 0, 'tn': 0,", "'fp': KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median': within_group['median'],", "KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max':", "parser.add_argument('coverages', type=str, metavar=\"COVERAGES\", help=('Coverages to subsample to.')) parser.add_argument('outdir', type=str, metavar=\"OUTDIR\",", "kmer summary\") if args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else:", "\"\"\"Reverse complement a DNA sequence.\"\"\" complement = { 'A': 'T',", "line.rstrip().replace(\">\", \"\") kmer, distance = line.split(\"-\") if not has_hamming: distance", "print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir, args.group ))", "print(\"Working on {0} ({1} of {2})\".format(sample, current, total)) current +=", "'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median': within_group['non_zero_median'], 'non_zero_group_kmer_cov_max': within_group['non_zero_max'], 'outgroup_kmer_cov_min': outgroup['min'], 'outgroup_kmer_cov_mean': outgroup['mean'],", "SAMPLES[sample]['is_ba'], 'has_lethal': SAMPLES[sample]['has_lethal'], 'simulated_coverage': result['simulated_coverage'], 'group': args.group, 'within_group': result['within_group'], 'total_kmers':", "if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") kmer, distance = line.split(\"-\")", "in kmer_handle: if line.startswith(\">\"): line = line.rstrip().replace(\">\", \"\") kmer, distance", "[ 'sample', 'is_bcg', 'is_ba', 'has_lethal', 'simulated_coverage', 'group', 'total_kmers', 'tp', 'tn',", "= line.rstrip().replace(\">\", \"\") KMERS[line.split(\"-\")[0]] = True if __name__ == '__main__':", "KMERS[kmer][coverage]['tn'], 'fp': KMERS[kmer][coverage]['fp'], 'fn': KMERS[kmer][coverage]['fn'], 'group_kmer_cov_min': within_group['min'], 'group_kmer_cov_mean': within_group['mean'], 'group_kmer_cov_median':", "if not args.skip_kmers: print(\"Output kmer summary\") if args.single_sample: print_kmer_summary(\"{0}/count-summary-kmer-{1}-{2}.txt\".format( args.outdir,", "'has_lethal', 'simulated_coverage', 'group', 'total_kmers', 'tp', 'tn', 'fp', 'fn', 'kmer_cov_min', 'kmer_cov_mean',", "False elif group == 'bcg': within_group = True if SAMPLES[sample]['is_bcg']", "col in SAMPLE_COLS ]))) output_handle.write(\"\\n\") def print_kmer_summary(file_output): \"\"\"Print the final", "coverage, args.group, skip_kmers=args.skip_kmers, filter_kmers=args.filter) print(\"Output sample summary\") if args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format(", "'True' else False else: # lef within_group = True if", "def parse_summary(summary): \"\"\"Parse Summary file.\"\"\" cols = None with open(summary,", "'bcg' or 'lef'\") coverages = read_lines(args.coverages) print(\"Parsing Summary\") parse_summary(args.summary) print(\"Parsing", "'fn': sample_row['fn'], 'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'],", "sample_row['tn'], 'fp': sample_row['fp'], 'fn': sample_row['fn'], 'kmer_cov_min': coverage_stats['min'], 'kmer_cov_mean': coverage_stats['mean'], 'kmer_cov_median':", "with open(summary, 'r') as summary_handle: # Column Names: # accession,", "1 samples = list(SAMPLES.keys()) if args.single_sample: samples = [args.single_sample] total", "int(count) parse = True if filter_kmers: parse = kmer in", "'bcg', 'lef']: raise Exception(\"GROUPS must be 'ba', 'bcg' or 'lef'\")", "parser.add_argument('group', type=str, metavar=\"GROUP\", help='Which group to parse (ba, bcg or", "'tp', 'tn', 'fp', 'fn', 'group_kmer_cov_min', 'group_kmer_cov_mean', 'group_kmer_cov_median', 'group_kmer_cov_max', 'non_zero_group_kmer_cov_min', 'non_zero_group_kmer_cov_mean',", "outgroup['max'], 'non_zero_outgroup_kmer_cov_min': outgroup['non_zero_min'], 'non_zero_outgroup_kmer_cov_mean': outgroup['non_zero_mean'], 'non_zero_outgroup_kmer_cov_median': outgroup['non_zero_median'], 'non_zero_outgroup_kmer_cov_max': outgroup['non_zero_max'], }", ") parser.add_argument('summary', type=str, metavar=\"SUMMARY\", help='Summary of Bacillus genomes.') parser.add_argument('directory', type=str,", "[c for c in coverage if c] np_array = np.array(coverage)", "summaries.\"\"\" with open(file_output, 'w') as output_handle: output_handle.write((\"\\t\".join(SAMPLE_COLS))) output_handle.write(\"\\n\") for sample", "args.filter: print(\"Filtering Kmers\") args.skip_kmers = True parse_filter_kmers(args.kmers) else: print(\"Parsing Kmers\")", "line.rstrip().replace(\">\", \"\") KMERS[line.split(\"-\")[0]] = True if __name__ == '__main__': parser", "= [] def print_sample_summary(file_output): \"\"\"Print the final per sample summaries.\"\"\"", "result['kmer_cov_mean'], 'kmer_cov_median': result['kmer_cov_median'], 'kmer_cov_max': result['kmer_cov_max'], 'non_zero_kmer_cov_min': result['non_zero_kmer_cov_min'], 'non_zero_kmer_cov_mean': result['non_zero_kmer_cov_mean'], 'non_zero_kmer_cov_median':", "must be 'ba', 'bcg' or 'lef'\") coverages = read_lines(args.coverages) print(\"Parsing", "line in count_handle: kmer, count = line.decode().rstrip().split() count = int(count)", "get_coverage_stats(coverage): \"\"\"Return summary stats of a set of coverages.\"\"\" non_zero", "SAMPLES = OrderedDict() KMERS = {} HAMMING = OrderedDict() SAMPLE_COLS", "c] np_array = np.array(coverage) non_zero_array = np.array(non_zero) return { 'min':", "non_zero_array = np.array(non_zero) return { 'min': min(coverage) if coverage else", "'a': 't', 't': 'a', 'g': 'c', 'c': 'g' } return", "'tn': 0, 'fp': 0, 'fn': 0} with gzip.open(counts, 'r') as", "SAMPLES[row['accession']] = row if row['accession'] == 'NZ_CP009941': # NZ_CP009941 -", "help='Number of cores to use (Default: 1)') parser.add_argument('--single_sample', type=str, metavar=\"STR\",", "\"\"\"Parse through the simulated sequencing group specific kmer counts.\"\"\" import", "in coverages: KMERS[kmer][coverage] = { 'group_coverages': [], 'outgroup_coverages': [], 'tp':", "result['tn'], 'fp': result['fp'], 'fn': result['fn'], 'kmer_cov_min': result['kmer_cov_min'], 'kmer_cov_mean': result['kmer_cov_mean'], 'kmer_cov_median':", "in input_handle: lines.append(line.rstrip()) return lines def parse_filter_kmers(kmers): with open(kmers, 'r')", "specific 31-mer counts.') parser.add_argument('group', type=str, metavar=\"GROUP\", help='Which group to parse", "else: sample_row['tn'] += 1 coverage_stats = get_coverage_stats(sample_row['coverages']) SAMPLES[sample]['results'].append({ 'simulated_coverage': coverage,", "} return ''.join([complement[b] for b in seq[::-1]]) def parse_counts(counts, sample,", "parser.add_argument('kmers', type=str, metavar=\"KMERS\", help='Group specific k-mers.') parser.add_argument('coverages', type=str, metavar=\"COVERAGES\", help=('Coverages", "metavar=\"SIMUALTION_DIR\", help='Directory with group specific 31-mer counts.') parser.add_argument('group', type=str, metavar=\"GROUP\",", "k-mers.') parser.add_argument('coverages', type=str, metavar=\"COVERAGES\", help=('Coverages to subsample to.')) parser.add_argument('outdir', type=str,", "if args.single_sample: print_sample_summary(\"{0}/count-summary-{1}-{2}.txt\".format( args.outdir, args.single_sample, args.group )) else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir,", "'True' else False elif group == 'bcg': within_group = True", "SAMPLE_COLS = [ 'sample', 'is_bcg', 'is_ba', 'has_lethal', 'simulated_coverage', 'group', 'total_kmers',", "else: # lef within_group = True if SAMPLES[sample]['has_lethal'] else False", "KMERS[kmer][coverage]['outgroup_coverages'].append(count) if count: KMERS[kmer][coverage]['fp'] += 1 else: KMERS[kmer][coverage]['tn'] += 1", "has_hamming: distance = False KMERS[kmer] = OrderedDict() HAMMING[kmer] = distance", "within_group['mean'], 'group_kmer_cov_median': within_group['median'], 'group_kmer_cov_max': within_group['max'], 'non_zero_group_kmer_cov_min': within_group['non_zero_min'], 'non_zero_group_kmer_cov_mean': within_group['non_zero_mean'], 'non_zero_group_kmer_cov_median':", "else: print_sample_summary(\"{0}/count-summary-sample-{1}.txt\".format( args.outdir, args.group )) if not args.skip_kmers: print(\"Output kmer", "== 'ba': within_group = True if SAMPLES[sample]['is_ba'] == 'True' else", "help='Which group to parse (ba, bcg or lef).') parser.add_argument('kmers', type=str,", "'kmer_cov_median': coverage_stats['median'], 'kmer_cov_max': coverage_stats['max'], 'non_zero_kmer_cov_min': coverage_stats['non_zero_min'], 'non_zero_kmer_cov_mean': coverage_stats['non_zero_mean'], 'non_zero_kmer_cov_median': coverage_stats['non_zero_median'],", "is_ba, species, genome_size, description for line in summary_handle: line =", "coverage else 0, 'non_zero_min': min(non_zero_array) if non_zero else 0, 'non_zero_median':" ]
[ "class ObjectDoesNotExist(Exception): \"\"\"Exception if not found results\"\"\" pass class CommunicationError(Exception):", "import ValidationError class ObjectDoesNotExist(Exception): \"\"\"Exception if not found results\"\"\" pass", "marshmallow.exceptions import ValidationError class ObjectDoesNotExist(Exception): \"\"\"Exception if not found results\"\"\"", "diferents problem with communications.\"\"\" pass __all__ = ('ValidationError', 'ObjectDoesNotExist', 'CommunicationError')", "from marshmallow.exceptions import ValidationError class ObjectDoesNotExist(Exception): \"\"\"Exception if not found", "for diferents problem with communications.\"\"\" pass __all__ = ('ValidationError', 'ObjectDoesNotExist',", "ObjectDoesNotExist(Exception): \"\"\"Exception if not found results\"\"\" pass class CommunicationError(Exception): \"\"\"Exception", "results\"\"\" pass class CommunicationError(Exception): \"\"\"Exception for diferents problem with communications.\"\"\"", "ValidationError class ObjectDoesNotExist(Exception): \"\"\"Exception if not found results\"\"\" pass class", "CommunicationError(Exception): \"\"\"Exception for diferents problem with communications.\"\"\" pass __all__ =", "pass class CommunicationError(Exception): \"\"\"Exception for diferents problem with communications.\"\"\" pass", "if not found results\"\"\" pass class CommunicationError(Exception): \"\"\"Exception for diferents", "\"\"\"Exception for diferents problem with communications.\"\"\" pass __all__ = ('ValidationError',", "not found results\"\"\" pass class CommunicationError(Exception): \"\"\"Exception for diferents problem", "class CommunicationError(Exception): \"\"\"Exception for diferents problem with communications.\"\"\" pass __all__", "found results\"\"\" pass class CommunicationError(Exception): \"\"\"Exception for diferents problem with", "\"\"\"Exception if not found results\"\"\" pass class CommunicationError(Exception): \"\"\"Exception for", "<filename>movies/exceptions.py from marshmallow.exceptions import ValidationError class ObjectDoesNotExist(Exception): \"\"\"Exception if not" ]
[ "from django.contrib import admin from .models import Songs admin.site.register(Songs) #", "django.contrib import admin from .models import Songs admin.site.register(Songs) # Register", "import admin from .models import Songs admin.site.register(Songs) # Register your", "admin from .models import Songs admin.site.register(Songs) # Register your models", "from .models import Songs admin.site.register(Songs) # Register your models here." ]
[ "= sort_identifiers_by_date(identifiers) def identifiers_to_joined_image(identifiers): images = [] for identifier in", "# Early leaf senescence # generate_image_series_for_plot(3, 16) # generate_image_series_for_plot(7, 9)", "= 'file:/Users/hartleym/data_intermediate/separate_plots' dataset = dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay = dataset.get_overlay('plot_number') ordering_overlay =", "dates_and_identifiers = [(date_overlay[i], i) for i in identifiers] sorted_dates_and_identifiers =", "dataset = dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay = dataset.get_overlay('plot_number') ordering_overlay = dataset.get_overlay('ordering') date_overlay", "join_vertically def identifiers_where_match_is_true(dataset, match_function): return [i for i in dataset.identifiers", "identifiers] sorted_dates_and_identifiers = sorted(dates_and_identifiers) _, sorted_identifiers = zip(*sorted_dates_and_identifiers) return(sorted_identifiers) sorted_identifiers", "as fh: fh.write(result.png()) @click.command() def main(): # Early leaf senescence", "leaf senescence # generate_image_series_for_plot(3, 16) # generate_image_series_for_plot(7, 9) # generate_image_series_for_plot(9,", "identifiers_where_match_is_true(dataset, match_function): return [i for i in dataset.identifiers if match_function(i)]", "Image.from_file(image_fpath) images.append(image) return join_horizontally(images) result = identifiers_to_joined_image(sorted_identifiers) output_fname = 'example_from_tobin.png'", "output_fname = 'example_from_tobin.png' with open(output_fname, 'wb') as fh: fh.write(result.png()) @click.command()", "def identifiers_where_match_is_true(dataset, match_function): return [i for i in dataset.identifiers if", "result = identifiers_to_joined_image(sorted_identifiers) output_fname = 'example_from_tobin.png' with open(output_fname, 'wb') as", "generate_image_series_for_plot(7, 9) # generate_image_series_for_plot(9, 1) # Late leaf senescence generate_image_series_for_plot(7,", "if int(plot_number_overlay[i]) != n_plot: return False return True identifiers =", "return True identifiers = identifiers_where_match_is_true(dataset, is_match) def sort_identifiers_by_date(identifiers): dates_and_identifiers =", "\"{}_{}\".format(n_image, n_plot) dataset_uri = 'file:/Users/hartleym/data_intermediate/separate_plots' dataset = dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay =", "!= n_image: return False if int(plot_number_overlay[i]) != n_plot: return False", "identifiers = identifiers_where_match_is_true(dataset, is_match) def sort_identifiers_by_date(identifiers): dates_and_identifiers = [(date_overlay[i], i)", "[i for i in dataset.identifiers if match_function(i)] def generate_image_series_for_plot(rack, plot):", "n_image, n_plot = rack_plot_to_image_plot(rack, plot) # n_image, n_plot = 55,", "sorted_identifiers = sort_identifiers_by_date(identifiers) def identifiers_to_joined_image(identifiers): images = [] for identifier", "sort_identifiers_by_date(identifiers) def identifiers_to_joined_image(identifiers): images = [] for identifier in identifiers:", "match_function): return [i for i in dataset.identifiers if match_function(i)] def", "join_horizontally, join_vertically def identifiers_where_match_is_true(dataset, match_function): return [i for i in", "def is_match(i): try: ordering_as_int = int(ordering_overlay[i]) except TypeError: return False", "55, 24 print \"{}_{}\".format(n_image, n_plot) dataset_uri = 'file:/Users/hartleym/data_intermediate/separate_plots' dataset =", "= int(ordering_overlay[i]) except TypeError: return False if ordering_as_int != n_image:", "identifiers_to_joined_image(identifiers): images = [] for identifier in identifiers: image_fpath =", "zip(*sorted_dates_and_identifiers) return(sorted_identifiers) sorted_identifiers = sort_identifiers_by_date(identifiers) def identifiers_to_joined_image(identifiers): images = []", "# generate_image_series_for_plot(7, 9) # generate_image_series_for_plot(9, 1) # Late leaf senescence", "except TypeError: return False if ordering_as_int != n_image: return False", "images.append(image) return join_horizontally(images) result = identifiers_to_joined_image(sorted_identifiers) output_fname = 'example_from_tobin.png' with", "translate_labels import rack_plot_to_image_plot from image_utils import join_horizontally, join_vertically def identifiers_where_match_is_true(dataset,", "dataset.get_overlay('date') def is_match(i): try: ordering_as_int = int(ordering_overlay[i]) except TypeError: return", "series for one or more plots from jicbioimage.core.image import Image", "fh: fh.write(result.png()) @click.command() def main(): # Early leaf senescence #", "return join_horizontally(images) result = identifiers_to_joined_image(sorted_identifiers) output_fname = 'example_from_tobin.png' with open(output_fname,", "for one or more plots from jicbioimage.core.image import Image import", "import click from translate_labels import rack_plot_to_image_plot from image_utils import join_horizontally,", "# n_image, n_plot = 55, 24 print \"{}_{}\".format(n_image, n_plot) dataset_uri", "date_overlay = dataset.get_overlay('date') def is_match(i): try: ordering_as_int = int(ordering_overlay[i]) except", "= sorted(dates_and_identifiers) _, sorted_identifiers = zip(*sorted_dates_and_identifiers) return(sorted_identifiers) sorted_identifiers = sort_identifiers_by_date(identifiers)", "= 'example_from_tobin.png' with open(output_fname, 'wb') as fh: fh.write(result.png()) @click.command() def", "main(): # Early leaf senescence # generate_image_series_for_plot(3, 16) # generate_image_series_for_plot(7,", "import dtoolcore import click from translate_labels import rack_plot_to_image_plot from image_utils", "# Draw image time series for one or more plots", "ordering_as_int = int(ordering_overlay[i]) except TypeError: return False if ordering_as_int !=", "n_plot = 55, 24 print \"{}_{}\".format(n_image, n_plot) dataset_uri = 'file:/Users/hartleym/data_intermediate/separate_plots'", "[(date_overlay[i], i) for i in identifiers] sorted_dates_and_identifiers = sorted(dates_and_identifiers) _,", "for i in dataset.identifiers if match_function(i)] def generate_image_series_for_plot(rack, plot): n_image,", "sorted_identifiers = zip(*sorted_dates_and_identifiers) return(sorted_identifiers) sorted_identifiers = sort_identifiers_by_date(identifiers) def identifiers_to_joined_image(identifiers): images", "rack_plot_to_image_plot(rack, plot) # n_image, n_plot = 55, 24 print \"{}_{}\".format(n_image,", "match_function(i)] def generate_image_series_for_plot(rack, plot): n_image, n_plot = rack_plot_to_image_plot(rack, plot) #", "import Image import dtoolcore import click from translate_labels import rack_plot_to_image_plot", "= dataset.get_overlay('plot_number') ordering_overlay = dataset.get_overlay('ordering') date_overlay = dataset.get_overlay('date') def is_match(i):", "import rack_plot_to_image_plot from image_utils import join_horizontally, join_vertically def identifiers_where_match_is_true(dataset, match_function):", "TypeError: return False if ordering_as_int != n_image: return False if", "# generate_image_series_for_plot(3, 16) # generate_image_series_for_plot(7, 9) # generate_image_series_for_plot(9, 1) #", "# generate_image_series_for_plot(9, 1) # Late leaf senescence generate_image_series_for_plot(7, 15) if", "Late leaf senescence generate_image_series_for_plot(7, 15) if __name__ == '__main__': main()", "plot_number_overlay = dataset.get_overlay('plot_number') ordering_overlay = dataset.get_overlay('ordering') date_overlay = dataset.get_overlay('date') def", "senescence # generate_image_series_for_plot(3, 16) # generate_image_series_for_plot(7, 9) # generate_image_series_for_plot(9, 1)", "# Late leaf senescence generate_image_series_for_plot(7, 15) if __name__ == '__main__':", "= 55, 24 print \"{}_{}\".format(n_image, n_plot) dataset_uri = 'file:/Users/hartleym/data_intermediate/separate_plots' dataset", "= identifiers_to_joined_image(sorted_identifiers) output_fname = 'example_from_tobin.png' with open(output_fname, 'wb') as fh:", "n_image, n_plot = 55, 24 print \"{}_{}\".format(n_image, n_plot) dataset_uri =", "i in identifiers] sorted_dates_and_identifiers = sorted(dates_and_identifiers) _, sorted_identifiers = zip(*sorted_dates_and_identifiers)", "False if int(plot_number_overlay[i]) != n_plot: return False return True identifiers", "= dataset.get_overlay('date') def is_match(i): try: ordering_as_int = int(ordering_overlay[i]) except TypeError:", "'example_from_tobin.png' with open(output_fname, 'wb') as fh: fh.write(result.png()) @click.command() def main():", "dataset.get_overlay('ordering') date_overlay = dataset.get_overlay('date') def is_match(i): try: ordering_as_int = int(ordering_overlay[i])", "generate_image_series_for_plot(9, 1) # Late leaf senescence generate_image_series_for_plot(7, 15) if __name__", "n_plot: return False return True identifiers = identifiers_where_match_is_true(dataset, is_match) def", "24 print \"{}_{}\".format(n_image, n_plot) dataset_uri = 'file:/Users/hartleym/data_intermediate/separate_plots' dataset = dtoolcore.DataSet.from_uri(dataset_uri)", "plot): n_image, n_plot = rack_plot_to_image_plot(rack, plot) # n_image, n_plot =", "generate_image_series_for_plot(3, 16) # generate_image_series_for_plot(7, 9) # generate_image_series_for_plot(9, 1) # Late", "try: ordering_as_int = int(ordering_overlay[i]) except TypeError: return False if ordering_as_int", "plots from jicbioimage.core.image import Image import dtoolcore import click from", "from jicbioimage.core.image import Image import dtoolcore import click from translate_labels", "n_image: return False if int(plot_number_overlay[i]) != n_plot: return False return", "identifiers: image_fpath = dataset.item_content_abspath(identifier) image = Image.from_file(image_fpath) images.append(image) return join_horizontally(images)", "Early leaf senescence # generate_image_series_for_plot(3, 16) # generate_image_series_for_plot(7, 9) #", "'file:/Users/hartleym/data_intermediate/separate_plots' dataset = dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay = dataset.get_overlay('plot_number') ordering_overlay = dataset.get_overlay('ordering')", "is_match(i): try: ordering_as_int = int(ordering_overlay[i]) except TypeError: return False if", "= dataset.item_content_abspath(identifier) image = Image.from_file(image_fpath) images.append(image) return join_horizontally(images) result =", "for identifier in identifiers: image_fpath = dataset.item_content_abspath(identifier) image = Image.from_file(image_fpath)", "rack_plot_to_image_plot from image_utils import join_horizontally, join_vertically def identifiers_where_match_is_true(dataset, match_function): return", "n_plot) dataset_uri = 'file:/Users/hartleym/data_intermediate/separate_plots' dataset = dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay = dataset.get_overlay('plot_number')", "'wb') as fh: fh.write(result.png()) @click.command() def main(): # Early leaf", "sort_identifiers_by_date(identifiers): dates_and_identifiers = [(date_overlay[i], i) for i in identifiers] sorted_dates_and_identifiers", "open(output_fname, 'wb') as fh: fh.write(result.png()) @click.command() def main(): # Early", "or more plots from jicbioimage.core.image import Image import dtoolcore import", "is_match) def sort_identifiers_by_date(identifiers): dates_and_identifiers = [(date_overlay[i], i) for i in", "1) # Late leaf senescence generate_image_series_for_plot(7, 15) if __name__ ==", "9) # generate_image_series_for_plot(9, 1) # Late leaf senescence generate_image_series_for_plot(7, 15)", "ordering_as_int != n_image: return False if int(plot_number_overlay[i]) != n_plot: return", "ordering_overlay = dataset.get_overlay('ordering') date_overlay = dataset.get_overlay('date') def is_match(i): try: ordering_as_int", "from image_utils import join_horizontally, join_vertically def identifiers_where_match_is_true(dataset, match_function): return [i", "dataset.get_overlay('plot_number') ordering_overlay = dataset.get_overlay('ordering') date_overlay = dataset.get_overlay('date') def is_match(i): try:", "sorted(dates_and_identifiers) _, sorted_identifiers = zip(*sorted_dates_and_identifiers) return(sorted_identifiers) sorted_identifiers = sort_identifiers_by_date(identifiers) def", "with open(output_fname, 'wb') as fh: fh.write(result.png()) @click.command() def main(): #", "print \"{}_{}\".format(n_image, n_plot) dataset_uri = 'file:/Users/hartleym/data_intermediate/separate_plots' dataset = dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay", "= [(date_overlay[i], i) for i in identifiers] sorted_dates_and_identifiers = sorted(dates_and_identifiers)", "images = [] for identifier in identifiers: image_fpath = dataset.item_content_abspath(identifier)", "def main(): # Early leaf senescence # generate_image_series_for_plot(3, 16) #", "in dataset.identifiers if match_function(i)] def generate_image_series_for_plot(rack, plot): n_image, n_plot =", "dataset.identifiers if match_function(i)] def generate_image_series_for_plot(rack, plot): n_image, n_plot = rack_plot_to_image_plot(rack,", "True identifiers = identifiers_where_match_is_true(dataset, is_match) def sort_identifiers_by_date(identifiers): dates_and_identifiers = [(date_overlay[i],", "join_horizontally(images) result = identifiers_to_joined_image(sorted_identifiers) output_fname = 'example_from_tobin.png' with open(output_fname, 'wb')", "image time series for one or more plots from jicbioimage.core.image", "dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay = dataset.get_overlay('plot_number') ordering_overlay = dataset.get_overlay('ordering') date_overlay = dataset.get_overlay('date')", "False if ordering_as_int != n_image: return False if int(plot_number_overlay[i]) !=", "return(sorted_identifiers) sorted_identifiers = sort_identifiers_by_date(identifiers) def identifiers_to_joined_image(identifiers): images = [] for", "click from translate_labels import rack_plot_to_image_plot from image_utils import join_horizontally, join_vertically", "return [i for i in dataset.identifiers if match_function(i)] def generate_image_series_for_plot(rack,", "for i in identifiers] sorted_dates_and_identifiers = sorted(dates_and_identifiers) _, sorted_identifiers =", "image_fpath = dataset.item_content_abspath(identifier) image = Image.from_file(image_fpath) images.append(image) return join_horizontally(images) result", "False return True identifiers = identifiers_where_match_is_true(dataset, is_match) def sort_identifiers_by_date(identifiers): dates_and_identifiers", "= identifiers_where_match_is_true(dataset, is_match) def sort_identifiers_by_date(identifiers): dates_and_identifiers = [(date_overlay[i], i) for", "one or more plots from jicbioimage.core.image import Image import dtoolcore", "identifier in identifiers: image_fpath = dataset.item_content_abspath(identifier) image = Image.from_file(image_fpath) images.append(image)", "generate_image_series_for_plot(rack, plot): n_image, n_plot = rack_plot_to_image_plot(rack, plot) # n_image, n_plot", "int(plot_number_overlay[i]) != n_plot: return False return True identifiers = identifiers_where_match_is_true(dataset,", "return False if int(plot_number_overlay[i]) != n_plot: return False return True", "in identifiers: image_fpath = dataset.item_content_abspath(identifier) image = Image.from_file(image_fpath) images.append(image) return", "n_plot = rack_plot_to_image_plot(rack, plot) # n_image, n_plot = 55, 24", "= rack_plot_to_image_plot(rack, plot) # n_image, n_plot = 55, 24 print", "Image import dtoolcore import click from translate_labels import rack_plot_to_image_plot from", "dtoolcore import click from translate_labels import rack_plot_to_image_plot from image_utils import", "_, sorted_identifiers = zip(*sorted_dates_and_identifiers) return(sorted_identifiers) sorted_identifiers = sort_identifiers_by_date(identifiers) def identifiers_to_joined_image(identifiers):", "= Image.from_file(image_fpath) images.append(image) return join_horizontally(images) result = identifiers_to_joined_image(sorted_identifiers) output_fname =", "return False if ordering_as_int != n_image: return False if int(plot_number_overlay[i])", "!= n_plot: return False return True identifiers = identifiers_where_match_is_true(dataset, is_match)", "def generate_image_series_for_plot(rack, plot): n_image, n_plot = rack_plot_to_image_plot(rack, plot) # n_image,", "= zip(*sorted_dates_and_identifiers) return(sorted_identifiers) sorted_identifiers = sort_identifiers_by_date(identifiers) def identifiers_to_joined_image(identifiers): images =", "[] for identifier in identifiers: image_fpath = dataset.item_content_abspath(identifier) image =", "def identifiers_to_joined_image(identifiers): images = [] for identifier in identifiers: image_fpath", "dataset_uri = 'file:/Users/hartleym/data_intermediate/separate_plots' dataset = dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay = dataset.get_overlay('plot_number') ordering_overlay", "identifiers_where_match_is_true(dataset, is_match) def sort_identifiers_by_date(identifiers): dates_and_identifiers = [(date_overlay[i], i) for i", "= dtoolcore.DataSet.from_uri(dataset_uri) plot_number_overlay = dataset.get_overlay('plot_number') ordering_overlay = dataset.get_overlay('ordering') date_overlay =", "more plots from jicbioimage.core.image import Image import dtoolcore import click", "int(ordering_overlay[i]) except TypeError: return False if ordering_as_int != n_image: return", "def sort_identifiers_by_date(identifiers): dates_and_identifiers = [(date_overlay[i], i) for i in identifiers]", "= dataset.get_overlay('ordering') date_overlay = dataset.get_overlay('date') def is_match(i): try: ordering_as_int =", "sorted_dates_and_identifiers = sorted(dates_and_identifiers) _, sorted_identifiers = zip(*sorted_dates_and_identifiers) return(sorted_identifiers) sorted_identifiers =", "image = Image.from_file(image_fpath) images.append(image) return join_horizontally(images) result = identifiers_to_joined_image(sorted_identifiers) output_fname", "in identifiers] sorted_dates_and_identifiers = sorted(dates_and_identifiers) _, sorted_identifiers = zip(*sorted_dates_and_identifiers) return(sorted_identifiers)", "i) for i in identifiers] sorted_dates_and_identifiers = sorted(dates_and_identifiers) _, sorted_identifiers", "jicbioimage.core.image import Image import dtoolcore import click from translate_labels import", "i in dataset.identifiers if match_function(i)] def generate_image_series_for_plot(rack, plot): n_image, n_plot", "import join_horizontally, join_vertically def identifiers_where_match_is_true(dataset, match_function): return [i for i", "= [] for identifier in identifiers: image_fpath = dataset.item_content_abspath(identifier) image", "@click.command() def main(): # Early leaf senescence # generate_image_series_for_plot(3, 16)", "fh.write(result.png()) @click.command() def main(): # Early leaf senescence # generate_image_series_for_plot(3,", "if ordering_as_int != n_image: return False if int(plot_number_overlay[i]) != n_plot:", "plot) # n_image, n_plot = 55, 24 print \"{}_{}\".format(n_image, n_plot)", "from translate_labels import rack_plot_to_image_plot from image_utils import join_horizontally, join_vertically def", "time series for one or more plots from jicbioimage.core.image import", "image_utils import join_horizontally, join_vertically def identifiers_where_match_is_true(dataset, match_function): return [i for", "dataset.item_content_abspath(identifier) image = Image.from_file(image_fpath) images.append(image) return join_horizontally(images) result = identifiers_to_joined_image(sorted_identifiers)", "16) # generate_image_series_for_plot(7, 9) # generate_image_series_for_plot(9, 1) # Late leaf", "if match_function(i)] def generate_image_series_for_plot(rack, plot): n_image, n_plot = rack_plot_to_image_plot(rack, plot)", "identifiers_to_joined_image(sorted_identifiers) output_fname = 'example_from_tobin.png' with open(output_fname, 'wb') as fh: fh.write(result.png())", "return False return True identifiers = identifiers_where_match_is_true(dataset, is_match) def sort_identifiers_by_date(identifiers):", "Draw image time series for one or more plots from" ]
[ "= {} return system_status.Engine( dn=response_object.get('DN'), display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'), id=response_object.get('Id'), name=response_object.get('Name'), )", "<gh_stars>1-10 from pytpp.properties.response_objects.dataclasses import system_status from pytpp.tools.helpers.date_converter import from_date_string class", "@staticmethod def Task(response_object: dict): if not isinstance(response_object, dict): response_object =", "version=response_object.get('version'), ) @staticmethod def Task(response_object: dict): if not isinstance(response_object, dict):", "status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t) for t in response_object.get('TasksCompleted', [])], tasks_pending=[SystemStatus.Task(t)", "tasks_running=[SystemStatus.Task(t) for t in response_object.get('TasksRunning', [])], ) @staticmethod def UpgradeSummary(response_object:", "in response_object.get('TasksPending', [])], tasks_running=[SystemStatus.Task(t) for t in response_object.get('TasksRunning', [])], )", "if not isinstance(response_object, dict): response_object = {} return system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')),", "UpgradeStatus(response_object: dict): if not isinstance(response_object, dict): response_object = {} return", "system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t) for t in response_object.get('TasksCompleted',", "from_date_string class SystemStatus: @staticmethod def Engine(response_object: dict): if not isinstance(response_object,", "upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), completed_tasks=response_object.get('CompletedTasks'), target_version=response_object.get('TargetVersion'), engines_complete=response_object.get('EnginesComplete'), engines_running=response_object.get('EnginesRunning'), engines_blocked=response_object.get('EnginesBlocked'), engines_in_error=response_object.get('EnginesInError'), engines_pending_install=response_object.get('EnginesPendingInstall'), )", "return system_status.Engine( dn=response_object.get('DN'), display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'), id=response_object.get('Id'), name=response_object.get('Name'), ) @staticmethod def", "not isinstance(response_object, dict): response_object = {} return system_status.Engine( dn=response_object.get('DN'), display_name=response_object.get('DisplayName'),", "{} return system_status.SystemStatus( engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'), ) @staticmethod def Task(response_object:", "if not isinstance(response_object, dict): response_object = {} return system_status.UpgradeInfo( id=response_object.get('Id'),", "@staticmethod def Services(response_object: dict): if not isinstance(response_object, dict): response_object =", "return system_status.SystemStatus( engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'), ) @staticmethod def Task(response_object: dict):", "Services(response_object: dict): if not isinstance(response_object, dict): response_object = {} return", "dict): if not isinstance(response_object, dict): response_object = {} return system_status.UpgradeInfo(", "if not isinstance(response_object, dict): response_object = {} return system_status.Service( modules=response_object.get('modules'),", "def Task(response_object: dict): if not isinstance(response_object, dict): response_object = {}", "dict): response_object = {} return system_status.UpgradeSummary( status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), completed_tasks=response_object.get('CompletedTasks'),", "display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'), id=response_object.get('Id'), name=response_object.get('Name'), ) @staticmethod def Services(response_object: dict): if", "dict): if not isinstance(response_object, dict): response_object = {} return system_status.Task(", "tasks_completed=[SystemStatus.Task(t) for t in response_object.get('TasksCompleted', [])], tasks_pending=[SystemStatus.Task(t) for t in", "iis=SystemStatus.Service(response_object.get('iis')), ) @staticmethod def Service(response_object: dict): if not isinstance(response_object, dict):", "system_status.Task( display_name=response_object.get('DisplayName'), name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'), ) @staticmethod def UpgradeInfo(response_object:", "def UpgradeStatus(response_object: dict): if not isinstance(response_object, dict): response_object = {}", "dict): response_object = {} return system_status.Task( display_name=response_object.get('DisplayName'), name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')),", "duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True), status=response_object.get('Status'), ) @staticmethod def SystemStatus(response_object: dict): if", "isinstance(response_object, dict): response_object = {} return system_status.UpgradeInfo( id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'),", "isinstance(response_object, dict): response_object = {} return system_status.Service( modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True),", "@staticmethod def Engine(response_object: dict): if not isinstance(response_object, dict): response_object =", "{} return system_status.UpgradeInfo( id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'), ) @staticmethod def UpgradeStatus(response_object:", ") @staticmethod def UpgradeStatus(response_object: dict): if not isinstance(response_object, dict): response_object", "t in response_object.get('TasksRunning', [])], ) @staticmethod def UpgradeSummary(response_object: dict): if", "isinstance(response_object, dict): response_object = {} return system_status.Task( display_name=response_object.get('DisplayName'), name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')),", "warning_count=response_object.get('WarningCount'), ) @staticmethod def UpgradeInfo(response_object: dict): if not isinstance(response_object, dict):", "if not isinstance(response_object, dict): response_object = {} return system_status.Engine( dn=response_object.get('DN'),", "display_name=response_object.get('DisplayName'), name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'), ) @staticmethod def UpgradeInfo(response_object: dict):", "name=response_object.get('Name'), ) @staticmethod def Services(response_object: dict): if not isinstance(response_object, dict):", "in response_object.get('TasksRunning', [])], ) @staticmethod def UpgradeSummary(response_object: dict): if not", "{} return system_status.Engine( dn=response_object.get('DN'), display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'), id=response_object.get('Id'), name=response_object.get('Name'), ) @staticmethod", "stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'), ) @staticmethod def UpgradeInfo(response_object: dict): if not isinstance(response_object,", "return system_status.Task( display_name=response_object.get('DisplayName'), name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'), ) @staticmethod def", "not isinstance(response_object, dict): response_object = {} return system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')),", "system_status.Engine( dn=response_object.get('DN'), display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'), id=response_object.get('Id'), name=response_object.get('Name'), ) @staticmethod def Services(response_object:", "dict): if not isinstance(response_object, dict): response_object = {} return system_status.UpgradeSummary(", "if not isinstance(response_object, dict): response_object = {} return system_status.SystemStatus( engine_name=response_object.get('engineName'),", "log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')), ) @staticmethod def Service(response_object: dict): if not isinstance(response_object,", "= {} return system_status.UpgradeInfo( id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'), ) @staticmethod def", "@staticmethod def UpgradeSummary(response_object: dict): if not isinstance(response_object, dict): response_object =", "engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t) for t in response_object.get('TasksCompleted', [])],", "for t in response_object.get('TasksRunning', [])], ) @staticmethod def UpgradeSummary(response_object: dict):", "dict): if not isinstance(response_object, dict): response_object = {} return system_status.Services(", "for t in response_object.get('TasksCompleted', [])], tasks_pending=[SystemStatus.Task(t) for t in response_object.get('TasksPending',", "[])], ) @staticmethod def UpgradeSummary(response_object: dict): if not isinstance(response_object, dict):", "system_status.UpgradeSummary( status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), completed_tasks=response_object.get('CompletedTasks'), target_version=response_object.get('TargetVersion'), engines_complete=response_object.get('EnginesComplete'), engines_running=response_object.get('EnginesRunning'), engines_blocked=response_object.get('EnginesBlocked'), engines_in_error=response_object.get('EnginesInError'),", "def Engine(response_object: dict): if not isinstance(response_object, dict): response_object = {}", "upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t) for t in response_object.get('TasksCompleted', [])], tasks_pending=[SystemStatus.Task(t) for t", "system_status.SystemStatus( engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'), ) @staticmethod def Task(response_object: dict): if", "id=response_object.get('Id'), name=response_object.get('Name'), ) @staticmethod def Services(response_object: dict): if not isinstance(response_object,", "Task(response_object: dict): if not isinstance(response_object, dict): response_object = {} return", ") @staticmethod def UpgradeInfo(response_object: dict): if not isinstance(response_object, dict): response_object", "response_object.get('TasksCompleted', [])], tasks_pending=[SystemStatus.Task(t) for t in response_object.get('TasksPending', [])], tasks_running=[SystemStatus.Task(t) for", "Engine(response_object: dict): if not isinstance(response_object, dict): response_object = {} return", "if not isinstance(response_object, dict): response_object = {} return system_status.Task( display_name=response_object.get('DisplayName'),", "def Services(response_object: dict): if not isinstance(response_object, dict): response_object = {}", "return system_status.UpgradeSummary( status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), completed_tasks=response_object.get('CompletedTasks'), target_version=response_object.get('TargetVersion'), engines_complete=response_object.get('EnginesComplete'), engines_running=response_object.get('EnginesRunning'), engines_blocked=response_object.get('EnginesBlocked'),", "def SystemStatus(response_object: dict): if not isinstance(response_object, dict): response_object = {}", "response_object = {} return system_status.Service( modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True),", "pytpp.properties.response_objects.dataclasses import system_status from pytpp.tools.helpers.date_converter import from_date_string class SystemStatus: @staticmethod", "@staticmethod def Service(response_object: dict): if not isinstance(response_object, dict): response_object =", "return system_status.UpgradeInfo( id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'), ) @staticmethod def UpgradeStatus(response_object: dict):", "= {} return system_status.Service( modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True), status=response_object.get('Status'),", "status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), completed_tasks=response_object.get('CompletedTasks'), target_version=response_object.get('TargetVersion'), engines_complete=response_object.get('EnginesComplete'), engines_running=response_object.get('EnginesRunning'), engines_blocked=response_object.get('EnginesBlocked'), engines_in_error=response_object.get('EnginesInError'), engines_pending_install=response_object.get('EnginesPendingInstall'),", "not isinstance(response_object, dict): response_object = {} return system_status.Task( display_name=response_object.get('DisplayName'), name=response_object.get('Name'),", ") @staticmethod def Service(response_object: dict): if not isinstance(response_object, dict): response_object", "def UpgradeSummary(response_object: dict): if not isinstance(response_object, dict): response_object = {}", "{} return system_status.UpgradeSummary( status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), completed_tasks=response_object.get('CompletedTasks'), target_version=response_object.get('TargetVersion'), engines_complete=response_object.get('EnginesComplete'), engines_running=response_object.get('EnginesRunning'),", "= {} return system_status.SystemStatus( engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'), ) @staticmethod def", "return system_status.Service( modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True), status=response_object.get('Status'), ) @staticmethod", "isinstance(response_object, dict): response_object = {} return system_status.SystemStatus( engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'),", "services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'), ) @staticmethod def Task(response_object: dict): if not isinstance(response_object,", "UpgradeInfo(response_object: dict): if not isinstance(response_object, dict): response_object = {} return", "dict): response_object = {} return system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')),", "not isinstance(response_object, dict): response_object = {} return system_status.UpgradeSummary( status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')),", "response_object = {} return system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t)", "duration_format=True), status=response_object.get('Status'), ) @staticmethod def SystemStatus(response_object: dict): if not isinstance(response_object,", "response_object = {} return system_status.Engine( dn=response_object.get('DN'), display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'), id=response_object.get('Id'), name=response_object.get('Name'),", "UpgradeSummary(response_object: dict): if not isinstance(response_object, dict): response_object = {} return", "not isinstance(response_object, dict): response_object = {} return system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'),", "pytpp.tools.helpers.date_converter import from_date_string class SystemStatus: @staticmethod def Engine(response_object: dict): if", "= {} return system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t) for", "response_object = {} return system_status.SystemStatus( engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'), ) @staticmethod", "for t in response_object.get('TasksPending', [])], tasks_running=[SystemStatus.Task(t) for t in response_object.get('TasksRunning',", "{} return system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')), ) @staticmethod def Service(response_object:", "upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t) for t in response_object.get('TasksCompleted', [])], tasks_pending=[SystemStatus.Task(t) for", "system_status.Service( modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True), status=response_object.get('Status'), ) @staticmethod def", "@staticmethod def UpgradeStatus(response_object: dict): if not isinstance(response_object, dict): response_object =", "[])], tasks_running=[SystemStatus.Task(t) for t in response_object.get('TasksRunning', [])], ) @staticmethod def", "dict): response_object = {} return system_status.SystemStatus( engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'), )", "tasks_pending=[SystemStatus.Task(t) for t in response_object.get('TasksPending', [])], tasks_running=[SystemStatus.Task(t) for t in", "if not isinstance(response_object, dict): response_object = {} return system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')),", "dict): if not isinstance(response_object, dict): response_object = {} return system_status.SystemStatus(", "dict): response_object = {} return system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')), )", "dn=response_object.get('DN'), display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'), id=response_object.get('Id'), name=response_object.get('Name'), ) @staticmethod def Services(response_object: dict):", "t in response_object.get('TasksCompleted', [])], tasks_pending=[SystemStatus.Task(t) for t in response_object.get('TasksPending', [])],", "in response_object.get('TasksCompleted', [])], tasks_pending=[SystemStatus.Task(t) for t in response_object.get('TasksPending', [])], tasks_running=[SystemStatus.Task(t)", "name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'), ) @staticmethod def UpgradeInfo(response_object: dict): if", "not isinstance(response_object, dict): response_object = {} return system_status.SystemStatus( engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')),", "dict): response_object = {} return system_status.Service( modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'),", "system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')), ) @staticmethod def Service(response_object: dict): if", "if not isinstance(response_object, dict): response_object = {} return system_status.UpgradeSummary( status=response_object.get('Status'),", "= {} return system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')), ) @staticmethod def", "@staticmethod def SystemStatus(response_object: dict): if not isinstance(response_object, dict): response_object =", "from pytpp.properties.response_objects.dataclasses import system_status from pytpp.tools.helpers.date_converter import from_date_string class SystemStatus:", "@staticmethod def UpgradeInfo(response_object: dict): if not isinstance(response_object, dict): response_object =", "guid=response_object.get('Guid'), id=response_object.get('Id'), name=response_object.get('Name'), ) @staticmethod def Services(response_object: dict): if not", "time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True), status=response_object.get('Status'), ) @staticmethod def SystemStatus(response_object: dict): if not", "Service(response_object: dict): if not isinstance(response_object, dict): response_object = {} return", "status=response_object.get('Status'), ) @staticmethod def SystemStatus(response_object: dict): if not isinstance(response_object, dict):", "id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'), ) @staticmethod def UpgradeStatus(response_object: dict): if not", "dict): if not isinstance(response_object, dict): response_object = {} return system_status.Service(", "start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'), ) @staticmethod def UpgradeStatus(response_object: dict): if not isinstance(response_object,", "vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')), ) @staticmethod def Service(response_object: dict): if not", "response_object.get('TasksPending', [])], tasks_running=[SystemStatus.Task(t) for t in response_object.get('TasksRunning', [])], ) @staticmethod", "dict): response_object = {} return system_status.UpgradeInfo( id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'), )", "not isinstance(response_object, dict): response_object = {} return system_status.UpgradeInfo( id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')),", "= {} return system_status.UpgradeSummary( status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), completed_tasks=response_object.get('CompletedTasks'), target_version=response_object.get('TargetVersion'), engines_complete=response_object.get('EnginesComplete'),", "modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True), status=response_object.get('Status'), ) @staticmethod def SystemStatus(response_object:", "response_object.get('TasksRunning', [])], ) @staticmethod def UpgradeSummary(response_object: dict): if not isinstance(response_object,", "not isinstance(response_object, dict): response_object = {} return system_status.Service( modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'),", "SystemStatus(response_object: dict): if not isinstance(response_object, dict): response_object = {} return", "{} return system_status.Task( display_name=response_object.get('DisplayName'), name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'), ) @staticmethod", "dict): if not isinstance(response_object, dict): response_object = {} return system_status.UpgradeStatus(", "isinstance(response_object, dict): response_object = {} return system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')),", "from pytpp.tools.helpers.date_converter import from_date_string class SystemStatus: @staticmethod def Engine(response_object: dict):", "= {} return system_status.Task( display_name=response_object.get('DisplayName'), name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'), )", "return system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')), ) @staticmethod def Service(response_object: dict):", "return system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t) for t in", "[])], tasks_pending=[SystemStatus.Task(t) for t in response_object.get('TasksPending', [])], tasks_running=[SystemStatus.Task(t) for t", ") @staticmethod def SystemStatus(response_object: dict): if not isinstance(response_object, dict): response_object", ") @staticmethod def Task(response_object: dict): if not isinstance(response_object, dict): response_object", "response_object = {} return system_status.UpgradeInfo( id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'), ) @staticmethod", ") @staticmethod def UpgradeSummary(response_object: dict): if not isinstance(response_object, dict): response_object", "import from_date_string class SystemStatus: @staticmethod def Engine(response_object: dict): if not", "response_object = {} return system_status.UpgradeSummary( status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), completed_tasks=response_object.get('CompletedTasks'), target_version=response_object.get('TargetVersion'),", "versions=response_object.get('Versions'), ) @staticmethod def UpgradeStatus(response_object: dict): if not isinstance(response_object, dict):", "{} return system_status.Service( modules=response_object.get('modules'), time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True), status=response_object.get('Status'), )", "t in response_object.get('TasksPending', [])], tasks_running=[SystemStatus.Task(t) for t in response_object.get('TasksRunning', [])],", "start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'), ) @staticmethod def UpgradeInfo(response_object: dict): if not", "{} return system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')), tasks_completed=[SystemStatus.Task(t) for t", "SystemStatus: @staticmethod def Engine(response_object: dict): if not isinstance(response_object, dict): response_object", "def UpgradeInfo(response_object: dict): if not isinstance(response_object, dict): response_object = {}", "system_status.UpgradeInfo( id=response_object.get('Id'), start_time=from_date_string(response_object.get('StartTime')), versions=response_object.get('Versions'), ) @staticmethod def UpgradeStatus(response_object: dict): if", "isinstance(response_object, dict): response_object = {} return system_status.UpgradeStatus( engine=SystemStatus.Engine(response_object.get('Engine')), status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')),", "def Service(response_object: dict): if not isinstance(response_object, dict): response_object = {}", "response_object = {} return system_status.Task( display_name=response_object.get('DisplayName'), name=response_object.get('Name'), start_time=from_date_string(response_object.get('StartTime')), stop_time=from_date_string(response_object.get('StopTime')), warning_count=response_object.get('WarningCount'),", "dict): if not isinstance(response_object, dict): response_object = {} return system_status.Engine(", "dict): response_object = {} return system_status.Engine( dn=response_object.get('DN'), display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'), id=response_object.get('Id'),", "system_status from pytpp.tools.helpers.date_converter import from_date_string class SystemStatus: @staticmethod def Engine(response_object:", "time_since_first_seen=from_date_string(response_object.get('timeSinceFirstSeen'), duration_format=True), time_since_last_seen=from_date_string(response_object.get('timeSinceLastSeen'), duration_format=True), status=response_object.get('Status'), ) @staticmethod def SystemStatus(response_object: dict):", "class SystemStatus: @staticmethod def Engine(response_object: dict): if not isinstance(response_object, dict):", "response_object = {} return system_status.Services( vplatform=SystemStatus.Service(response_object.get('vPlatform')), log_server=SystemStatus.Service(response_object.get('logServer')), iis=SystemStatus.Service(response_object.get('iis')), ) @staticmethod", "isinstance(response_object, dict): response_object = {} return system_status.UpgradeSummary( status=response_object.get('Status'), upgrade_start_time=from_date_string(response_object.get('UpgradeStartTime')), upgrade_stop_time=from_date_string(response_object.get('UpgradeStopTime')),", "import system_status from pytpp.tools.helpers.date_converter import from_date_string class SystemStatus: @staticmethod def", ") @staticmethod def Services(response_object: dict): if not isinstance(response_object, dict): response_object", "isinstance(response_object, dict): response_object = {} return system_status.Engine( dn=response_object.get('DN'), display_name=response_object.get('DisplayName'), guid=response_object.get('Guid'),", "engine_name=response_object.get('engineName'), services=SystemStatus.Services(response_object.get('services')), version=response_object.get('version'), ) @staticmethod def Task(response_object: dict): if not" ]
[ "test_dataloader(self) -> DataLoader: return DataLoader(self.test_set, batch_size=32, num_workers=4) if __name__ ==", "tokenized_abstracts = tokenizer.batch_encode_plus( abstracts, padding=True, truncation=True, return_tensors=\"pt\" ) tokenized_titles =", "torch from omegaconf import OmegaConf from torch.utils.data import DataLoader, random_split", "DataLoader, random_split from transformers import T5Tokenizer from src.data.PaperDataset import PaperDataset", "= random_split( self.data, [self.config.n_train, self.config.n_val, self.config.n_test], generator=torch.Generator().manual_seed(1337), ) if stage", "DataLoader: return DataLoader(self.train_set, batch_size=32, num_workers=4) def val_dataloader(self) -> DataLoader: return", "__init__(self, config: str = \"src/data/config.yaml\") -> None: super().__init__() self.config =", "import pytorch_lightning as pl import torch from omegaconf import OmegaConf", "random_split( self.data, [self.config.n_train, self.config.n_val, self.config.n_test], generator=torch.Generator().manual_seed(1337), ) if stage ==", "prepare_data(self) -> None: # Add tokenizing tokenizer = T5Tokenizer.from_pretrained(\"t5-base\") titles,", "import OmegaConf from torch.utils.data import DataLoader, random_split from transformers import", "self.test_set = test def train_dataloader(self) -> DataLoader: return DataLoader(self.train_set, batch_size=32,", "= T5Tokenizer.from_pretrained(\"t5-base\") titles, abstracts = torch.load(\"data/processed/data.pt\").T #titles, abstracts = torch.load(\"data/processed/data.pt\").T", "pytorch_lightning as pl import torch from omegaconf import OmegaConf from", "OmegaConf from torch.utils.data import DataLoader, random_split from transformers import T5Tokenizer", "self.data, [self.config.n_train, self.config.n_val, self.config.n_test], generator=torch.Generator().manual_seed(1337), ) if stage == \"fit\"", "-> None: super().__init__() self.config = OmegaConf.load(config) def prepare_data(self) -> None:", "def train_dataloader(self) -> DataLoader: return DataLoader(self.train_set, batch_size=32, num_workers=4) def val_dataloader(self)", "transformers import T5Tokenizer from src.data.PaperDataset import PaperDataset class ArvixDataModule(pl.LightningDataModule): def", "stage == \"fit\" or stage is None: self.train_set = train", "PaperDataset(tokenized_abstracts, tokenized_titles) def setup(self, stage: Optional[str] = None): train, val,", "# Add tokenizing tokenizer = T5Tokenizer.from_pretrained(\"t5-base\") titles, abstracts = torch.load(\"data/processed/data.pt\").T", "super().__init__() self.config = OmegaConf.load(config) def prepare_data(self) -> None: # Add", "test def train_dataloader(self) -> DataLoader: return DataLoader(self.train_set, batch_size=32, num_workers=4) def", "= torch.load(\"data/processed/data.pt\").T tokenized_abstracts = tokenizer.batch_encode_plus( abstracts, padding=True, truncation=True, return_tensors=\"pt\" )", "titles, padding=True, truncation=True, return_tensors=\"pt\" ) self.data = PaperDataset(tokenized_abstracts, tokenized_titles) def", "-> DataLoader: return DataLoader(self.val_set, batch_size=32, num_workers=4) def test_dataloader(self) -> DataLoader:", "= torch.load(\"data/processed/data.pt\").T #titles, abstracts = torch.load(\"data/processed/data.pt\").T tokenized_abstracts = tokenizer.batch_encode_plus( abstracts,", "Optional import pytorch_lightning as pl import torch from omegaconf import", "PaperDataset class ArvixDataModule(pl.LightningDataModule): def __init__(self, config: str = \"src/data/config.yaml\") ->", "torch.utils.data import DataLoader, random_split from transformers import T5Tokenizer from src.data.PaperDataset", "None: self.train_set = train self.val_set = val if stage ==", "None: # Add tokenizing tokenizer = T5Tokenizer.from_pretrained(\"t5-base\") titles, abstracts =", "= None): train, val, test = random_split( self.data, [self.config.n_train, self.config.n_val,", "== \"test\": self.test_set = test def train_dataloader(self) -> DataLoader: return", "T5Tokenizer from src.data.PaperDataset import PaperDataset class ArvixDataModule(pl.LightningDataModule): def __init__(self, config:", "random_split from transformers import T5Tokenizer from src.data.PaperDataset import PaperDataset class", "tokenized_titles = tokenizer.batch_encode_plus( titles, padding=True, truncation=True, return_tensors=\"pt\" ) self.data =", "from torch.utils.data import DataLoader, random_split from transformers import T5Tokenizer from", "truncation=True, return_tensors=\"pt\" ) tokenized_titles = tokenizer.batch_encode_plus( titles, padding=True, truncation=True, return_tensors=\"pt\"", "self.config.n_val, self.config.n_test], generator=torch.Generator().manual_seed(1337), ) if stage == \"fit\" or stage", "def __init__(self, config: str = \"src/data/config.yaml\") -> None: super().__init__() self.config", "DataLoader: return DataLoader(self.val_set, batch_size=32, num_workers=4) def test_dataloader(self) -> DataLoader: return", "import DataLoader, random_split from transformers import T5Tokenizer from src.data.PaperDataset import", "test = random_split( self.data, [self.config.n_train, self.config.n_val, self.config.n_test], generator=torch.Generator().manual_seed(1337), ) if", "\"test\": self.test_set = test def train_dataloader(self) -> DataLoader: return DataLoader(self.train_set,", "train self.val_set = val if stage == \"test\": self.test_set =", "= OmegaConf.load(config) def prepare_data(self) -> None: # Add tokenizing tokenizer", "T5Tokenizer.from_pretrained(\"t5-base\") titles, abstracts = torch.load(\"data/processed/data.pt\").T #titles, abstracts = torch.load(\"data/processed/data.pt\").T tokenized_abstracts", "train_dataloader(self) -> DataLoader: return DataLoader(self.train_set, batch_size=32, num_workers=4) def val_dataloader(self) ->", "as pl import torch from omegaconf import OmegaConf from torch.utils.data", ") if stage == \"fit\" or stage is None: self.train_set", "#titles, abstracts = torch.load(\"data/processed/data.pt\").T tokenized_abstracts = tokenizer.batch_encode_plus( abstracts, padding=True, truncation=True,", "src.data.PaperDataset import PaperDataset class ArvixDataModule(pl.LightningDataModule): def __init__(self, config: str =", "torch.load(\"data/processed/data.pt\").T #titles, abstracts = torch.load(\"data/processed/data.pt\").T tokenized_abstracts = tokenizer.batch_encode_plus( abstracts, padding=True,", "= PaperDataset(tokenized_abstracts, tokenized_titles) def setup(self, stage: Optional[str] = None): train,", "val, test = random_split( self.data, [self.config.n_train, self.config.n_val, self.config.n_test], generator=torch.Generator().manual_seed(1337), )", "generator=torch.Generator().manual_seed(1337), ) if stage == \"fit\" or stage is None:", "if stage == \"fit\" or stage is None: self.train_set =", "stage: Optional[str] = None): train, val, test = random_split( self.data,", "num_workers=4) def val_dataloader(self) -> DataLoader: return DataLoader(self.val_set, batch_size=32, num_workers=4) def", "import torch from omegaconf import OmegaConf from torch.utils.data import DataLoader,", "ArvixDataModule(pl.LightningDataModule): def __init__(self, config: str = \"src/data/config.yaml\") -> None: super().__init__()", "= tokenizer.batch_encode_plus( titles, padding=True, truncation=True, return_tensors=\"pt\" ) self.data = PaperDataset(tokenized_abstracts,", "return_tensors=\"pt\" ) self.data = PaperDataset(tokenized_abstracts, tokenized_titles) def setup(self, stage: Optional[str]", "= \"src/data/config.yaml\") -> None: super().__init__() self.config = OmegaConf.load(config) def prepare_data(self)", "self.config.n_test], generator=torch.Generator().manual_seed(1337), ) if stage == \"fit\" or stage is", "= val if stage == \"test\": self.test_set = test def", "val_dataloader(self) -> DataLoader: return DataLoader(self.val_set, batch_size=32, num_workers=4) def test_dataloader(self) ->", "None: super().__init__() self.config = OmegaConf.load(config) def prepare_data(self) -> None: #", "from omegaconf import OmegaConf from torch.utils.data import DataLoader, random_split from", "omegaconf import OmegaConf from torch.utils.data import DataLoader, random_split from transformers", "import T5Tokenizer from src.data.PaperDataset import PaperDataset class ArvixDataModule(pl.LightningDataModule): def __init__(self,", ") self.data = PaperDataset(tokenized_abstracts, tokenized_titles) def setup(self, stage: Optional[str] =", "class ArvixDataModule(pl.LightningDataModule): def __init__(self, config: str = \"src/data/config.yaml\") -> None:", "def val_dataloader(self) -> DataLoader: return DataLoader(self.val_set, batch_size=32, num_workers=4) def test_dataloader(self)", "return_tensors=\"pt\" ) tokenized_titles = tokenizer.batch_encode_plus( titles, padding=True, truncation=True, return_tensors=\"pt\" )", "None): train, val, test = random_split( self.data, [self.config.n_train, self.config.n_val, self.config.n_test],", "if stage == \"test\": self.test_set = test def train_dataloader(self) ->", "= test def train_dataloader(self) -> DataLoader: return DataLoader(self.train_set, batch_size=32, num_workers=4)", "config: str = \"src/data/config.yaml\") -> None: super().__init__() self.config = OmegaConf.load(config)", "-> DataLoader: return DataLoader(self.test_set, batch_size=32, num_workers=4) if __name__ == \"__main__\":", "self.train_set = train self.val_set = val if stage == \"test\":", "\"src/data/config.yaml\") -> None: super().__init__() self.config = OmegaConf.load(config) def prepare_data(self) ->", "val if stage == \"test\": self.test_set = test def train_dataloader(self)", "batch_size=32, num_workers=4) def val_dataloader(self) -> DataLoader: return DataLoader(self.val_set, batch_size=32, num_workers=4)", "abstracts, padding=True, truncation=True, return_tensors=\"pt\" ) tokenized_titles = tokenizer.batch_encode_plus( titles, padding=True,", "abstracts = torch.load(\"data/processed/data.pt\").T #titles, abstracts = torch.load(\"data/processed/data.pt\").T tokenized_abstracts = tokenizer.batch_encode_plus(", "tokenizer.batch_encode_plus( titles, padding=True, truncation=True, return_tensors=\"pt\" ) self.data = PaperDataset(tokenized_abstracts, tokenized_titles)", "def setup(self, stage: Optional[str] = None): train, val, test =", "-> DataLoader: return DataLoader(self.train_set, batch_size=32, num_workers=4) def val_dataloader(self) -> DataLoader:", "-> None: # Add tokenizing tokenizer = T5Tokenizer.from_pretrained(\"t5-base\") titles, abstracts", "[self.config.n_train, self.config.n_val, self.config.n_test], generator=torch.Generator().manual_seed(1337), ) if stage == \"fit\" or", "import PaperDataset class ArvixDataModule(pl.LightningDataModule): def __init__(self, config: str = \"src/data/config.yaml\")", "def test_dataloader(self) -> DataLoader: return DataLoader(self.test_set, batch_size=32, num_workers=4) if __name__", "from transformers import T5Tokenizer from src.data.PaperDataset import PaperDataset class ArvixDataModule(pl.LightningDataModule):", "DataLoader(self.train_set, batch_size=32, num_workers=4) def val_dataloader(self) -> DataLoader: return DataLoader(self.val_set, batch_size=32,", "truncation=True, return_tensors=\"pt\" ) self.data = PaperDataset(tokenized_abstracts, tokenized_titles) def setup(self, stage:", "DataLoader: return DataLoader(self.test_set, batch_size=32, num_workers=4) if __name__ == \"__main__\": dm", "typing import Optional import pytorch_lightning as pl import torch from", "return DataLoader(self.test_set, batch_size=32, num_workers=4) if __name__ == \"__main__\": dm =", "padding=True, truncation=True, return_tensors=\"pt\" ) self.data = PaperDataset(tokenized_abstracts, tokenized_titles) def setup(self,", "self.config = OmegaConf.load(config) def prepare_data(self) -> None: # Add tokenizing", "stage is None: self.train_set = train self.val_set = val if", "\"fit\" or stage is None: self.train_set = train self.val_set =", "torch.load(\"data/processed/data.pt\").T tokenized_abstracts = tokenizer.batch_encode_plus( abstracts, padding=True, truncation=True, return_tensors=\"pt\" ) tokenized_titles", "or stage is None: self.train_set = train self.val_set = val", "DataLoader(self.val_set, batch_size=32, num_workers=4) def test_dataloader(self) -> DataLoader: return DataLoader(self.test_set, batch_size=32,", "from src.data.PaperDataset import PaperDataset class ArvixDataModule(pl.LightningDataModule): def __init__(self, config: str", "num_workers=4) def test_dataloader(self) -> DataLoader: return DataLoader(self.test_set, batch_size=32, num_workers=4) if", "str = \"src/data/config.yaml\") -> None: super().__init__() self.config = OmegaConf.load(config) def", "DataLoader(self.test_set, batch_size=32, num_workers=4) if __name__ == \"__main__\": dm = ArvixDataModule()", "tokenizing tokenizer = T5Tokenizer.from_pretrained(\"t5-base\") titles, abstracts = torch.load(\"data/processed/data.pt\").T #titles, abstracts", "self.data = PaperDataset(tokenized_abstracts, tokenized_titles) def setup(self, stage: Optional[str] = None):", "= tokenizer.batch_encode_plus( abstracts, padding=True, truncation=True, return_tensors=\"pt\" ) tokenized_titles = tokenizer.batch_encode_plus(", "Optional[str] = None): train, val, test = random_split( self.data, [self.config.n_train,", "tokenizer = T5Tokenizer.from_pretrained(\"t5-base\") titles, abstracts = torch.load(\"data/processed/data.pt\").T #titles, abstracts =", "abstracts = torch.load(\"data/processed/data.pt\").T tokenized_abstracts = tokenizer.batch_encode_plus( abstracts, padding=True, truncation=True, return_tensors=\"pt\"", "<gh_stars>0 from typing import Optional import pytorch_lightning as pl import", "setup(self, stage: Optional[str] = None): train, val, test = random_split(", "padding=True, truncation=True, return_tensors=\"pt\" ) tokenized_titles = tokenizer.batch_encode_plus( titles, padding=True, truncation=True,", "train, val, test = random_split( self.data, [self.config.n_train, self.config.n_val, self.config.n_test], generator=torch.Generator().manual_seed(1337),", "self.val_set = val if stage == \"test\": self.test_set = test", "from typing import Optional import pytorch_lightning as pl import torch", "tokenized_titles) def setup(self, stage: Optional[str] = None): train, val, test", "tokenizer.batch_encode_plus( abstracts, padding=True, truncation=True, return_tensors=\"pt\" ) tokenized_titles = tokenizer.batch_encode_plus( titles,", ") tokenized_titles = tokenizer.batch_encode_plus( titles, padding=True, truncation=True, return_tensors=\"pt\" ) self.data", "pl import torch from omegaconf import OmegaConf from torch.utils.data import", "import Optional import pytorch_lightning as pl import torch from omegaconf", "OmegaConf.load(config) def prepare_data(self) -> None: # Add tokenizing tokenizer =", "def prepare_data(self) -> None: # Add tokenizing tokenizer = T5Tokenizer.from_pretrained(\"t5-base\")", "== \"fit\" or stage is None: self.train_set = train self.val_set", "stage == \"test\": self.test_set = test def train_dataloader(self) -> DataLoader:", "return DataLoader(self.val_set, batch_size=32, num_workers=4) def test_dataloader(self) -> DataLoader: return DataLoader(self.test_set,", "= train self.val_set = val if stage == \"test\": self.test_set", "batch_size=32, num_workers=4) def test_dataloader(self) -> DataLoader: return DataLoader(self.test_set, batch_size=32, num_workers=4)", "is None: self.train_set = train self.val_set = val if stage", "return DataLoader(self.train_set, batch_size=32, num_workers=4) def val_dataloader(self) -> DataLoader: return DataLoader(self.val_set,", "Add tokenizing tokenizer = T5Tokenizer.from_pretrained(\"t5-base\") titles, abstracts = torch.load(\"data/processed/data.pt\").T #titles,", "titles, abstracts = torch.load(\"data/processed/data.pt\").T #titles, abstracts = torch.load(\"data/processed/data.pt\").T tokenized_abstracts =" ]
[ "self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotCorrFrame(self) self.plot_frame.Show() pub.sendMessage('corr.plot', message=msg)", "StepsDialog from PlotFrame import PlotFuncFrame, PlotCorrFrame import interface import mbox", "directory for the tree :param calc_type: calculation type \"\"\" self.calcTree.DeleteAllItems()", "[self.calcs[i] for i in getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation time: %7.2f s.' %", "enqueue_local(calc_dir): \"\"\" Enqueue a task on a local filesystem :param", "initialize calc list self.calcList.InsertColumn(0, 'Directory', width=180) self.calcList.InsertColumn(1, 'Type', width=70) self.calcList.InsertColumn(2,", "def enqueue_local(calc_dir): \"\"\" Enqueue a task on a local filesystem", "# queue putter on a local machine local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),", "enqueue a task :param user: user of a remote system", "== 0: self.plot_property() else: self.plot_correlation() def plot_property(self): # plot options", "else: self.plot_correlation() def plot_property(self): # plot options - get all", "all the data to plot ptype = self.propType.GetItems()[self.propType.GetSelection()] pchoice =", "# selection indices sind = getListCtrlSelection(self.calcList) if sind: # number", "it's not there if not os.path.isfile(config_file): os.makedirs(config_dir) open(config_file, 'w').close() config", "config.set(\"general\", \"root_dir\", root_dir) else: sys.exit(1) with open(config_file, 'w') as f:", "not None else '') return 0 def on_enqueue_press(self, _): from", "not None: q = 'slurm' else: mbox.JobSubmit(None, ()) return -1", "import subprocess import wx import ConfigParser from wx.lib.mixins.listctrl import getListCtrlSelection", "subprocess.Popen(['/bin/bash', comm, '-d=' + calc_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) mbox.JobSubmit(q, submit.communicate()) @staticmethod", "from sshutils import getSSHClient, getQueue, copyFile, removeFile, runCommand ssh =", "def downBtnPress(self, event): # current list count clc = self.calcList.GetItemCount()", "parent = self.calcTree.GetItemParent(item) path = [self.calcTree.GetItemText(item)] while parent.IsOk(): path.append(self.calcTree.GetItemText(parent)) parent", "a task :return: error code (0 is OK) \"\"\" from", "self.propType.GetItems()[self.propType.GetSelection()] pchoice = self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class = self.propChoices.dataClass(ptype, pchoice) leg =", "PBS, sinfo - SLURM) q = getQueue(ssh) if q is", "+= 1 return 0 return 1 def downBtnPress(self, event): #", "dialog dlg = StepsDialog(None) if dlg.ShowModal() == wx.ID_OK: r =", "error_code (0 is OK) \"\"\" import distutils.spawn # find which", "t1)) msg = plot_data try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame", "ancdirs = dir_path.split(os.sep)[r:] if nsteps is not None: ancdirs[-1] +=", "wx.PyDeadObjectError): self.plot_frame = PlotFuncFrame(self) self.plot_frame.Show() pub.sendMessage('data.plot', message=msg) def plot_correlation(self): #", "path = [self.calcTree.GetItemText(item)] while parent.IsOk(): path.append(self.calcTree.GetItemText(parent)) parent = self.calcTree.GetItemParent(parent) #", "return calc_dir # return os.sep.join((self.root, calc_dir)) def onSelChange(self, event): #", "plot_data = interface.getData(ptype, data_class, leg, [self.calcs[i] for i in getListCtrlSelection(self.calcList)])", "getRemoteDir # on which device are we? calc_dir = self.get_selection_dir()", "interface.getCorr(xchoice, ychoice, [self.calcs[i] for i in getListCtrlSelection(self.calcList)]) msg = [leg,", "plot_data try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotFuncFrame(self) self.plot_frame.Show()", "propTypeChange(self, event): # property type pt_num = self.propType.GetSelection() pt =", "the data to plot xchoice = self.xCorr.GetSelection() ychoice = self.yCorr.GetSelection()", "and create one if it's not there if not os.path.isfile(config_file):", "on a remote filesystem :param calc_dir: calculation directory on a", "putter = q + '.sh' sftp = copyFile(ssh, putter, local_dir,", "sshutils import getMount, getDevice, getRemoteDir # on which device are", "\"\"\" import distutils.spawn # find which queue system is implemented", "@staticmethod def enqueue_local(calc_dir): \"\"\" Enqueue a task on a local", "self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0) self.propChoice.SetSelection(0) self.xCorr.SetSelection(0) self.yCorr.SetSelection(0) # initialize calc tree self.build_tree(self.root,", "time import subprocess import wx import ConfigParser from wx.lib.mixins.listctrl import", "+ '.sh')) submit = subprocess.Popen(['/bin/bash', comm, '-d=' + calc_dir], stdout=subprocess.PIPE,", "sinfo - SLURM) if distutils.spawn.find_executable('qstat') is not None: q =", "filesystem :param host: host where to enqueue a task :param", "+ '.sh' sftp = copyFile(ssh, putter, local_dir, calc_dir) remote_file =", "import distutils.spawn # find which queue system is implemented on", "else: sys.exit(1) with open(config_file, 'w') as f: config.write(f) return root_dir", "- ds) self.calcList.DeleteItem(si - ds) ds += 1 return 0", "ssh.close() def plotBtnPress(self, event): if self.noteBook.GetSelection() == 0: self.plot_property() else:", "config.read(config_file) # if config exists and has needed option if", "nsteps = interface.GetNumMDESteps(dir_path) ancdirs = dir_path.split(os.sep)[r:] if nsteps is not", "enqueue_remote(calc_dir, host, user): \"\"\" Enqueue a task on a remote", "'w') as f: config.write(f) return root_dir def build_tree(self, root, calc_type):", "local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q)) putter = q + '.sh'", "wx.lib.mixins.listctrl import getListCtrlSelection from wx.lib.pubsub import pub from gui.RootGUI import", "time.clock() plot_data = interface.getData(ptype, data_class, leg, [self.calcs[i] for i in", "ychoice, [self.calcs[i] for i in getListCtrlSelection(self.calcList)]) msg = [leg, data,", "putter) stdout, stderr = runCommand(ssh, 'bash ' + remote_file +", "a new root element and then its children :param root:", "interface.isCalcOfType(calc_type, dn=dir_names, fn=file_names): # find the number of steps in", "for i in getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation time: %7.2f s.' % (time.clock()", "\"\"\" Adds a new root element and then its children", "'pbs' elif distutils.spawn.find_executable('sinfo') is not None: q = 'slurm' else:", "self.calcTree.AppendItem(ids[ad], ancdir) self.calcTree.SortChildren(ids[ad]) ad = d def get_selection_dir(self): item =", "try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotCorrFrame(self) self.plot_frame.Show() pub.sendMessage('corr.plot',", "enter dialog dlg = StepsDialog(None) if dlg.ShowModal() == wx.ID_OK: r", "self.plot_frame.Show() pub.sendMessage('data.plot', message=msg) def plot_correlation(self): # correlate options - get", "def typeChange(self, event): ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root, ctype) def upBtnPress(self,", "self.propChoices.classes(calc_data_types[0]) corr_classes = self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0) self.propChoice.SetSelection(0)", "calcs = [] plot_frame = None def __init__(self, *args, **kwds):", "in device_type: user, host_dir = device_name.split('@') hostname, remote_mount_path = host_dir.split(':')", "if not interface.isCalcOfType(ctype, dir=cdir): mbox.NoResults(cdir, ctype) return 1 # init", "None: q = 'slurm' else: mbox.JobSubmit(None, ()) return -1 comm", "'..', q, q + '.sh')) submit = subprocess.Popen(['/bin/bash', comm, '-d='", "[self.calcs[i] for i in getListCtrlSelection(self.calcList)]) msg = [leg, data, info]", "calc_dir: calculation directory on a local filesystem :return: error_code (0", "SLURM) if distutils.spawn.find_executable('qstat') is not None: q = 'pbs' elif", "user, host_dir = device_name.split('@') hostname, remote_mount_path = host_dir.split(':') remote_dir =", "root directory fr GUI based on config file :return: Root", "calc_dir = self.get_selection_dir() mount_path = getMount(calc_dir) device_name, device_type = getDevice(mount_path)", "# current list count clc = self.calcList.GetItemCount() # calculation type", "in os.walk(root): if interface.isCalcOfType(calc_type, dn=dir_names, fn=file_names): # find the number", "root, calc_type): \"\"\" Adds a new root element and then", "calc list self.calcList.InsertColumn(0, 'Directory', width=180) self.calcList.InsertColumn(1, 'Type', width=70) self.calcList.InsertColumn(2, 'NSteps',", "== wx.ID_OK: root_dir = dlg.GetPath() config.set(\"general\", \"root_dir\", root_dir) else: sys.exit(1)", "a remote system who enqueues a task :return: error code", "ad = root for ancdir in ancdirs: d = os.path.join(ad,", "dir=cdir): self.enqueueBtn.Enable() else: self.enqueueBtn.Enable(False) def propTypeChange(self, event): # property type", "\"Select root directory\") if dlg.ShowModal() == wx.ID_OK: root_dir = dlg.GetPath()", "self.calcTree.GetItemParent(item) path = [self.calcTree.GetItemText(item)] while parent.IsOk(): path.append(self.calcTree.GetItemText(parent)) parent = self.calcTree.GetItemParent(parent)", "remote_dir = getRemoteDir(calc_dir, mount_path, remote_mount_path) self.enqueue_remote(remote_dir, hostname, user) else: self.enqueue_local(calc_dir)", "is not None: q = 'slurm' else: mbox.JobSubmit(None, ()) return", ":param host: host where to enqueue a task :param user:", "quickly nsteps = interface.GetNumMDESteps(dir_path) ancdirs = dir_path.split(os.sep)[r:] if nsteps is", "correlate options - get all the data to plot xchoice", "from sshutils import getMount, getDevice, getRemoteDir # on which device", "r = len(root.split(os.sep)) ids = {root: self.calcTree.AddRoot(root)} for (dir_path, dir_names,", "# calculation directory cdir = self.get_selection_dir() if interface.isCalcOfType(ctype, dir=cdir): self.enqueueBtn.Enable()", "2, str(len(r)) if r is not None else '') return", "mount_path, remote_mount_path) self.enqueue_remote(remote_dir, hostname, user) else: self.enqueue_local(calc_dir) @staticmethod def enqueue_local(calc_dir):", "plot_property(self): # plot options - get all the data to", "sind: self.calcs.pop(si - ds) self.calcList.DeleteItem(si - ds) ds += 1", "remote filesystem :param host: host where to enqueue a task", "dlg.Destroy() self.calcs.append(interface.getCalc(cdir, ctype, r)) self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc, 1, ctype) self.calcList.SetStringItem(clc,", "-*- coding: utf-8 -*- import os import sys import time", "children :param root: root directory for the tree :param calc_type:", "distutils.spawn.find_executable('sinfo') is not None: q = 'slurm' else: mbox.JobSubmit(None, ())", "s.' % (time.clock() - t1)) msg = plot_data try: self.plot_frame.Raise()", "# number of deleted strings ds = 0 for si", ":param calc_dir: calculation directory on a remote filesystem :param host:", "d in ids: ids[d] = self.calcTree.AppendItem(ids[ad], ancdir) self.calcTree.SortChildren(ids[ad]) ad =", "ancdir) if not d in ids: ids[d] = self.calcTree.AppendItem(ids[ad], ancdir)", "local filesystem :return: error_code (0 is OK) \"\"\" import distutils.spawn", "path.append(self.calcTree.GetItemText(parent)) parent = self.calcTree.GetItemParent(parent) # calculation directory calc_dir = os.sep.join(path[::-1]).split()[0]", "OK) \"\"\" import distutils.spawn # find which queue system is", "ids: ids[d] = self.calcTree.AppendItem(ids[ad], ancdir) self.calcTree.SortChildren(ids[ad]) ad = d def", "system who enqueues a task :return: error code (0 is", "self.calcs.append(interface.getCalc(cdir, ctype, r)) self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc, 1, ctype) self.calcList.SetStringItem(clc, 2,", "event): # selection indices sind = getListCtrlSelection(self.calcList) if sind: #", "options - get all the data to plot ptype =", "a task on a local filesystem :param calc_dir: calculation directory", "PlotCorrFrame import interface import mbox class RootFrame(RootGUI): calcs = []", "its children :param root: root directory for the tree :param", "0 for si in sind: self.calcs.pop(si - ds) self.calcList.DeleteItem(si -", "# init steps range r = None if ctype in", "config_file = os.path.join(config_dir, \"shs_gui.cfg\") # check the file and create", "= 'slurm' else: mbox.JobSubmit(None, ()) return -1 comm = os.path.abspath(os.path.join(os.path.dirname(__file__),", "self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class = self.propChoices.dataClass(ptype, pchoice) leg = [self.calcList.GetItemText(i) for i", "tree self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) # initialize calc list self.calcList.InsertColumn(0, 'Directory', width=180)", "remote_file = os.path.join(calc_dir, putter) stdout, stderr = runCommand(ssh, 'bash '", "= os.path.join(calc_dir, putter) stdout, stderr = runCommand(ssh, 'bash ' +", "os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q, q + '.sh')) submit = subprocess.Popen(['/bin/bash', comm,", "return 0 def on_enqueue_press(self, _): from sshutils import getMount, getDevice,", "local machine local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q)) putter = q", "self.plot_property() else: self.plot_correlation() def plot_property(self): # plot options - get", "root_dir) else: sys.exit(1) with open(config_file, 'w') as f: config.write(f) return", ":param calc_type: calculation type \"\"\" self.calcTree.DeleteAllItems() r = len(root.split(os.sep)) ids", "number of steps in MDE file, quickly nsteps = interface.GetNumMDESteps(dir_path)", "plot xchoice = self.xCorr.GetSelection() ychoice = self.yCorr.GetSelection() leg = [self.calcList.GetItemText(i)", "calc_dir: calculation directory on a remote filesystem :param host: host", "tree :param calc_type: calculation type \"\"\" self.calcTree.DeleteAllItems() r = len(root.split(os.sep))", "%7.2f s.' % (time.clock() - t1)) msg = plot_data try:", "= getRemoteDir(calc_dir, mount_path, remote_mount_path) self.enqueue_remote(remote_dir, hostname, user) else: self.enqueue_local(calc_dir) @staticmethod", "ds) ds += 1 return 0 return 1 def downBtnPress(self,", "dlg.GetPath() config.set(\"general\", \"root_dir\", root_dir) else: sys.exit(1) with open(config_file, 'w') as", "xchoice = self.xCorr.GetSelection() ychoice = self.yCorr.GetSelection() leg = [self.calcList.GetItemText(i) for", "# initialize calc list self.calcList.InsertColumn(0, 'Directory', width=180) self.calcList.InsertColumn(1, 'Type', width=70)", "0: self.plot_property() else: self.plot_correlation() def plot_property(self): # plot options -", "0 def on_enqueue_press(self, _): from sshutils import getMount, getDevice, getRemoteDir", "host where to enqueue a task :param user: user of", "is None: mbox.JobSubmit(None, ()) return None # queue putter on", "= plot_data try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotFuncFrame(self)", "leg = [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] t1 = time.clock()", "ctype) def upBtnPress(self, event): # selection indices sind = getListCtrlSelection(self.calcList)", "is not None: q = 'pbs' elif distutils.spawn.find_executable('sinfo') is not", "directory on a remote filesystem :param host: host where to", "ds = 0 for si in sind: self.calcs.pop(si - ds)", "# on which device are we? calc_dir = self.get_selection_dir() mount_path", "ConfigParser from wx.lib.mixins.listctrl import getListCtrlSelection from wx.lib.pubsub import pub from", "data, info] try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotCorrFrame(self)", "q + '.sh' sftp = copyFile(ssh, putter, local_dir, calc_dir) remote_file", "in ('.output', '.ANI'): # enter dialog dlg = StepsDialog(None) if", "calculation directory on a remote filesystem :param host: host where", "PlotFrame import PlotFuncFrame, PlotCorrFrame import interface import mbox class RootFrame(RootGUI):", "d def get_selection_dir(self): item = self.calcTree.GetSelection() parent = self.calcTree.GetItemParent(item) path", "= host_dir.split(':') remote_dir = getRemoteDir(calc_dir, mount_path, remote_mount_path) self.enqueue_remote(remote_dir, hostname, user)", "self.calcTree.SortChildren(ids[ad]) ad = d def get_selection_dir(self): item = self.calcTree.GetSelection() parent", "removeFile(sftp, remote_file) ssh.close() def plotBtnPress(self, event): if self.noteBook.GetSelection() == 0:", "self.enqueueBtn.Enable(False) def propTypeChange(self, event): # property type pt_num = self.propType.GetSelection()", "def onSelChange(self, event): # calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) #", "distutils.spawn.find_executable('qstat') is not None: q = 'pbs' elif distutils.spawn.find_executable('sinfo') is", "self.enqueue_remote(remote_dir, hostname, user) else: self.enqueue_local(calc_dir) @staticmethod def enqueue_local(calc_dir): \"\"\" Enqueue", "{root: self.calcTree.AddRoot(root)} for (dir_path, dir_names, file_names) in os.walk(root): if interface.isCalcOfType(calc_type,", "of steps in MDE file, quickly nsteps = interface.GetNumMDESteps(dir_path) ancdirs", "\"\"\" config_dir = os.path.expanduser(\"~/.local/shs\") config_file = os.path.join(config_dir, \"shs_gui.cfg\") # check", "= self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory cdir = self.get_selection_dir() if interface.isCalcOfType(ctype,", "1 def downBtnPress(self, event): # current list count clc =", "new root element and then its children :param root: root", "self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0) self.propChoice.SetSelection(0) self.xCorr.SetSelection(0) self.yCorr.SetSelection(0) # initialize calc", "self.propChoices = interface.dataClasses() calc_data_types = self.propChoices.types() calc_data_classes = self.propChoices.classes(calc_data_types[0]) corr_classes", "mbox.JobSubmit(None, ()) return None # queue putter on a local", "except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotFuncFrame(self) self.plot_frame.Show() pub.sendMessage('data.plot', message=msg) def", "exists and has needed option if config.has_option(\"general\", \"root_dir\"): return config.get(\"general\",", "in getListCtrlSelection(self.calcList)]) msg = [leg, data, info] try: self.plot_frame.Raise() except", "PBS, sinfo - SLURM) if distutils.spawn.find_executable('qstat') is not None: q", ":param calc_dir: calculation directory on a local filesystem :return: error_code", "directory fr GUI based on config file :return: Root directory", "with open(config_file, 'w') as f: config.write(f) return root_dir def build_tree(self,", "if sind: # number of deleted strings ds = 0", "self.calcList.InsertColumn(1, 'Type', width=70) self.calcList.InsertColumn(2, 'NSteps', width=100) def set_root(self): \"\"\" Sets", "= self.calcTree.AppendItem(ids[ad], ancdir) self.calcTree.SortChildren(ids[ad]) ad = d def get_selection_dir(self): item", "stderr=subprocess.PIPE) mbox.JobSubmit(q, submit.communicate()) @staticmethod def enqueue_remote(calc_dir, host, user): \"\"\" Enqueue", "a local machine local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q)) putter =", "getSSHClient(host, user) # find which queue system is implemented on", "sys.exit(1) with open(config_file, 'w') as f: config.write(f) return root_dir def", "on config file :return: Root directory \"\"\" config_dir = os.path.expanduser(\"~/.local/shs\")", "else: self.enqueueBtn.Enable(False) def propTypeChange(self, event): # property type pt_num =", "from StepsDialog import StepsDialog from PlotFrame import PlotFuncFrame, PlotCorrFrame import", "getRemoteDir(calc_dir, mount_path, remote_mount_path) self.enqueue_remote(remote_dir, hostname, user) else: self.enqueue_local(calc_dir) @staticmethod def", "for i in getListCtrlSelection(self.calcList)]) msg = [leg, data, info] try:", "self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0) def typeChange(self, event): ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root,", "remote_mount_path) self.enqueue_remote(remote_dir, hostname, user) else: self.enqueue_local(calc_dir) @staticmethod def enqueue_local(calc_dir): \"\"\"", "= self.propType.GetSelection() pt = self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0) def typeChange(self, event):", "import pub from gui.RootGUI import RootGUI from StepsDialog import StepsDialog", "for (dir_path, dir_names, file_names) in os.walk(root): if interface.isCalcOfType(calc_type, dn=dir_names, fn=file_names):", "self.calcList.GetItemCount() # calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory", "build_tree(self, root, calc_type): \"\"\" Adds a new root element and", "ctype in ('.output', '.ANI'): # enter dialog dlg = StepsDialog(None)", "calc_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) mbox.JobSubmit(q, submit.communicate()) @staticmethod def enqueue_remote(calc_dir, host, user):", "a remote filesystem :param host: host where to enqueue a", "pt = self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0) def typeChange(self, event): ctype =", "= self.propChoices.dataClass(ptype, pchoice) leg = [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)]", "+ remote_file + ' -d=' + calc_dir) mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines())))", "None else '') return 0 def on_enqueue_press(self, _): from sshutils", "one if it's not there if not os.path.isfile(config_file): os.makedirs(config_dir) open(config_file,", "config exists and has needed option if config.has_option(\"general\", \"root_dir\"): return", "on a local filesystem :return: error_code (0 is OK) \"\"\"", "# check the file and create one if it's not", "None # queue putter on a local machine local_dir =", "mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines()))) removeFile(sftp, remote_file) ssh.close() def plotBtnPress(self, event): if", "device_type: user, host_dir = device_name.split('@') hostname, remote_mount_path = host_dir.split(':') remote_dir", "def enqueue_remote(calc_dir, host, user): \"\"\" Enqueue a task on a", "= subprocess.Popen(['/bin/bash', comm, '-d=' + calc_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) mbox.JobSubmit(q, submit.communicate())", "= copyFile(ssh, putter, local_dir, calc_dir) remote_file = os.path.join(calc_dir, putter) stdout,", "type pt_num = self.propType.GetSelection() pt = self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0) def", "self.propType.SetSelection(0) self.propChoice.SetSelection(0) self.xCorr.SetSelection(0) self.yCorr.SetSelection(0) # initialize calc tree self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()))", "of deleted strings ds = 0 for si in sind:", "RootGUI from StepsDialog import StepsDialog from PlotFrame import PlotFuncFrame, PlotCorrFrame", "on a local filesystem :param calc_dir: calculation directory on a", "set root self.root = self.set_root() # initialize choices self.propChoices =", "q, q + '.sh')) submit = subprocess.Popen(['/bin/bash', comm, '-d=' +", "coding: utf-8 -*- import os import sys import time import", "user) # find which queue system is implemented on cluster", "r)) self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc, 1, ctype) self.calcList.SetStringItem(clc, 2, str(len(r)) if", "config file :return: Root directory \"\"\" config_dir = os.path.expanduser(\"~/.local/shs\") config_file", "interface.isCalcOfType(ctype, dir=cdir): mbox.NoResults(cdir, ctype) return 1 # init steps range", "data to plot ptype = self.propType.GetItems()[self.propType.GetSelection()] pchoice = self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class", "open(config_file, 'w').close() config = ConfigParser.ConfigParser() config.read(config_file) # if config exists", "make config if not config.has_section(\"general\"): config.add_section(\"general\") dlg = wx.DirDialog(self, \"Select", "\"root_dir\") # make config if not config.has_section(\"general\"): config.add_section(\"general\") dlg =", "# return os.sep.join((self.root, calc_dir)) def onSelChange(self, event): # calculation type", "all the data to plot xchoice = self.xCorr.GetSelection() ychoice =", "self.enqueueBtn.Enable() else: self.enqueueBtn.Enable(False) def propTypeChange(self, event): # property type pt_num", "clc = self.calcList.GetItemCount() # calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) #", "= os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q, q + '.sh')) submit = subprocess.Popen(['/bin/bash',", "initialize choices self.propChoices = interface.dataClasses() calc_data_types = self.propChoices.types() calc_data_classes =", "import ConfigParser from wx.lib.mixins.listctrl import getListCtrlSelection from wx.lib.pubsub import pub", "ConfigParser.ConfigParser() config.read(config_file) # if config exists and has needed option", "i in getListCtrlSelection(self.calcList)] data, info = interface.getCorr(xchoice, ychoice, [self.calcs[i] for", "()) return None # queue putter on a local machine", "def plotBtnPress(self, event): if self.noteBook.GetSelection() == 0: self.plot_property() else: self.plot_correlation()", "directory \"\"\" config_dir = os.path.expanduser(\"~/.local/shs\") config_file = os.path.join(config_dir, \"shs_gui.cfg\") #", "ctype, r)) self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc, 1, ctype) self.calcList.SetStringItem(clc, 2, str(len(r))", "onSelChange(self, event): # calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation", "\"\"\" Sets root directory fr GUI based on config file", "info = interface.getCorr(xchoice, ychoice, [self.calcs[i] for i in getListCtrlSelection(self.calcList)]) msg", "'ssh' in device_type: user, host_dir = device_name.split('@') hostname, remote_mount_path =", "get_selection_dir(self): item = self.calcTree.GetSelection() parent = self.calcTree.GetItemParent(item) path = [self.calcTree.GetItemText(item)]", "= interface.getData(ptype, data_class, leg, [self.calcs[i] for i in getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation", "= StepsDialog(None) if dlg.ShowModal() == wx.ID_OK: r = dlg.GetRange() dlg.Destroy()", "- SLURM) if distutils.spawn.find_executable('qstat') is not None: q = 'pbs'", "'-d=' + calc_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) mbox.JobSubmit(q, submit.communicate()) @staticmethod def enqueue_remote(calc_dir,", "**kwds) # set root self.root = self.set_root() # initialize choices", "mbox class RootFrame(RootGUI): calcs = [] plot_frame = None def", "on_enqueue_press(self, _): from sshutils import getMount, getDevice, getRemoteDir # on", "mbox.JobSubmit(None, ()) return -1 comm = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q, q", "are we? calc_dir = self.get_selection_dir() mount_path = getMount(calc_dir) device_name, device_type", "None: mbox.JobSubmit(None, ()) return None # queue putter on a", "\"\"\" Enqueue a task on a remote filesystem :param calc_dir:", "r is not None else '') return 0 def on_enqueue_press(self,", "local_dir, calc_dir) remote_file = os.path.join(calc_dir, putter) stdout, stderr = runCommand(ssh,", "calc_type: calculation type \"\"\" self.calcTree.DeleteAllItems() r = len(root.split(os.sep)) ids =", "is OK) \"\"\" from sshutils import getSSHClient, getQueue, copyFile, removeFile,", "distutils.spawn # find which queue system is implemented on cluster", "on a remote filesystem :param host: host where to enqueue", "class RootFrame(RootGUI): calcs = [] plot_frame = None def __init__(self,", "host: host where to enqueue a task :param user: user", "' + remote_file + ' -d=' + calc_dir) mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()),", "if dlg.ShowModal() == wx.ID_OK: root_dir = dlg.GetPath() config.set(\"general\", \"root_dir\", root_dir)", "type \"\"\" self.calcTree.DeleteAllItems() r = len(root.split(os.sep)) ids = {root: self.calcTree.AddRoot(root)}", "sftp = copyFile(ssh, putter, local_dir, calc_dir) remote_file = os.path.join(calc_dir, putter)", "user) else: self.enqueue_local(calc_dir) @staticmethod def enqueue_local(calc_dir): \"\"\" Enqueue a task", "cdir = self.get_selection_dir() if not interface.isCalcOfType(ctype, dir=cdir): mbox.NoResults(cdir, ctype) return", "1 return 0 return 1 def downBtnPress(self, event): # current", "else: mbox.JobSubmit(None, ()) return -1 comm = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q,", "import PlotFuncFrame, PlotCorrFrame import interface import mbox class RootFrame(RootGUI): calcs", "a task on a remote filesystem :param calc_dir: calculation directory", "os.path.join(calc_dir, putter) stdout, stderr = runCommand(ssh, 'bash ' + remote_file", "import StepsDialog from PlotFrame import PlotFuncFrame, PlotCorrFrame import interface import", "mbox.JobSubmit(q, submit.communicate()) @staticmethod def enqueue_remote(calc_dir, host, user): \"\"\" Enqueue a", "root for ancdir in ancdirs: d = os.path.join(ad, ancdir) if", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) mbox.JobSubmit(q, submit.communicate()) @staticmethod def enqueue_remote(calc_dir, host, user): \"\"\"", "of a remote system who enqueues a task :return: error", "data_class, leg, [self.calcs[i] for i in getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation time: %7.2f", "i in getListCtrlSelection(self.calcList)]) msg = [leg, data, info] try: self.plot_frame.Raise()", "copyFile(ssh, putter, local_dir, calc_dir) remote_file = os.path.join(calc_dir, putter) stdout, stderr", "user of a remote system who enqueues a task :return:", "sys import time import subprocess import wx import ConfigParser from", "os.makedirs(config_dir) open(config_file, 'w').close() config = ConfigParser.ConfigParser() config.read(config_file) # if config", "element and then its children :param root: root directory for", "[%i]' % nsteps ad = root for ancdir in ancdirs:", "= root for ancdir in ancdirs: d = os.path.join(ad, ancdir)", "= 'pbs' elif distutils.spawn.find_executable('sinfo') is not None: q = 'slurm'", "strings ds = 0 for si in sind: self.calcs.pop(si -", "a local filesystem :return: error_code (0 is OK) \"\"\" import", "self.SetStatusText('Calculation time: %7.2f s.' % (time.clock() - t1)) msg =", "StepsDialog import StepsDialog from PlotFrame import PlotFuncFrame, PlotCorrFrame import interface", "def __init__(self, *args, **kwds): super(RootFrame, self).__init__(*args, **kwds) # set root", "not None: ancdirs[-1] += ' [%i]' % nsteps ad =", "def plot_property(self): # plot options - get all the data", "list self.calcList.InsertColumn(0, 'Directory', width=180) self.calcList.InsertColumn(1, 'Type', width=70) self.calcList.InsertColumn(2, 'NSteps', width=100)", "open(config_file, 'w') as f: config.write(f) return root_dir def build_tree(self, root,", "if config.has_option(\"general\", \"root_dir\"): return config.get(\"general\", \"root_dir\") # make config if", "def propTypeChange(self, event): # property type pt_num = self.propType.GetSelection() pt", "parent = self.calcTree.GetItemParent(parent) # calculation directory calc_dir = os.sep.join(path[::-1]).split()[0] return", "if q is None: mbox.JobSubmit(None, ()) return None # queue", "while parent.IsOk(): path.append(self.calcTree.GetItemText(parent)) parent = self.calcTree.GetItemParent(parent) # calculation directory calc_dir", "cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc, 1, ctype) self.calcList.SetStringItem(clc, 2, str(len(r)) if r is", "calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory cdir =", "is implemented on cluster (qstat - PBS, sinfo - SLURM)", "interface.getData(ptype, data_class, leg, [self.calcs[i] for i in getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation time:", "# calculation directory cdir = self.get_selection_dir() if not interface.isCalcOfType(ctype, dir=cdir):", "interface.GetNumMDESteps(dir_path) ancdirs = dir_path.split(os.sep)[r:] if nsteps is not None: ancdirs[-1]", "import sys import time import subprocess import wx import ConfigParser", "if 'ssh' in device_type: user, host_dir = device_name.split('@') hostname, remote_mount_path", "is OK) \"\"\" import distutils.spawn # find which queue system", "# initialize choices self.propChoices = interface.dataClasses() calc_data_types = self.propChoices.types() calc_data_classes", "ptype = self.propType.GetItems()[self.propType.GetSelection()] pchoice = self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class = self.propChoices.dataClass(ptype, pchoice)", "self.xCorr.GetSelection() ychoice = self.yCorr.GetSelection() leg = [self.calcList.GetItemText(i) for i in", "number of deleted strings ds = 0 for si in", "Enqueue a task on a local filesystem :param calc_dir: calculation", "self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory cdir = self.get_selection_dir() if interface.isCalcOfType(ctype, dir=cdir):", "# initialize calc tree self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) # initialize calc list", "width=70) self.calcList.InsertColumn(2, 'NSteps', width=100) def set_root(self): \"\"\" Sets root directory", "q + '.sh')) submit = subprocess.Popen(['/bin/bash', comm, '-d=' + calc_dir],", "self.get_selection_dir() if not interface.isCalcOfType(ctype, dir=cdir): mbox.NoResults(cdir, ctype) return 1 #", "remote_file + ' -d=' + calc_dir) mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines()))) removeFile(sftp,", ":return: error code (0 is OK) \"\"\" from sshutils import", "in getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation time: %7.2f s.' % (time.clock() - t1))", "= interface.getCorr(xchoice, ychoice, [self.calcs[i] for i in getListCtrlSelection(self.calcList)]) msg =", "= self.calcTree.GetSelection() parent = self.calcTree.GetItemParent(item) path = [self.calcTree.GetItemText(item)] while parent.IsOk():", "os.sep.join(path[::-1]).split()[0] return calc_dir # return os.sep.join((self.root, calc_dir)) def onSelChange(self, event):", "comm = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q, q + '.sh')) submit =", "event): if self.noteBook.GetSelection() == 0: self.plot_property() else: self.plot_correlation() def plot_property(self):", "directory cdir = self.get_selection_dir() if not interface.isCalcOfType(ctype, dir=cdir): mbox.NoResults(cdir, ctype)", "# correlate options - get all the data to plot", "steps in MDE file, quickly nsteps = interface.GetNumMDESteps(dir_path) ancdirs =", "mount_path = getMount(calc_dir) device_name, device_type = getDevice(mount_path) if 'ssh' in", "[self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] data, info = interface.getCorr(xchoice, ychoice,", "copyFile, removeFile, runCommand ssh = getSSHClient(host, user) # find which", "+ ' -d=' + calc_dir) mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines()))) removeFile(sftp, remote_file)", "os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q)) putter = q + '.sh' sftp =", "not os.path.isfile(config_file): os.makedirs(config_dir) open(config_file, 'w').close() config = ConfigParser.ConfigParser() config.read(config_file) #", "= dlg.GetPath() config.set(\"general\", \"root_dir\", root_dir) else: sys.exit(1) with open(config_file, 'w')", "fr GUI based on config file :return: Root directory \"\"\"", "queue putter on a local machine local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',", "sshutils import getSSHClient, getQueue, copyFile, removeFile, runCommand ssh = getSSHClient(host,", "= [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] data, info = interface.getCorr(xchoice,", "= os.path.expanduser(\"~/.local/shs\") config_file = os.path.join(config_dir, \"shs_gui.cfg\") # check the file", "corr_classes = self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0) self.propChoice.SetSelection(0) self.xCorr.SetSelection(0)", "= self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0) def typeChange(self, event): ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())", "as f: config.write(f) return root_dir def build_tree(self, root, calc_type): \"\"\"", "= [self.calcTree.GetItemText(item)] while parent.IsOk(): path.append(self.calcTree.GetItemText(parent)) parent = self.calcTree.GetItemParent(parent) # calculation", "pub from gui.RootGUI import RootGUI from StepsDialog import StepsDialog from", "in MDE file, quickly nsteps = interface.GetNumMDESteps(dir_path) ancdirs = dir_path.split(os.sep)[r:]", "dlg.GetRange() dlg.Destroy() self.calcs.append(interface.getCalc(cdir, ctype, r)) self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc, 1, ctype)", "a remote filesystem :param calc_dir: calculation directory on a remote", "calc_data_types = self.propChoices.types() calc_data_classes = self.propChoices.classes(calc_data_types[0]) corr_classes = self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types)", "get all the data to plot ptype = self.propType.GetItems()[self.propType.GetSelection()] pchoice", "host, user): \"\"\" Enqueue a task on a remote filesystem", "wx.DirDialog(self, \"Select root directory\") if dlg.ShowModal() == wx.ID_OK: root_dir =", "self.set_root() # initialize choices self.propChoices = interface.dataClasses() calc_data_types = self.propChoices.types()", "config if not config.has_section(\"general\"): config.add_section(\"general\") dlg = wx.DirDialog(self, \"Select root", "a task :param user: user of a remote system who", "in sind: self.calcs.pop(si - ds) self.calcList.DeleteItem(si - ds) ds +=", "self.enqueue_local(calc_dir) @staticmethod def enqueue_local(calc_dir): \"\"\" Enqueue a task on a", "event): # property type pt_num = self.propType.GetSelection() pt = self.propType.GetItems()[pt_num]", "(qstat - PBS, sinfo - SLURM) if distutils.spawn.find_executable('qstat') is not", "who enqueues a task :return: error code (0 is OK)", "event): # calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory", "\"\"\" from sshutils import getSSHClient, getQueue, copyFile, removeFile, runCommand ssh", "nsteps is not None: ancdirs[-1] += ' [%i]' % nsteps", "queue system is implemented on cluster (qstat - PBS, sinfo", "event): # current list count clc = self.calcList.GetItemCount() # calculation", "the number of steps in MDE file, quickly nsteps =", "self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0) self.propChoice.SetSelection(0) self.xCorr.SetSelection(0) self.yCorr.SetSelection(0) # initialize calc tree", "= self.propType.GetItems()[self.propType.GetSelection()] pchoice = self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class = self.propChoices.dataClass(ptype, pchoice) leg", "user: user of a remote system who enqueues a task", "item = self.calcTree.GetSelection() parent = self.calcTree.GetItemParent(item) path = [self.calcTree.GetItemText(item)] while", "import mbox class RootFrame(RootGUI): calcs = [] plot_frame = None", "user): \"\"\" Enqueue a task on a remote filesystem :param", "= getQueue(ssh) if q is None: mbox.JobSubmit(None, ()) return None", "('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines()))) removeFile(sftp, remote_file) ssh.close() def plotBtnPress(self, event): if self.noteBook.GetSelection()", "implemented on cluster (qstat - PBS, sinfo - SLURM) if", "return config.get(\"general\", \"root_dir\") # make config if not config.has_section(\"general\"): config.add_section(\"general\")", "if self.noteBook.GetSelection() == 0: self.plot_property() else: self.plot_correlation() def plot_property(self): #", "= self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory cdir = self.get_selection_dir() if not", "interface.dataClasses() calc_data_types = self.propChoices.types() calc_data_classes = self.propChoices.classes(calc_data_types[0]) corr_classes = self.propChoices.classes(\"Histogram\")", "+ calc_dir) mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines()))) removeFile(sftp, remote_file) ssh.close() def plotBtnPress(self,", "current list count clc = self.calcList.GetItemCount() # calculation type ctype", "(0 is OK) \"\"\" import distutils.spawn # find which queue", "config.add_section(\"general\") dlg = wx.DirDialog(self, \"Select root directory\") if dlg.ShowModal() ==", "super(RootFrame, self).__init__(*args, **kwds) # set root self.root = self.set_root() #", "Root directory \"\"\" config_dir = os.path.expanduser(\"~/.local/shs\") config_file = os.path.join(config_dir, \"shs_gui.cfg\")", "'..', q)) putter = q + '.sh' sftp = copyFile(ssh,", "which queue system is implemented on cluster (qstat - PBS,", "@staticmethod def enqueue_remote(calc_dir, host, user): \"\"\" Enqueue a task on", "pchoice) leg = [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] t1 =", "calculation directory on a local filesystem :return: error_code (0 is", "= self.get_selection_dir() if interface.isCalcOfType(ctype, dir=cdir): self.enqueueBtn.Enable() else: self.enqueueBtn.Enable(False) def propTypeChange(self,", "init steps range r = None if ctype in ('.output',", "config.has_section(\"general\"): config.add_section(\"general\") dlg = wx.DirDialog(self, \"Select root directory\") if dlg.ShowModal()", "config_dir = os.path.expanduser(\"~/.local/shs\") config_file = os.path.join(config_dir, \"shs_gui.cfg\") # check the", "= ConfigParser.ConfigParser() config.read(config_file) # if config exists and has needed", "= {root: self.calcTree.AddRoot(root)} for (dir_path, dir_names, file_names) in os.walk(root): if", "pchoice = self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class = self.propChoices.dataClass(ptype, pchoice) leg = [self.calcList.GetItemText(i)", "create one if it's not there if not os.path.isfile(config_file): os.makedirs(config_dir)", "ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root, ctype) def upBtnPress(self, event): # selection", "# plot options - get all the data to plot", "cluster (qstat - PBS, sinfo - SLURM) q = getQueue(ssh)", "and then its children :param root: root directory for the", "'slurm' else: mbox.JobSubmit(None, ()) return -1 comm = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',", "def on_enqueue_press(self, _): from sshutils import getMount, getDevice, getRemoteDir #", "interface import mbox class RootFrame(RootGUI): calcs = [] plot_frame =", "self.calcList.InsertColumn(2, 'NSteps', width=100) def set_root(self): \"\"\" Sets root directory fr", "count clc = self.calcList.GetItemCount() # calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())", "% nsteps ad = root for ancdir in ancdirs: d", "= self.get_selection_dir() mount_path = getMount(calc_dir) device_name, device_type = getDevice(mount_path) if", "\"shs_gui.cfg\") # check the file and create one if it's", "self.calcList.SetStringItem(clc, 1, ctype) self.calcList.SetStringItem(clc, 2, str(len(r)) if r is not", "to plot ptype = self.propType.GetItems()[self.propType.GetSelection()] pchoice = self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class =", ":return: Root directory \"\"\" config_dir = os.path.expanduser(\"~/.local/shs\") config_file = os.path.join(config_dir,", "self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0) def typeChange(self, event): ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root, ctype)", "'w').close() config = ConfigParser.ConfigParser() config.read(config_file) # if config exists and", "import time import subprocess import wx import ConfigParser from wx.lib.mixins.listctrl", "os.walk(root): if interface.isCalcOfType(calc_type, dn=dir_names, fn=file_names): # find the number of", "based on config file :return: Root directory \"\"\" config_dir =", "import wx import ConfigParser from wx.lib.mixins.listctrl import getListCtrlSelection from wx.lib.pubsub", "sinfo - SLURM) q = getQueue(ssh) if q is None:", "= time.clock() plot_data = interface.getData(ptype, data_class, leg, [self.calcs[i] for i", "calculation directory calc_dir = os.sep.join(path[::-1]).split()[0] return calc_dir # return os.sep.join((self.root,", "filesystem :return: error_code (0 is OK) \"\"\" import distutils.spawn #", "else: self.enqueue_local(calc_dir) @staticmethod def enqueue_local(calc_dir): \"\"\" Enqueue a task on", "ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory cdir = self.get_selection_dir() if", "= runCommand(ssh, 'bash ' + remote_file + ' -d=' +", "[self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] t1 = time.clock() plot_data =", "self.get_selection_dir() if interface.isCalcOfType(ctype, dir=cdir): self.enqueueBtn.Enable() else: self.enqueueBtn.Enable(False) def propTypeChange(self, event):", "ad = d def get_selection_dir(self): item = self.calcTree.GetSelection() parent =", "root element and then its children :param root: root directory", ":return: error_code (0 is OK) \"\"\" import distutils.spawn # find", "sind = getListCtrlSelection(self.calcList) if sind: # number of deleted strings", "where to enqueue a task :param user: user of a", "= [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] t1 = time.clock() plot_data", "is not None else '') return 0 def on_enqueue_press(self, _):", "d = os.path.join(ad, ancdir) if not d in ids: ids[d]", "if dlg.ShowModal() == wx.ID_OK: r = dlg.GetRange() dlg.Destroy() self.calcs.append(interface.getCalc(cdir, ctype,", "return root_dir def build_tree(self, root, calc_type): \"\"\" Adds a new", "try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotFuncFrame(self) self.plot_frame.Show() pub.sendMessage('data.plot',", "1 # init steps range r = None if ctype", "= self.propChoices.classes(calc_data_types[0]) corr_classes = self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0)", "is not None: ancdirs[-1] += ' [%i]' % nsteps ad", "' -d=' + calc_dir) mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines()))) removeFile(sftp, remote_file) ssh.close()", "= [leg, data, info] try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame", "file_names) in os.walk(root): if interface.isCalcOfType(calc_type, dn=dir_names, fn=file_names): # find the", "root directory\") if dlg.ShowModal() == wx.ID_OK: root_dir = dlg.GetPath() config.set(\"general\",", "calc_dir = os.sep.join(path[::-1]).split()[0] return calc_dir # return os.sep.join((self.root, calc_dir)) def", "a local filesystem :param calc_dir: calculation directory on a local", "property type pt_num = self.propType.GetSelection() pt = self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0)", "filesystem :param calc_dir: calculation directory on a local filesystem :return:", "self.propChoice.SetSelection(0) def typeChange(self, event): ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root, ctype) def", "= getDevice(mount_path) if 'ssh' in device_type: user, host_dir = device_name.split('@')", "= dir_path.split(os.sep)[r:] if nsteps is not None: ancdirs[-1] += '", "else '') return 0 def on_enqueue_press(self, _): from sshutils import", "si in sind: self.calcs.pop(si - ds) self.calcList.DeleteItem(si - ds) ds", "= d def get_selection_dir(self): item = self.calcTree.GetSelection() parent = self.calcTree.GetItemParent(item)", "task on a local filesystem :param calc_dir: calculation directory on", "def plot_correlation(self): # correlate options - get all the data", "getListCtrlSelection(self.calcList) if sind: # number of deleted strings ds =", "None if ctype in ('.output', '.ANI'): # enter dialog dlg", "[leg, data, info] try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame =", "StepsDialog(None) if dlg.ShowModal() == wx.ID_OK: r = dlg.GetRange() dlg.Destroy() self.calcs.append(interface.getCalc(cdir,", "calc tree self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) # initialize calc list self.calcList.InsertColumn(0, 'Directory',", "Enqueue a task on a remote filesystem :param calc_dir: calculation", "= dlg.GetRange() dlg.Destroy() self.calcs.append(interface.getCalc(cdir, ctype, r)) self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc, 1,", "(time.clock() - t1)) msg = plot_data try: self.plot_frame.Raise() except (AttributeError,", "message=msg) def plot_correlation(self): # correlate options - get all the", "task :param user: user of a remote system who enqueues", "q)) putter = q + '.sh' sftp = copyFile(ssh, putter,", "= os.path.join(ad, ancdir) if not d in ids: ids[d] =", "self.calcTree.GetItemParent(parent) # calculation directory calc_dir = os.sep.join(path[::-1]).split()[0] return calc_dir #", "from PlotFrame import PlotFuncFrame, PlotCorrFrame import interface import mbox class", "task :return: error code (0 is OK) \"\"\" from sshutils", "def build_tree(self, root, calc_type): \"\"\" Adds a new root element", "self.calcList.SetStringItem(clc, 2, str(len(r)) if r is not None else '')", "(dir_path, dir_names, file_names) in os.walk(root): if interface.isCalcOfType(calc_type, dn=dir_names, fn=file_names): #", "= self.calcList.GetItemCount() # calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation", "width=180) self.calcList.InsertColumn(1, 'Type', width=70) self.calcList.InsertColumn(2, 'NSteps', width=100) def set_root(self): \"\"\"", "OK) \"\"\" from sshutils import getSSHClient, getQueue, copyFile, removeFile, runCommand", "PlotFuncFrame(self) self.plot_frame.Show() pub.sendMessage('data.plot', message=msg) def plot_correlation(self): # correlate options -", "machine local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q)) putter = q +", "calculation directory cdir = self.get_selection_dir() if not interface.isCalcOfType(ctype, dir=cdir): mbox.NoResults(cdir,", "system is implemented on cluster (qstat - PBS, sinfo -", "return os.sep.join((self.root, calc_dir)) def onSelChange(self, event): # calculation type ctype", "self.propChoice.SetSelection(0) self.xCorr.SetSelection(0) self.yCorr.SetSelection(0) # initialize calc tree self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) #", "for the tree :param calc_type: calculation type \"\"\" self.calcTree.DeleteAllItems() r", "self.calcList.InsertColumn(0, 'Directory', width=180) self.calcList.InsertColumn(1, 'Type', width=70) self.calcList.InsertColumn(2, 'NSteps', width=100) def", "os.path.join(config_dir, \"shs_gui.cfg\") # check the file and create one if", "None def __init__(self, *args, **kwds): super(RootFrame, self).__init__(*args, **kwds) # set", "self.calcs.pop(si - ds) self.calcList.DeleteItem(si - ds) ds += 1 return", "get all the data to plot xchoice = self.xCorr.GetSelection() ychoice", "removeFile, runCommand ssh = getSSHClient(host, user) # find which queue", "if distutils.spawn.find_executable('qstat') is not None: q = 'pbs' elif distutils.spawn.find_executable('sinfo')", "= len(root.split(os.sep)) ids = {root: self.calcTree.AddRoot(root)} for (dir_path, dir_names, file_names)", "SLURM) q = getQueue(ssh) if q is None: mbox.JobSubmit(None, ())", "remote_file) ssh.close() def plotBtnPress(self, event): if self.noteBook.GetSelection() == 0: self.plot_property()", "ctype) return 1 # init steps range r = None", "= self.calcTree.GetItemParent(item) path = [self.calcTree.GetItemText(item)] while parent.IsOk(): path.append(self.calcTree.GetItemText(parent)) parent =", "self.calcTree.AddRoot(root)} for (dir_path, dir_names, file_names) in os.walk(root): if interface.isCalcOfType(calc_type, dn=dir_names,", "which device are we? calc_dir = self.get_selection_dir() mount_path = getMount(calc_dir)", "calc_type): \"\"\" Adds a new root element and then its", "calc_dir)) def onSelChange(self, event): # calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())", "nsteps ad = root for ancdir in ancdirs: d =", "self.calcTree.GetSelection() parent = self.calcTree.GetItemParent(item) path = [self.calcTree.GetItemText(item)] while parent.IsOk(): path.append(self.calcTree.GetItemText(parent))", "= self.xCorr.GetSelection() ychoice = self.yCorr.GetSelection() leg = [self.calcList.GetItemText(i) for i", "option if config.has_option(\"general\", \"root_dir\"): return config.get(\"general\", \"root_dir\") # make config", "root_dir = dlg.GetPath() config.set(\"general\", \"root_dir\", root_dir) else: sys.exit(1) with open(config_file,", "import getListCtrlSelection from wx.lib.pubsub import pub from gui.RootGUI import RootGUI", "getSSHClient, getQueue, copyFile, removeFile, runCommand ssh = getSSHClient(host, user) #", "t1 = time.clock() plot_data = interface.getData(ptype, data_class, leg, [self.calcs[i] for", "initialize calc tree self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) # initialize calc list self.calcList.InsertColumn(0,", "config.has_option(\"general\", \"root_dir\"): return config.get(\"general\", \"root_dir\") # make config if not", "\"root_dir\"): return config.get(\"general\", \"root_dir\") # make config if not config.has_section(\"general\"):", "config.get(\"general\", \"root_dir\") # make config if not config.has_section(\"general\"): config.add_section(\"general\") dlg", "mbox.NoResults(cdir, ctype) return 1 # init steps range r =", "runCommand ssh = getSSHClient(host, user) # find which queue system", "= interface.dataClasses() calc_data_types = self.propChoices.types() calc_data_classes = self.propChoices.classes(calc_data_types[0]) corr_classes =", "return 0 return 1 def downBtnPress(self, event): # current list", "RootFrame(RootGUI): calcs = [] plot_frame = None def __init__(self, *args,", "plot_frame = None def __init__(self, *args, **kwds): super(RootFrame, self).__init__(*args, **kwds)", "getQueue, copyFile, removeFile, runCommand ssh = getSSHClient(host, user) # find", "dlg.ShowModal() == wx.ID_OK: r = dlg.GetRange() dlg.Destroy() self.calcs.append(interface.getCalc(cdir, ctype, r))", "the tree :param calc_type: calculation type \"\"\" self.calcTree.DeleteAllItems() r =", "if r is not None else '') return 0 def", "fn=file_names): # find the number of steps in MDE file,", "from wx.lib.mixins.listctrl import getListCtrlSelection from wx.lib.pubsub import pub from gui.RootGUI", "(AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotFuncFrame(self) self.plot_frame.Show() pub.sendMessage('data.plot', message=msg) def plot_correlation(self):", "for i in getListCtrlSelection(self.calcList)] t1 = time.clock() plot_data = interface.getData(ptype,", "i in getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation time: %7.2f s.' % (time.clock() -", "q is None: mbox.JobSubmit(None, ()) return None # queue putter", "q = 'pbs' elif distutils.spawn.find_executable('sinfo') is not None: q =", "self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) # initialize calc list self.calcList.InsertColumn(0, 'Directory', width=180) self.calcList.InsertColumn(1,", "MDE file, quickly nsteps = interface.GetNumMDESteps(dir_path) ancdirs = dir_path.split(os.sep)[r:] if", "host_dir.split(':') remote_dir = getRemoteDir(calc_dir, mount_path, remote_mount_path) self.enqueue_remote(remote_dir, hostname, user) else:", "dir=cdir): mbox.NoResults(cdir, ctype) return 1 # init steps range r", "self).__init__(*args, **kwds) # set root self.root = self.set_root() # initialize", "-d=' + calc_dir) mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines()))) removeFile(sftp, remote_file) ssh.close() def", "self.yCorr.GetSelection() leg = [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] data, info", "msg = [leg, data, info] try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError):", "interface.isCalcOfType(ctype, dir=cdir): self.enqueueBtn.Enable() else: self.enqueueBtn.Enable(False) def propTypeChange(self, event): # property", "enqueues a task :return: error code (0 is OK) \"\"\"", "# calculation directory calc_dir = os.sep.join(path[::-1]).split()[0] return calc_dir # return", "calc_dir # return os.sep.join((self.root, calc_dir)) def onSelChange(self, event): # calculation", "r = None if ctype in ('.output', '.ANI'): # enter", "plot_correlation(self): # correlate options - get all the data to", "calculation directory cdir = self.get_selection_dir() if interface.isCalcOfType(ctype, dir=cdir): self.enqueueBtn.Enable() else:", "remote filesystem :param calc_dir: calculation directory on a remote filesystem", "gui.RootGUI import RootGUI from StepsDialog import StepsDialog from PlotFrame import", "root self.root = self.set_root() # initialize choices self.propChoices = interface.dataClasses()", "not config.has_section(\"general\"): config.add_section(\"general\") dlg = wx.DirDialog(self, \"Select root directory\") if", "dlg.ShowModal() == wx.ID_OK: root_dir = dlg.GetPath() config.set(\"general\", \"root_dir\", root_dir) else:", "deleted strings ds = 0 for si in sind: self.calcs.pop(si", "not None: q = 'pbs' elif distutils.spawn.find_executable('sinfo') is not None:", "task on a remote filesystem :param calc_dir: calculation directory on", "file :return: Root directory \"\"\" config_dir = os.path.expanduser(\"~/.local/shs\") config_file =", "' [%i]' % nsteps ad = root for ancdir in", "to enqueue a task :param user: user of a remote", "PlotFuncFrame, PlotCorrFrame import interface import mbox class RootFrame(RootGUI): calcs =", "= getMount(calc_dir) device_name, device_type = getDevice(mount_path) if 'ssh' in device_type:", "+= ' [%i]' % nsteps ad = root for ancdir", "ctype) self.calcList.SetStringItem(clc, 2, str(len(r)) if r is not None else", "wx.ID_OK: r = dlg.GetRange() dlg.Destroy() self.calcs.append(interface.getCalc(cdir, ctype, r)) self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:])", "0 return 1 def downBtnPress(self, event): # current list count", "= interface.GetNumMDESteps(dir_path) ancdirs = dir_path.split(os.sep)[r:] if nsteps is not None:", "+ calc_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) mbox.JobSubmit(q, submit.communicate()) @staticmethod def enqueue_remote(calc_dir, host,", "options - get all the data to plot xchoice =", "for ancdir in ancdirs: d = os.path.join(ad, ancdir) if not", "choices self.propChoices = interface.dataClasses() calc_data_types = self.propChoices.types() calc_data_classes = self.propChoices.classes(calc_data_types[0])", "import os import sys import time import subprocess import wx", "find the number of steps in MDE file, quickly nsteps", "getMount(calc_dir) device_name, device_type = getDevice(mount_path) if 'ssh' in device_type: user,", "GUI based on config file :return: Root directory \"\"\" config_dir", "typeChange(self, event): ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root, ctype) def upBtnPress(self, event):", "**kwds): super(RootFrame, self).__init__(*args, **kwds) # set root self.root = self.set_root()", "the file and create one if it's not there if", "if ctype in ('.output', '.ANI'): # enter dialog dlg =", "ancdir) self.calcTree.SortChildren(ids[ad]) ad = d def get_selection_dir(self): item = self.calcTree.GetSelection()", "from gui.RootGUI import RootGUI from StepsDialog import StepsDialog from PlotFrame", "error code (0 is OK) \"\"\" from sshutils import getSSHClient,", "and has needed option if config.has_option(\"general\", \"root_dir\"): return config.get(\"general\", \"root_dir\")", "import interface import mbox class RootFrame(RootGUI): calcs = [] plot_frame", "calc_dir) remote_file = os.path.join(calc_dir, putter) stdout, stderr = runCommand(ssh, 'bash", "calculation type \"\"\" self.calcTree.DeleteAllItems() r = len(root.split(os.sep)) ids = {root:", "on cluster (qstat - PBS, sinfo - SLURM) q =", "(0 is OK) \"\"\" from sshutils import getSSHClient, getQueue, copyFile,", "ds) self.calcList.DeleteItem(si - ds) ds += 1 return 0 return", "dir_path.split(os.sep)[r:] if nsteps is not None: ancdirs[-1] += ' [%i]'", "pt_num = self.propType.GetSelection() pt = self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0) def typeChange(self,", "f: config.write(f) return root_dir def build_tree(self, root, calc_type): \"\"\" Adds", "-1 comm = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q, q + '.sh')) submit", "os.path.isfile(config_file): os.makedirs(config_dir) open(config_file, 'w').close() config = ConfigParser.ConfigParser() config.read(config_file) # if", "self.calcList.DeleteItem(si - ds) ds += 1 return 0 return 1", "not there if not os.path.isfile(config_file): os.makedirs(config_dir) open(config_file, 'w').close() config =", "msg = plot_data try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame =", "= PlotFuncFrame(self) self.plot_frame.Show() pub.sendMessage('data.plot', message=msg) def plot_correlation(self): # correlate options", "= wx.DirDialog(self, \"Select root directory\") if dlg.ShowModal() == wx.ID_OK: root_dir", "def set_root(self): \"\"\" Sets root directory fr GUI based on", "'\\n'.join(stderr.readlines()))) removeFile(sftp, remote_file) ssh.close() def plotBtnPress(self, event): if self.noteBook.GetSelection() ==", "__init__(self, *args, **kwds): super(RootFrame, self).__init__(*args, **kwds) # set root self.root", "= self.yCorr.GetSelection() leg = [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] data,", "device are we? calc_dir = self.get_selection_dir() mount_path = getMount(calc_dir) device_name,", "dir_names, file_names) in os.walk(root): if interface.isCalcOfType(calc_type, dn=dir_names, fn=file_names): # find", "getListCtrlSelection(self.calcList)]) msg = [leg, data, info] try: self.plot_frame.Raise() except (AttributeError,", "return -1 comm = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q, q + '.sh'))", "config.write(f) return root_dir def build_tree(self, root, calc_type): \"\"\" Adds a", "\"\"\" self.calcTree.DeleteAllItems() r = len(root.split(os.sep)) ids = {root: self.calcTree.AddRoot(root)} for", "'') return 0 def on_enqueue_press(self, _): from sshutils import getMount,", "= [] plot_frame = None def __init__(self, *args, **kwds): super(RootFrame,", "'NSteps', width=100) def set_root(self): \"\"\" Sets root directory fr GUI", "root_dir def build_tree(self, root, calc_type): \"\"\" Adds a new root", "self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory cdir = self.get_selection_dir() if not interface.isCalcOfType(ctype,", "Sets root directory fr GUI based on config file :return:", "if it's not there if not os.path.isfile(config_file): os.makedirs(config_dir) open(config_file, 'w').close()", "()) return -1 comm = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q, q +", "in getListCtrlSelection(self.calcList)] t1 = time.clock() plot_data = interface.getData(ptype, data_class, leg,", "# find which queue system is implemented on cluster (qstat", "'bash ' + remote_file + ' -d=' + calc_dir) mbox.JobSubmit(q,", "- get all the data to plot xchoice = self.xCorr.GetSelection()", "has needed option if config.has_option(\"general\", \"root_dir\"): return config.get(\"general\", \"root_dir\") #", "'.ANI'): # enter dialog dlg = StepsDialog(None) if dlg.ShowModal() ==", "self.propChoices.dataClass(ptype, pchoice) leg = [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] t1", "import getSSHClient, getQueue, copyFile, removeFile, runCommand ssh = getSSHClient(host, user)", "plot ptype = self.propType.GetItems()[self.propType.GetSelection()] pchoice = self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class = self.propChoices.dataClass(ptype,", "self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0) self.propChoice.SetSelection(0) self.xCorr.SetSelection(0) self.yCorr.SetSelection(0) #", "there if not os.path.isfile(config_file): os.makedirs(config_dir) open(config_file, 'w').close() config = ConfigParser.ConfigParser()", "on cluster (qstat - PBS, sinfo - SLURM) if distutils.spawn.find_executable('qstat')", "remote system who enqueues a task :return: error code (0", "= self.propChoice.GetItems()[self.propChoice.GetSelection()] data_class = self.propChoices.dataClass(ptype, pchoice) leg = [self.calcList.GetItemText(i) for", "for si in sind: self.calcs.pop(si - ds) self.calcList.DeleteItem(si - ds)", "downBtnPress(self, event): # current list count clc = self.calcList.GetItemCount() #", "local filesystem :param calc_dir: calculation directory on a local filesystem", "= self.get_selection_dir() if not interface.isCalcOfType(ctype, dir=cdir): mbox.NoResults(cdir, ctype) return 1", "hostname, user) else: self.enqueue_local(calc_dir) @staticmethod def enqueue_local(calc_dir): \"\"\" Enqueue a", "= self.propChoices.types() calc_data_classes = self.propChoices.classes(calc_data_types[0]) corr_classes = self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes)", "= self.calcTree.GetItemParent(parent) # calculation directory calc_dir = os.sep.join(path[::-1]).split()[0] return calc_dir", "'.sh' sftp = copyFile(ssh, putter, local_dir, calc_dir) remote_file = os.path.join(calc_dir,", "# enter dialog dlg = StepsDialog(None) if dlg.ShowModal() == wx.ID_OK:", "self.build_tree(self.root, ctype) def upBtnPress(self, event): # selection indices sind =", "-*- import os import sys import time import subprocess import", "submit.communicate()) @staticmethod def enqueue_remote(calc_dir, host, user): \"\"\" Enqueue a task", "ids = {root: self.calcTree.AddRoot(root)} for (dir_path, dir_names, file_names) in os.walk(root):", "remote_mount_path = host_dir.split(':') remote_dir = getRemoteDir(calc_dir, mount_path, remote_mount_path) self.enqueue_remote(remote_dir, hostname,", "= getListCtrlSelection(self.calcList) if sind: # number of deleted strings ds", "os import sys import time import subprocess import wx import", "\"root_dir\", root_dir) else: sys.exit(1) with open(config_file, 'w') as f: config.write(f)", "% (time.clock() - t1)) msg = plot_data try: self.plot_frame.Raise() except", "not d in ids: ids[d] = self.calcTree.AppendItem(ids[ad], ancdir) self.calcTree.SortChildren(ids[ad]) ad", "device_name, device_type = getDevice(mount_path) if 'ssh' in device_type: user, host_dir", "= None if ctype in ('.output', '.ANI'): # enter dialog", "import RootGUI from StepsDialog import StepsDialog from PlotFrame import PlotFuncFrame,", "find which queue system is implemented on cluster (qstat -", "getListCtrlSelection(self.calcList)] t1 = time.clock() plot_data = interface.getData(ptype, data_class, leg, [self.calcs[i]", "if nsteps is not None: ancdirs[-1] += ' [%i]' %", "if interface.isCalcOfType(calc_type, dn=dir_names, fn=file_names): # find the number of steps", "implemented on cluster (qstat - PBS, sinfo - SLURM) q", "data to plot xchoice = self.xCorr.GetSelection() ychoice = self.yCorr.GetSelection() leg", "info] try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotCorrFrame(self) self.plot_frame.Show()", "ancdirs[-1] += ' [%i]' % nsteps ad = root for", "code (0 is OK) \"\"\" from sshutils import getSSHClient, getQueue,", "'Directory', width=180) self.calcList.InsertColumn(1, 'Type', width=70) self.calcList.InsertColumn(2, 'NSteps', width=100) def set_root(self):", "'.sh')) submit = subprocess.Popen(['/bin/bash', comm, '-d=' + calc_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "root: root directory for the tree :param calc_type: calculation type", "return None # queue putter on a local machine local_dir", "# calculation type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory cdir", "getQueue(ssh) if q is None: mbox.JobSubmit(None, ()) return None #", "width=100) def set_root(self): \"\"\" Sets root directory fr GUI based", "len(root.split(os.sep)) ids = {root: self.calcTree.AddRoot(root)} for (dir_path, dir_names, file_names) in", "range r = None if ctype in ('.output', '.ANI'): #", "self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError): self.plot_frame = PlotFuncFrame(self) self.plot_frame.Show() pub.sendMessage('data.plot', message=msg)", "[] plot_frame = None def __init__(self, *args, **kwds): super(RootFrame, self).__init__(*args,", "str(len(r)) if r is not None else '') return 0", "parent.IsOk(): path.append(self.calcTree.GetItemText(parent)) parent = self.calcTree.GetItemParent(parent) # calculation directory calc_dir =", "directory on a local filesystem :return: error_code (0 is OK)", "# property type pt_num = self.propType.GetSelection() pt = self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt))", "directory cdir = self.get_selection_dir() if interface.isCalcOfType(ctype, dir=cdir): self.enqueueBtn.Enable() else: self.enqueueBtn.Enable(False)", "putter, local_dir, calc_dir) remote_file = os.path.join(calc_dir, putter) stdout, stderr =", "None: ancdirs[-1] += ' [%i]' % nsteps ad = root", "on which device are we? calc_dir = self.get_selection_dir() mount_path =", "directory calc_dir = os.sep.join(path[::-1]).split()[0] return calc_dir # return os.sep.join((self.root, calc_dir))", "- get all the data to plot ptype = self.propType.GetItems()[self.propType.GetSelection()]", "self.xCorr.SetSelection(0) self.yCorr.SetSelection(0) # initialize calc tree self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) # initialize", "== wx.ID_OK: r = dlg.GetRange() dlg.Destroy() self.calcs.append(interface.getCalc(cdir, ctype, r)) self.calcList.InsertStringItem(clc,", "self.get_selection_dir() mount_path = getMount(calc_dir) device_name, device_type = getDevice(mount_path) if 'ssh'", "file and create one if it's not there if not", "None: q = 'pbs' elif distutils.spawn.find_executable('sinfo') is not None: q", "= os.sep.join(path[::-1]).split()[0] return calc_dir # return os.sep.join((self.root, calc_dir)) def onSelChange(self,", "to plot xchoice = self.xCorr.GetSelection() ychoice = self.yCorr.GetSelection() leg =", "elif distutils.spawn.find_executable('sinfo') is not None: q = 'slurm' else: mbox.JobSubmit(None,", "# find the number of steps in MDE file, quickly", "= self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root, ctype) def upBtnPress(self, event): # selection indices", "stdout, stderr = runCommand(ssh, 'bash ' + remote_file + '", "- ds) ds += 1 return 0 return 1 def", "= None def __init__(self, *args, **kwds): super(RootFrame, self).__init__(*args, **kwds) #", "not interface.isCalcOfType(ctype, dir=cdir): mbox.NoResults(cdir, ctype) return 1 # init steps", "from wx.lib.pubsub import pub from gui.RootGUI import RootGUI from StepsDialog", "if not config.has_section(\"general\"): config.add_section(\"general\") dlg = wx.DirDialog(self, \"Select root directory\")", "leg, [self.calcs[i] for i in getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation time: %7.2f s.'", "the data to plot ptype = self.propType.GetItems()[self.propType.GetSelection()] pchoice = self.propChoice.GetItems()[self.propChoice.GetSelection()]", ":param root: root directory for the tree :param calc_type: calculation", "'Type', width=70) self.calcList.InsertColumn(2, 'NSteps', width=100) def set_root(self): \"\"\" Sets root", "return 1 def downBtnPress(self, event): # current list count clc", "runCommand(ssh, 'bash ' + remote_file + ' -d=' + calc_dir)", "- PBS, sinfo - SLURM) q = getQueue(ssh) if q", "q = getQueue(ssh) if q is None: mbox.JobSubmit(None, ()) return", "utf-8 -*- import os import sys import time import subprocess", "if interface.isCalcOfType(ctype, dir=cdir): self.enqueueBtn.Enable() else: self.enqueueBtn.Enable(False) def propTypeChange(self, event): #", "data_class = self.propChoices.dataClass(ptype, pchoice) leg = [self.calcList.GetItemText(i) for i in", "upBtnPress(self, event): # selection indices sind = getListCtrlSelection(self.calcList) if sind:", "dlg = wx.DirDialog(self, \"Select root directory\") if dlg.ShowModal() == wx.ID_OK:", "self.plot_correlation() def plot_property(self): # plot options - get all the", "self.noteBook.GetSelection() == 0: self.plot_property() else: self.plot_correlation() def plot_property(self): # plot", "hostname, remote_mount_path = host_dir.split(':') remote_dir = getRemoteDir(calc_dir, mount_path, remote_mount_path) self.enqueue_remote(remote_dir,", "wx.lib.pubsub import pub from gui.RootGUI import RootGUI from StepsDialog import", "list count clc = self.calcList.GetItemCount() # calculation type ctype =", "submit = subprocess.Popen(['/bin/bash', comm, '-d=' + calc_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) mbox.JobSubmit(q,", "steps range r = None if ctype in ('.output', '.ANI'):", "ssh = getSSHClient(host, user) # find which queue system is", "cdir = self.get_selection_dir() if interface.isCalcOfType(ctype, dir=cdir): self.enqueueBtn.Enable() else: self.enqueueBtn.Enable(False) def", "device_name.split('@') hostname, remote_mount_path = host_dir.split(':') remote_dir = getRemoteDir(calc_dir, mount_path, remote_mount_path)", "we? calc_dir = self.get_selection_dir() mount_path = getMount(calc_dir) device_name, device_type =", "os.path.expanduser(\"~/.local/shs\") config_file = os.path.join(config_dir, \"shs_gui.cfg\") # check the file and", "self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0) self.propChoice.SetSelection(0) self.xCorr.SetSelection(0) self.yCorr.SetSelection(0) # initialize", "def upBtnPress(self, event): # selection indices sind = getListCtrlSelection(self.calcList) if", "ds += 1 return 0 return 1 def downBtnPress(self, event):", "i in getListCtrlSelection(self.calcList)] t1 = time.clock() plot_data = interface.getData(ptype, data_class,", "= self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes) self.propType.SetSelection(0) self.propChoice.SetSelection(0) self.xCorr.SetSelection(0) self.yCorr.SetSelection(0)", "# set root self.root = self.set_root() # initialize choices self.propChoices", "getDevice(mount_path) if 'ssh' in device_type: user, host_dir = device_name.split('@') hostname,", "on a local machine local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q)) putter", "stderr = runCommand(ssh, 'bash ' + remote_file + ' -d='", "# make config if not config.has_section(\"general\"): config.add_section(\"general\") dlg = wx.DirDialog(self,", "Adds a new root element and then its children :param", "device_type = getDevice(mount_path) if 'ssh' in device_type: user, host_dir =", "getListCtrlSelection(self.calcList)]) self.SetStatusText('Calculation time: %7.2f s.' % (time.clock() - t1)) msg", "getListCtrlSelection from wx.lib.pubsub import pub from gui.RootGUI import RootGUI from", "self.propChoices.types() calc_data_classes = self.propChoices.classes(calc_data_types[0]) corr_classes = self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes)", "*args, **kwds): super(RootFrame, self).__init__(*args, **kwds) # set root self.root =", "calc_data_classes = self.propChoices.classes(calc_data_types[0]) corr_classes = self.propChoices.classes(\"Histogram\") self.propType.SetItems(calc_data_types) self.propChoice.SetItems(calc_data_classes) self.xCorr.SetItems(corr_classes) self.yCorr.SetItems(corr_classes)", "_): from sshutils import getMount, getDevice, getRemoteDir # on which", "leg = [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)] data, info =", "then its children :param root: root directory for the tree", "config = ConfigParser.ConfigParser() config.read(config_file) # if config exists and has", "q = 'slurm' else: mbox.JobSubmit(None, ()) return -1 comm =", "return 1 # init steps range r = None if", "host_dir = device_name.split('@') hostname, remote_mount_path = host_dir.split(':') remote_dir = getRemoteDir(calc_dir,", "self.plot_frame = PlotFuncFrame(self) self.plot_frame.Show() pub.sendMessage('data.plot', message=msg) def plot_correlation(self): # correlate", "type ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) # calculation directory cdir = self.get_selection_dir()", "ids[d] = self.calcTree.AppendItem(ids[ad], ancdir) self.calcTree.SortChildren(ids[ad]) ad = d def get_selection_dir(self):", "plot options - get all the data to plot ptype", "= self.set_root() # initialize choices self.propChoices = interface.dataClasses() calc_data_types =", "ancdir in ancdirs: d = os.path.join(ad, ancdir) if not d", "data, info = interface.getCorr(xchoice, ychoice, [self.calcs[i] for i in getListCtrlSelection(self.calcList)])", "event): ctype = self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root, ctype) def upBtnPress(self, event): #", "putter on a local machine local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q))", ":param user: user of a remote system who enqueues a", "if config exists and has needed option if config.has_option(\"general\", \"root_dir\"):", "self.root = self.set_root() # initialize choices self.propChoices = interface.dataClasses() calc_data_types", "= device_name.split('@') hostname, remote_mount_path = host_dir.split(':') remote_dir = getRemoteDir(calc_dir, mount_path,", "\"\"\" Enqueue a task on a local filesystem :param calc_dir:", "file, quickly nsteps = interface.GetNumMDESteps(dir_path) ancdirs = dir_path.split(os.sep)[r:] if nsteps", "- t1)) msg = plot_data try: self.plot_frame.Raise() except (AttributeError, wx.PyDeadObjectError):", "self.propType.GetSelection() pt = self.propType.GetItems()[pt_num] self.propChoice.SetItems(self.propChoices.classes(pt)) self.propChoice.SetSelection(0) def typeChange(self, event): ctype", "- SLURM) q = getQueue(ssh) if q is None: mbox.JobSubmit(None,", "wx import ConfigParser from wx.lib.mixins.listctrl import getListCtrlSelection from wx.lib.pubsub import", "self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) # initialize calc list self.calcList.InsertColumn(0, 'Directory', width=180) self.calcList.InsertColumn(1, 'Type',", "= os.path.join(config_dir, \"shs_gui.cfg\") # check the file and create one", "cluster (qstat - PBS, sinfo - SLURM) if distutils.spawn.find_executable('qstat') is", "in ancdirs: d = os.path.join(ad, ancdir) if not d in", "if not d in ids: ids[d] = self.calcTree.AppendItem(ids[ad], ancdir) self.calcTree.SortChildren(ids[ad])", "time: %7.2f s.' % (time.clock() - t1)) msg = plot_data", "dn=dir_names, fn=file_names): # find the number of steps in MDE", "filesystem :param calc_dir: calculation directory on a remote filesystem :param", "= q + '.sh' sftp = copyFile(ssh, putter, local_dir, calc_dir)", "def get_selection_dir(self): item = self.calcTree.GetSelection() parent = self.calcTree.GetItemParent(item) path =", "self.yCorr.SetSelection(0) # initialize calc tree self.build_tree(self.root, self.typeRBox.GetItemLabel(self.typeRBox.GetSelection())) # initialize calc", "[self.calcTree.GetItemText(item)] while parent.IsOk(): path.append(self.calcTree.GetItemText(parent)) parent = self.calcTree.GetItemParent(parent) # calculation directory", "self.calcTree.DeleteAllItems() r = len(root.split(os.sep)) ids = {root: self.calcTree.AddRoot(root)} for (dir_path,", "for i in getListCtrlSelection(self.calcList)] data, info = interface.getCorr(xchoice, ychoice, [self.calcs[i]", "('.output', '.ANI'): # enter dialog dlg = StepsDialog(None) if dlg.ShowModal()", "= os.path.abspath(os.path.join(os.path.dirname(__file__), '..', q)) putter = q + '.sh' sftp", "(qstat - PBS, sinfo - SLURM) q = getQueue(ssh) if", "pub.sendMessage('data.plot', message=msg) def plot_correlation(self): # correlate options - get all", "1, ctype) self.calcList.SetStringItem(clc, 2, str(len(r)) if r is not None", "import getMount, getDevice, getRemoteDir # on which device are we?", "root directory for the tree :param calc_type: calculation type \"\"\"", "getMount, getDevice, getRemoteDir # on which device are we? calc_dir", "getListCtrlSelection(self.calcList)] data, info = interface.getCorr(xchoice, ychoice, [self.calcs[i] for i in", "check the file and create one if it's not there", "dlg = StepsDialog(None) if dlg.ShowModal() == wx.ID_OK: r = dlg.GetRange()", "self.typeRBox.GetItemLabel(self.typeRBox.GetSelection()) self.build_tree(self.root, ctype) def upBtnPress(self, event): # selection indices sind", "self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc, 1, ctype) self.calcList.SetStringItem(clc, 2, str(len(r)) if r", "directory\") if dlg.ShowModal() == wx.ID_OK: root_dir = dlg.GetPath() config.set(\"general\", \"root_dir\",", "ychoice = self.yCorr.GetSelection() leg = [self.calcList.GetItemText(i) for i in getListCtrlSelection(self.calcList)]", "= 0 for si in sind: self.calcs.pop(si - ds) self.calcList.DeleteItem(si", "plotBtnPress(self, event): if self.noteBook.GetSelection() == 0: self.plot_property() else: self.plot_correlation() def", "needed option if config.has_option(\"general\", \"root_dir\"): return config.get(\"general\", \"root_dir\") # make", "sind: # number of deleted strings ds = 0 for", "# if config exists and has needed option if config.has_option(\"general\",", "set_root(self): \"\"\" Sets root directory fr GUI based on config", "# -*- coding: utf-8 -*- import os import sys import", "if not os.path.isfile(config_file): os.makedirs(config_dir) open(config_file, 'w').close() config = ConfigParser.ConfigParser() config.read(config_file)", "os.sep.join((self.root, calc_dir)) def onSelChange(self, event): # calculation type ctype =", "- PBS, sinfo - SLURM) if distutils.spawn.find_executable('qstat') is not None:", "comm, '-d=' + calc_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) mbox.JobSubmit(q, submit.communicate()) @staticmethod def", "os.path.join(ad, ancdir) if not d in ids: ids[d] = self.calcTree.AppendItem(ids[ad],", "= getSSHClient(host, user) # find which queue system is implemented", "ancdirs: d = os.path.join(ad, ancdir) if not d in ids:", "indices sind = getListCtrlSelection(self.calcList) if sind: # number of deleted", "getDevice, getRemoteDir # on which device are we? calc_dir =", "subprocess import wx import ConfigParser from wx.lib.mixins.listctrl import getListCtrlSelection from", "in ids: ids[d] = self.calcTree.AppendItem(ids[ad], ancdir) self.calcTree.SortChildren(ids[ad]) ad = d", "in getListCtrlSelection(self.calcList)] data, info = interface.getCorr(xchoice, ychoice, [self.calcs[i] for i", "r = dlg.GetRange() dlg.Destroy() self.calcs.append(interface.getCalc(cdir, ctype, r)) self.calcList.InsertStringItem(clc, cdir[len(self.root)+1:]) self.calcList.SetStringItem(clc,", "selection indices sind = getListCtrlSelection(self.calcList) if sind: # number of", "calc_dir) mbox.JobSubmit(q, ('\\n'.join(stdout.readlines()), '\\n'.join(stderr.readlines()))) removeFile(sftp, remote_file) ssh.close() def plotBtnPress(self, event):", "wx.ID_OK: root_dir = dlg.GetPath() config.set(\"general\", \"root_dir\", root_dir) else: sys.exit(1) with" ]
[ "name='ordereditem', options={'verbose_name': 'Ordered item', 'verbose_name_plural': 'Ordered items'}, ), migrations.AlterModelOptions( name='orderhistoryentry',", "null=True, verbose_name='shipping method name'), ), migrations.AlterField( model_name='deliverygroup', name='tracking_number', field=models.CharField(blank=True, default='',", "method name'), ), migrations.AlterField( model_name='deliverygroup', name='tracking_number', field=models.CharField(blank=True, default='', max_length=255, verbose_name='tracking", "address'), ), migrations.AlterField( model_name='order', name='total_net', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True,", "verbose_name='delivery group'), ), migrations.AlterField( model_name='ordereditem', name='stock', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='product.Stock', verbose_name='stock'),", "name='stock', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='product.Stock', verbose_name='stock'), ), migrations.AlterField( model_name='orderhistoryentry', name='comment', field=models.CharField(blank=True,", "'Ordered items'}, ), migrations.AlterModelOptions( name='orderhistoryentry', options={'ordering': ('date',), 'verbose_name': 'Order history", "max_length=255, verbose_name='tracking number'), ), migrations.AlterField( model_name='order', name='billing_address', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='+',", "editable=False, max_length=254, verbose_name='user email'), ), migrations.AlterField( model_name='order', name='voucher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL,", "migrations.AlterField( model_name='orderhistoryentry', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='order.Order', verbose_name='order'), ), migrations.AlterField( model_name='orderhistoryentry',", "name='payment', options={'ordering': ('-pk',), 'verbose_name': 'Payment', 'verbose_name_plural': 'Payments'}, ), migrations.AlterField( model_name='deliverygroup',", "id'), ), migrations.AlterField( model_name='order', name='user_email', field=models.EmailField(blank=True, default='', editable=False, max_length=254, verbose_name='user", "number'), ), migrations.AlterField( model_name='order', name='billing_address', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='billing", "to='discount.Voucher', verbose_name='voucher'), ), migrations.AlterField( model_name='ordereditem', name='delivery_group', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='order.DeliveryGroup',", "migrations.AlterField( model_name='order', name='shipping_address', field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='shipping address'),", "'Orders'}, ), migrations.AlterModelOptions( name='ordereditem', options={'verbose_name': 'Ordered item', 'verbose_name_plural': 'Ordered items'},", "to='order.Order', verbose_name='order'), ), migrations.AlterField( model_name='orderhistoryentry', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL,", "model_name='order', name='voucher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='discount.Voucher', verbose_name='voucher'), ), migrations.AlterField( model_name='ordereditem',", "model_name='orderhistoryentry', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'), ), migrations.AlterField( model_name='payment',", "-*- # Generated by Django 1.10.5 on 2017-02-06 10:07 from", "Django 1.10.5 on 2017-02-06 10:07 from __future__ import unicode_literals from", "= [ ('order', '0014_auto_20161028_0955'), ] operations = [ migrations.AlterModelOptions( name='deliverygroup',", "), migrations.AlterField( model_name='orderhistoryentry', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='order.Order', verbose_name='order'), ), migrations.AlterField(", "migrations.AlterField( model_name='ordereditem', name='stock', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='product.Stock', verbose_name='stock'), ), migrations.AlterField( model_name='orderhistoryentry',", "import django.db.models.deletion import django_prices.models class Migration(migrations.Migration): dependencies = [ ('order',", "field=models.CharField(blank=True, default='', max_length=255, verbose_name='discount name'), ), migrations.AlterField( model_name='order', name='shipping_address', field=models.ForeignKey(editable=False,", "model_name='ordereditem', name='delivery_group', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='order.DeliveryGroup', verbose_name='delivery group'), ), migrations.AlterField(", "name='delivery_group', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='order.DeliveryGroup', verbose_name='delivery group'), ), migrations.AlterField( model_name='ordereditem',", "null=True, verbose_name='discount amount'), ), migrations.AlterField( model_name='order', name='discount_name', field=models.CharField(blank=True, default='', max_length=255,", "max_length=255, null=True, verbose_name='shipping method name'), ), migrations.AlterField( model_name='deliverygroup', name='tracking_number', field=models.CharField(blank=True,", "), migrations.AlterField( model_name='order', name='discount_amount', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='discount", "related_name='+', to='discount.Voucher', verbose_name='voucher'), ), migrations.AlterField( model_name='ordereditem', name='delivery_group', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='items',", "field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total net'), ), migrations.AlterField( model_name='order',", "), migrations.AlterField( model_name='ordereditem', name='stock', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='product.Stock', verbose_name='stock'), ), migrations.AlterField(", "'Delivery Group', 'verbose_name_plural': 'Delivery Groups'}, ), migrations.AlterModelOptions( name='order', options={'ordering': ('-last_status_change',),", "group'), ), migrations.AlterField( model_name='ordereditem', name='stock', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='product.Stock', verbose_name='stock'), ),", "10:07 from __future__ import unicode_literals from django.conf import settings from", "Generated by Django 1.10.5 on 2017-02-06 10:07 from __future__ import", "__future__ import unicode_literals from django.conf import settings from django.db import", "model_name='order', name='user_email', field=models.EmailField(blank=True, default='', editable=False, max_length=254, verbose_name='user email'), ), migrations.AlterField(", "'verbose_name': 'Order history entry', 'verbose_name_plural': 'Order history entries'}, ), migrations.AlterModelOptions(", "migrations.AlterField( model_name='orderhistoryentry', name='comment', field=models.CharField(blank=True, default='', max_length=100, verbose_name='comment'), ), migrations.AlterField( model_name='orderhistoryentry',", "name='tracking_number', field=models.CharField(blank=True, default='', max_length=255, verbose_name='tracking number'), ), migrations.AlterField( model_name='order', name='billing_address',", "on_delete=django.db.models.deletion.CASCADE, related_name='items', to='order.DeliveryGroup', verbose_name='delivery group'), ), migrations.AlterField( model_name='ordereditem', name='stock', field=models.ForeignKey(null=True,", "1.10.5 on 2017-02-06 10:07 from __future__ import unicode_literals from django.conf", "class Migration(migrations.Migration): dependencies = [ ('order', '0014_auto_20161028_0955'), ] operations =", "'verbose_name_plural': 'Payments'}, ), migrations.AlterField( model_name='deliverygroup', name='last_updated', field=models.DateTimeField(auto_now=True, null=True, verbose_name='last updated'),", "on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='billing address'), ), migrations.AlterField( model_name='order', name='discount_amount', field=django_prices.models.MoneyField(blank=True,", "), migrations.AlterField( model_name='order', name='total_tax', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total", "default='', max_length=100, verbose_name='comment'), ), migrations.AlterField( model_name='orderhistoryentry', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='order.Order',", "entries'}, ), migrations.AlterModelOptions( name='ordernote', options={'verbose_name': 'Order note', 'verbose_name_plural': 'Order notes'},", "'Payments'}, ), migrations.AlterField( model_name='deliverygroup', name='last_updated', field=models.DateTimeField(auto_now=True, null=True, verbose_name='last updated'), ),", "items'}, ), migrations.AlterModelOptions( name='orderhistoryentry', options={'ordering': ('date',), 'verbose_name': 'Order history entry',", "to='account.Address', verbose_name='shipping address'), ), migrations.AlterField( model_name='order', name='total_net', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2,", "max_digits=12, null=True, verbose_name='total tax'), ), migrations.AlterField( model_name='order', name='tracking_client_id', field=models.CharField(blank=True, editable=False,", "verbose_name='user'), ), migrations.AlterField( model_name='payment', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments', to='order.Order', verbose_name='order'), ),", "null=True, verbose_name='total tax'), ), migrations.AlterField( model_name='order', name='tracking_client_id', field=models.CharField(blank=True, editable=False, max_length=36,", "verbose_name='order'), ), migrations.AlterField( model_name='orderhistoryentry', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'),", "verbose_name='tracking number'), ), migrations.AlterField( model_name='order', name='billing_address', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address',", "decimal_places=2, max_digits=12, null=True, verbose_name='discount amount'), ), migrations.AlterField( model_name='order', name='discount_name', field=models.CharField(blank=True,", "), migrations.AlterField( model_name='deliverygroup', name='last_updated', field=models.DateTimeField(auto_now=True, null=True, verbose_name='last updated'), ), migrations.AlterField(", "email'), ), migrations.AlterField( model_name='order', name='voucher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='discount.Voucher', verbose_name='voucher'),", "[ ('order', '0014_auto_20161028_0955'), ] operations = [ migrations.AlterModelOptions( name='deliverygroup', options={'verbose_name':", "migrations.AlterField( model_name='order', name='discount_amount', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='discount amount'),", "name'), ), migrations.AlterField( model_name='deliverygroup', name='tracking_number', field=models.CharField(blank=True, default='', max_length=255, verbose_name='tracking number'),", "entry', 'verbose_name_plural': 'Order history entries'}, ), migrations.AlterModelOptions( name='ordernote', options={'verbose_name': 'Order", "'verbose_name_plural': 'Order notes'}, ), migrations.AlterModelOptions( name='payment', options={'ordering': ('-pk',), 'verbose_name': 'Payment',", "'Order notes'}, ), migrations.AlterModelOptions( name='payment', options={'ordering': ('-pk',), 'verbose_name': 'Payment', 'verbose_name_plural':", "field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='discount amount'), ), migrations.AlterField( model_name='order',", "2017-02-06 10:07 from __future__ import unicode_literals from django.conf import settings", "model_name='order', name='total_net', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total net'), ),", "migrations.AlterField( model_name='order', name='tracking_client_id', field=models.CharField(blank=True, editable=False, max_length=36, verbose_name='tracking client id'), ),", "('order', '0014_auto_20161028_0955'), ] operations = [ migrations.AlterModelOptions( name='deliverygroup', options={'verbose_name': 'Delivery", "field=models.CharField(blank=True, default=None, editable=False, max_length=255, null=True, verbose_name='shipping method name'), ), migrations.AlterField(", "'verbose_name_plural': 'Orders'}, ), migrations.AlterModelOptions( name='ordereditem', options={'verbose_name': 'Ordered item', 'verbose_name_plural': 'Ordered", "name='total_net', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total net'), ), migrations.AlterField(", "verbose_name='tracking client id'), ), migrations.AlterField( model_name='order', name='user_email', field=models.EmailField(blank=True, default='', editable=False,", "options={'verbose_name': 'Ordered item', 'verbose_name_plural': 'Ordered items'}, ), migrations.AlterModelOptions( name='orderhistoryentry', options={'ordering':", "null=True, verbose_name='last updated'), ), migrations.AlterField( model_name='deliverygroup', name='shipping_method_name', field=models.CharField(blank=True, default=None, editable=False,", "), migrations.AlterField( model_name='orderhistoryentry', name='comment', field=models.CharField(blank=True, default='', max_length=100, verbose_name='comment'), ), migrations.AlterField(", "), migrations.AlterModelOptions( name='ordernote', options={'verbose_name': 'Order note', 'verbose_name_plural': 'Order notes'}, ),", "verbose_name='total tax'), ), migrations.AlterField( model_name='order', name='tracking_client_id', field=models.CharField(blank=True, editable=False, max_length=36, verbose_name='tracking", "models import django.db.models.deletion import django_prices.models class Migration(migrations.Migration): dependencies = [", "'Payment', 'verbose_name_plural': 'Payments'}, ), migrations.AlterField( model_name='deliverygroup', name='last_updated', field=models.DateTimeField(auto_now=True, null=True, verbose_name='last", "), migrations.AlterField( model_name='deliverygroup', name='tracking_number', field=models.CharField(blank=True, default='', max_length=255, verbose_name='tracking number'), ),", "field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='discount.Voucher', verbose_name='voucher'), ), migrations.AlterField( model_name='ordereditem', name='delivery_group', field=models.ForeignKey(editable=False,", "model_name='ordereditem', name='stock', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='product.Stock', verbose_name='stock'), ), migrations.AlterField( model_name='orderhistoryentry', name='comment',", "to=settings.AUTH_USER_MODEL, verbose_name='user'), ), migrations.AlterField( model_name='payment', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments', to='order.Order', verbose_name='order'),", "field=models.DateTimeField(auto_now=True, null=True, verbose_name='last updated'), ), migrations.AlterField( model_name='deliverygroup', name='shipping_method_name', field=models.CharField(blank=True, default=None,", "on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'), ), migrations.AlterField( model_name='payment', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments', to='order.Order',", "name='deliverygroup', options={'verbose_name': 'Delivery Group', 'verbose_name_plural': 'Delivery Groups'}, ), migrations.AlterModelOptions( name='order',", "history entry', 'verbose_name_plural': 'Order history entries'}, ), migrations.AlterModelOptions( name='ordernote', options={'verbose_name':", "migrations.AlterModelOptions( name='orderhistoryentry', options={'ordering': ('date',), 'verbose_name': 'Order history entry', 'verbose_name_plural': 'Order", "'0014_auto_20161028_0955'), ] operations = [ migrations.AlterModelOptions( name='deliverygroup', options={'verbose_name': 'Delivery Group',", "), migrations.AlterField( model_name='deliverygroup', name='shipping_method_name', field=models.CharField(blank=True, default=None, editable=False, max_length=255, null=True, verbose_name='shipping", "[ migrations.AlterModelOptions( name='deliverygroup', options={'verbose_name': 'Delivery Group', 'verbose_name_plural': 'Delivery Groups'}, ),", "verbose_name='stock'), ), migrations.AlterField( model_name='orderhistoryentry', name='comment', field=models.CharField(blank=True, default='', max_length=100, verbose_name='comment'), ),", "django.db import migrations, models import django.db.models.deletion import django_prices.models class Migration(migrations.Migration):", "), migrations.AlterField( model_name='order', name='billing_address', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='billing address'),", "= [ migrations.AlterModelOptions( name='deliverygroup', options={'verbose_name': 'Delivery Group', 'verbose_name_plural': 'Delivery Groups'},", "verbose_name='shipping address'), ), migrations.AlterField( model_name='order', name='total_net', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12,", "'Order history entries'}, ), migrations.AlterModelOptions( name='ordernote', options={'verbose_name': 'Order note', 'verbose_name_plural':", "migrations.AlterField( model_name='order', name='total_net', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total net'),", "migrations.AlterField( model_name='orderhistoryentry', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'), ), migrations.AlterField(", "from __future__ import unicode_literals from django.conf import settings from django.db", "history entries'}, ), migrations.AlterModelOptions( name='ordernote', options={'verbose_name': 'Order note', 'verbose_name_plural': 'Order", "max_digits=12, null=True, verbose_name='discount amount'), ), migrations.AlterField( model_name='order', name='discount_name', field=models.CharField(blank=True, default='',", "'verbose_name_plural': 'Delivery Groups'}, ), migrations.AlterModelOptions( name='order', options={'ordering': ('-last_status_change',), 'verbose_name': 'Order',", "amount'), ), migrations.AlterField( model_name='order', name='discount_name', field=models.CharField(blank=True, default='', max_length=255, verbose_name='discount name'),", "model_name='order', name='tracking_client_id', field=models.CharField(blank=True, editable=False, max_length=36, verbose_name='tracking client id'), ), migrations.AlterField(", "Group', 'verbose_name_plural': 'Delivery Groups'}, ), migrations.AlterModelOptions( name='order', options={'ordering': ('-last_status_change',), 'verbose_name':", "field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'), ), migrations.AlterField( model_name='payment', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "item', 'verbose_name_plural': 'Ordered items'}, ), migrations.AlterModelOptions( name='orderhistoryentry', options={'ordering': ('date',), 'verbose_name':", "options={'ordering': ('-pk',), 'verbose_name': 'Payment', 'verbose_name_plural': 'Payments'}, ), migrations.AlterField( model_name='deliverygroup', name='last_updated',", "('-pk',), 'verbose_name': 'Payment', 'verbose_name_plural': 'Payments'}, ), migrations.AlterField( model_name='deliverygroup', name='last_updated', field=models.DateTimeField(auto_now=True,", "model_name='order', name='billing_address', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='billing address'), ), migrations.AlterField(", "model_name='deliverygroup', name='shipping_method_name', field=models.CharField(blank=True, default=None, editable=False, max_length=255, null=True, verbose_name='shipping method name'),", "name='discount_name', field=models.CharField(blank=True, default='', max_length=255, verbose_name='discount name'), ), migrations.AlterField( model_name='order', name='shipping_address',", "note', 'verbose_name_plural': 'Order notes'}, ), migrations.AlterModelOptions( name='payment', options={'ordering': ('-pk',), 'verbose_name':", "Groups'}, ), migrations.AlterModelOptions( name='order', options={'ordering': ('-last_status_change',), 'verbose_name': 'Order', 'verbose_name_plural': 'Orders'},", "verbose_name='billing address'), ), migrations.AlterField( model_name='order', name='discount_amount', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12,", "verbose_name='total net'), ), migrations.AlterField( model_name='order', name='total_tax', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12,", "), migrations.AlterField( model_name='orderhistoryentry', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'), ),", "default='', max_length=255, verbose_name='tracking number'), ), migrations.AlterField( model_name='order', name='billing_address', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE,", "'Order history entry', 'verbose_name_plural': 'Order history entries'}, ), migrations.AlterModelOptions( name='ordernote',", "operations = [ migrations.AlterModelOptions( name='deliverygroup', options={'verbose_name': 'Delivery Group', 'verbose_name_plural': 'Delivery", "options={'verbose_name': 'Delivery Group', 'verbose_name_plural': 'Delivery Groups'}, ), migrations.AlterModelOptions( name='order', options={'ordering':", "verbose_name='last updated'), ), migrations.AlterField( model_name='deliverygroup', name='shipping_method_name', field=models.CharField(blank=True, default=None, editable=False, max_length=255,", "'Ordered item', 'verbose_name_plural': 'Ordered items'}, ), migrations.AlterModelOptions( name='orderhistoryentry', options={'ordering': ('date',),", "field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='order.DeliveryGroup', verbose_name='delivery group'), ), migrations.AlterField( model_name='ordereditem', name='stock',", "on_delete=django.db.models.deletion.SET_NULL, to='product.Stock', verbose_name='stock'), ), migrations.AlterField( model_name='orderhistoryentry', name='comment', field=models.CharField(blank=True, default='', max_length=100,", "field=models.CharField(blank=True, default='', max_length=100, verbose_name='comment'), ), migrations.AlterField( model_name='orderhistoryentry', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history',", "migrations.AlterModelOptions( name='payment', options={'ordering': ('-pk',), 'verbose_name': 'Payment', 'verbose_name_plural': 'Payments'}, ), migrations.AlterField(", "field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='product.Stock', verbose_name='stock'), ), migrations.AlterField( model_name='orderhistoryentry', name='comment', field=models.CharField(blank=True, default='',", "default='', editable=False, max_length=254, verbose_name='user email'), ), migrations.AlterField( model_name='order', name='voucher', field=models.ForeignKey(null=True,", "import migrations, models import django.db.models.deletion import django_prices.models class Migration(migrations.Migration): dependencies", "), migrations.AlterModelOptions( name='payment', options={'ordering': ('-pk',), 'verbose_name': 'Payment', 'verbose_name_plural': 'Payments'}, ),", "model_name='orderhistoryentry', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='order.Order', verbose_name='order'), ), migrations.AlterField( model_name='orderhistoryentry', name='user',", "django.db.models.deletion import django_prices.models class Migration(migrations.Migration): dependencies = [ ('order', '0014_auto_20161028_0955'),", "'verbose_name': 'Order', 'verbose_name_plural': 'Orders'}, ), migrations.AlterModelOptions( name='ordereditem', options={'verbose_name': 'Ordered item',", "), migrations.AlterField( model_name='order', name='tracking_client_id', field=models.CharField(blank=True, editable=False, max_length=36, verbose_name='tracking client id'),", "'verbose_name_plural': 'Order history entries'}, ), migrations.AlterModelOptions( name='ordernote', options={'verbose_name': 'Order note',", "name='order', options={'ordering': ('-last_status_change',), 'verbose_name': 'Order', 'verbose_name_plural': 'Orders'}, ), migrations.AlterModelOptions( name='ordereditem',", "'Order note', 'verbose_name_plural': 'Order notes'}, ), migrations.AlterModelOptions( name='payment', options={'ordering': ('-pk',),", "currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total tax'), ), migrations.AlterField( model_name='order', name='tracking_client_id',", "decimal_places=2, max_digits=12, null=True, verbose_name='total tax'), ), migrations.AlterField( model_name='order', name='tracking_client_id', field=models.CharField(blank=True,", "name='voucher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='discount.Voucher', verbose_name='voucher'), ), migrations.AlterField( model_name='ordereditem', name='delivery_group',", "on 2017-02-06 10:07 from __future__ import unicode_literals from django.conf import", "migrations.AlterModelOptions( name='order', options={'ordering': ('-last_status_change',), 'verbose_name': 'Order', 'verbose_name_plural': 'Orders'}, ), migrations.AlterModelOptions(", "verbose_name='comment'), ), migrations.AlterField( model_name='orderhistoryentry', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='order.Order', verbose_name='order'), ),", "to='product.Stock', verbose_name='stock'), ), migrations.AlterField( model_name='orderhistoryentry', name='comment', field=models.CharField(blank=True, default='', max_length=100, verbose_name='comment'),", "field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='order.Order', verbose_name='order'), ), migrations.AlterField( model_name='orderhistoryentry', name='user', field=models.ForeignKey(blank=True, null=True,", "currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='discount amount'), ), migrations.AlterField( model_name='order', name='discount_name',", "max_length=254, verbose_name='user email'), ), migrations.AlterField( model_name='order', name='voucher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+',", "field=models.CharField(blank=True, default='', max_length=255, verbose_name='tracking number'), ), migrations.AlterField( model_name='order', name='billing_address', field=models.ForeignKey(editable=False,", "import settings from django.db import migrations, models import django.db.models.deletion import", "), migrations.AlterModelOptions( name='orderhistoryentry', options={'ordering': ('date',), 'verbose_name': 'Order history entry', 'verbose_name_plural':", "'verbose_name': 'Payment', 'verbose_name_plural': 'Payments'}, ), migrations.AlterField( model_name='deliverygroup', name='last_updated', field=models.DateTimeField(auto_now=True, null=True,", "migrations.AlterField( model_name='order', name='total_tax', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total tax'),", "utf-8 -*- # Generated by Django 1.10.5 on 2017-02-06 10:07", "currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total net'), ), migrations.AlterField( model_name='order', name='total_tax',", "), migrations.AlterField( model_name='order', name='discount_name', field=models.CharField(blank=True, default='', max_length=255, verbose_name='discount name'), ),", "Migration(migrations.Migration): dependencies = [ ('order', '0014_auto_20161028_0955'), ] operations = [", "('date',), 'verbose_name': 'Order history entry', 'verbose_name_plural': 'Order history entries'}, ),", "name='ordernote', options={'verbose_name': 'Order note', 'verbose_name_plural': 'Order notes'}, ), migrations.AlterModelOptions( name='payment',", "migrations.AlterField( model_name='deliverygroup', name='last_updated', field=models.DateTimeField(auto_now=True, null=True, verbose_name='last updated'), ), migrations.AlterField( model_name='deliverygroup',", "verbose_name='discount name'), ), migrations.AlterField( model_name='order', name='shipping_address', field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+',", "max_length=255, verbose_name='discount name'), ), migrations.AlterField( model_name='order', name='shipping_address', field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE,", "'Delivery Groups'}, ), migrations.AlterModelOptions( name='order', options={'ordering': ('-last_status_change',), 'verbose_name': 'Order', 'verbose_name_plural':", "tax'), ), migrations.AlterField( model_name='order', name='tracking_client_id', field=models.CharField(blank=True, editable=False, max_length=36, verbose_name='tracking client", "editable=False, max_length=255, null=True, verbose_name='shipping method name'), ), migrations.AlterField( model_name='deliverygroup', name='tracking_number',", "verbose_name='discount amount'), ), migrations.AlterField( model_name='order', name='discount_name', field=models.CharField(blank=True, default='', max_length=255, verbose_name='discount", "name='tracking_client_id', field=models.CharField(blank=True, editable=False, max_length=36, verbose_name='tracking client id'), ), migrations.AlterField( model_name='order',", "name='shipping_method_name', field=models.CharField(blank=True, default=None, editable=False, max_length=255, null=True, verbose_name='shipping method name'), ),", "max_length=100, verbose_name='comment'), ), migrations.AlterField( model_name='orderhistoryentry', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='order.Order', verbose_name='order'),", "max_length=36, verbose_name='tracking client id'), ), migrations.AlterField( model_name='order', name='user_email', field=models.EmailField(blank=True, default='',", "default=None, editable=False, max_length=255, null=True, verbose_name='shipping method name'), ), migrations.AlterField( model_name='deliverygroup',", "related_name='history', to='order.Order', verbose_name='order'), ), migrations.AlterField( model_name='orderhistoryentry', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,", "field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total tax'), ), migrations.AlterField( model_name='order',", "), migrations.AlterField( model_name='order', name='total_net', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total", "coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-06", "migrations.AlterField( model_name='order', name='user_email', field=models.EmailField(blank=True, default='', editable=False, max_length=254, verbose_name='user email'), ),", "options={'verbose_name': 'Order note', 'verbose_name_plural': 'Order notes'}, ), migrations.AlterModelOptions( name='payment', options={'ordering':", "null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='shipping address'), ), migrations.AlterField( model_name='order', name='total_net',", "name='orderhistoryentry', options={'ordering': ('date',), 'verbose_name': 'Order history entry', 'verbose_name_plural': 'Order history", "model_name='order', name='discount_name', field=models.CharField(blank=True, default='', max_length=255, verbose_name='discount name'), ), migrations.AlterField( model_name='order',", "name='shipping_address', field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='shipping address'), ), migrations.AlterField(", "name'), ), migrations.AlterField( model_name='order', name='shipping_address', field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address',", "model_name='deliverygroup', name='tracking_number', field=models.CharField(blank=True, default='', max_length=255, verbose_name='tracking number'), ), migrations.AlterField( model_name='order',", "related_name='+', to='account.Address', verbose_name='billing address'), ), migrations.AlterField( model_name='order', name='discount_amount', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY,", "address'), ), migrations.AlterField( model_name='order', name='discount_amount', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True,", "on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='shipping address'), ), migrations.AlterField( model_name='order', name='total_net', field=django_prices.models.MoneyField(blank=True,", "name='user_email', field=models.EmailField(blank=True, default='', editable=False, max_length=254, verbose_name='user email'), ), migrations.AlterField( model_name='order',", "field=models.CharField(blank=True, editable=False, max_length=36, verbose_name='tracking client id'), ), migrations.AlterField( model_name='order', name='user_email',", "), migrations.AlterField( model_name='ordereditem', name='delivery_group', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='order.DeliveryGroup', verbose_name='delivery group'),", "name='comment', field=models.CharField(blank=True, default='', max_length=100, verbose_name='comment'), ), migrations.AlterField( model_name='orderhistoryentry', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='history', to='order.Order', verbose_name='order'), ), migrations.AlterField( model_name='orderhistoryentry', name='user', field=models.ForeignKey(blank=True,", "), migrations.AlterField( model_name='payment', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments', to='order.Order', verbose_name='order'), ), ]", "migrations.AlterModelOptions( name='deliverygroup', options={'verbose_name': 'Delivery Group', 'verbose_name_plural': 'Delivery Groups'}, ), migrations.AlterModelOptions(", "name='total_tax', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total tax'), ), migrations.AlterField(", "net'), ), migrations.AlterField( model_name='order', name='total_tax', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True,", "), migrations.AlterModelOptions( name='ordereditem', options={'verbose_name': 'Ordered item', 'verbose_name_plural': 'Ordered items'}, ),", "to='order.DeliveryGroup', verbose_name='delivery group'), ), migrations.AlterField( model_name='ordereditem', name='stock', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='product.Stock',", "migrations.AlterField( model_name='order', name='voucher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='discount.Voucher', verbose_name='voucher'), ), migrations.AlterField(", "related_name='items', to='order.DeliveryGroup', verbose_name='delivery group'), ), migrations.AlterField( model_name='ordereditem', name='stock', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL,", "field=models.EmailField(blank=True, default='', editable=False, max_length=254, verbose_name='user email'), ), migrations.AlterField( model_name='order', name='voucher',", "model_name='order', name='discount_amount', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='discount amount'), ),", "notes'}, ), migrations.AlterModelOptions( name='payment', options={'ordering': ('-pk',), 'verbose_name': 'Payment', 'verbose_name_plural': 'Payments'},", "] operations = [ migrations.AlterModelOptions( name='deliverygroup', options={'verbose_name': 'Delivery Group', 'verbose_name_plural':", "options={'ordering': ('date',), 'verbose_name': 'Order history entry', 'verbose_name_plural': 'Order history entries'},", "django_prices.models class Migration(migrations.Migration): dependencies = [ ('order', '0014_auto_20161028_0955'), ] operations", "verbose_name='voucher'), ), migrations.AlterField( model_name='ordereditem', name='delivery_group', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='order.DeliveryGroup', verbose_name='delivery", "updated'), ), migrations.AlterField( model_name='deliverygroup', name='shipping_method_name', field=models.CharField(blank=True, default=None, editable=False, max_length=255, null=True,", "), migrations.AlterField( model_name='order', name='user_email', field=models.EmailField(blank=True, default='', editable=False, max_length=254, verbose_name='user email'),", "options={'ordering': ('-last_status_change',), 'verbose_name': 'Order', 'verbose_name_plural': 'Orders'}, ), migrations.AlterModelOptions( name='ordereditem', options={'verbose_name':", "model_name='orderhistoryentry', name='comment', field=models.CharField(blank=True, default='', max_length=100, verbose_name='comment'), ), migrations.AlterField( model_name='orderhistoryentry', name='order',", "verbose_name='user email'), ), migrations.AlterField( model_name='order', name='voucher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='discount.Voucher',", "-*- coding: utf-8 -*- # Generated by Django 1.10.5 on", "'verbose_name_plural': 'Ordered items'}, ), migrations.AlterModelOptions( name='orderhistoryentry', options={'ordering': ('date',), 'verbose_name': 'Order", "from django.db import migrations, models import django.db.models.deletion import django_prices.models class", "field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='shipping address'), ), migrations.AlterField( model_name='order',", "client id'), ), migrations.AlterField( model_name='order', name='user_email', field=models.EmailField(blank=True, default='', editable=False, max_length=254,", "by Django 1.10.5 on 2017-02-06 10:07 from __future__ import unicode_literals", "name='billing_address', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='billing address'), ), migrations.AlterField( model_name='order',", "), migrations.AlterField( model_name='order', name='shipping_address', field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='shipping", "migrations.AlterModelOptions( name='ordernote', options={'verbose_name': 'Order note', 'verbose_name_plural': 'Order notes'}, ), migrations.AlterModelOptions(", "settings from django.db import migrations, models import django.db.models.deletion import django_prices.models", "dependencies = [ ('order', '0014_auto_20161028_0955'), ] operations = [ migrations.AlterModelOptions(", "), migrations.AlterModelOptions( name='order', options={'ordering': ('-last_status_change',), 'verbose_name': 'Order', 'verbose_name_plural': 'Orders'}, ),", "'Order', 'verbose_name_plural': 'Orders'}, ), migrations.AlterModelOptions( name='ordereditem', options={'verbose_name': 'Ordered item', 'verbose_name_plural':", "default='', max_length=255, verbose_name='discount name'), ), migrations.AlterField( model_name='order', name='shipping_address', field=models.ForeignKey(editable=False, null=True,", "verbose_name='shipping method name'), ), migrations.AlterField( model_name='deliverygroup', name='tracking_number', field=models.CharField(blank=True, default='', max_length=255,", "name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'), ), migrations.AlterField( model_name='payment', name='order',", "name='discount_amount', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='discount amount'), ), migrations.AlterField(", "editable=False, max_length=36, verbose_name='tracking client id'), ), migrations.AlterField( model_name='order', name='user_email', field=models.EmailField(blank=True,", "field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='billing address'), ), migrations.AlterField( model_name='order', name='discount_amount',", "to='account.Address', verbose_name='billing address'), ), migrations.AlterField( model_name='order', name='discount_amount', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2,", "model_name='deliverygroup', name='last_updated', field=models.DateTimeField(auto_now=True, null=True, verbose_name='last updated'), ), migrations.AlterField( model_name='deliverygroup', name='shipping_method_name',", "null=True, verbose_name='total net'), ), migrations.AlterField( model_name='order', name='total_tax', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2,", "import django_prices.models class Migration(migrations.Migration): dependencies = [ ('order', '0014_auto_20161028_0955'), ]", "), migrations.AlterField( model_name='order', name='voucher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='discount.Voucher', verbose_name='voucher'), ),", "('-last_status_change',), 'verbose_name': 'Order', 'verbose_name_plural': 'Orders'}, ), migrations.AlterModelOptions( name='ordereditem', options={'verbose_name': 'Ordered", "decimal_places=2, max_digits=12, null=True, verbose_name='total net'), ), migrations.AlterField( model_name='order', name='total_tax', field=django_prices.models.MoneyField(blank=True,", "null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'), ), migrations.AlterField( model_name='payment', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments',", "migrations.AlterField( model_name='deliverygroup', name='shipping_method_name', field=models.CharField(blank=True, default=None, editable=False, max_length=255, null=True, verbose_name='shipping method", "from django.conf import settings from django.db import migrations, models import", "migrations.AlterField( model_name='ordereditem', name='delivery_group', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='order.DeliveryGroup', verbose_name='delivery group'), ),", "on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='discount.Voucher', verbose_name='voucher'), ), migrations.AlterField( model_name='ordereditem', name='delivery_group', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE,", "migrations.AlterModelOptions( name='ordereditem', options={'verbose_name': 'Ordered item', 'verbose_name_plural': 'Ordered items'}, ), migrations.AlterModelOptions(", "# -*- coding: utf-8 -*- # Generated by Django 1.10.5", "model_name='order', name='shipping_address', field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='shipping address'), ),", "name='last_updated', field=models.DateTimeField(auto_now=True, null=True, verbose_name='last updated'), ), migrations.AlterField( model_name='deliverygroup', name='shipping_method_name', field=models.CharField(blank=True,", "migrations.AlterField( model_name='order', name='billing_address', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='account.Address', verbose_name='billing address'), ),", "max_digits=12, null=True, verbose_name='total net'), ), migrations.AlterField( model_name='order', name='total_tax', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY,", "related_name='+', to='account.Address', verbose_name='shipping address'), ), migrations.AlterField( model_name='order', name='total_net', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY,", "# Generated by Django 1.10.5 on 2017-02-06 10:07 from __future__", "django.conf import settings from django.db import migrations, models import django.db.models.deletion", "migrations.AlterField( model_name='deliverygroup', name='tracking_number', field=models.CharField(blank=True, default='', max_length=255, verbose_name='tracking number'), ), migrations.AlterField(", "model_name='order', name='total_tax', field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True, verbose_name='total tax'), ),", "import unicode_literals from django.conf import settings from django.db import migrations,", "migrations.AlterField( model_name='order', name='discount_name', field=models.CharField(blank=True, default='', max_length=255, verbose_name='discount name'), ), migrations.AlterField(", "unicode_literals from django.conf import settings from django.db import migrations, models", "migrations, models import django.db.models.deletion import django_prices.models class Migration(migrations.Migration): dependencies =" ]
[ "\"\"\" return self._post('update_config/{}'.format(config_group_id), json=dict(name=name)) def delete(self, config_id): \"\"\" Deletes an", "The ID of the project \"\"\" return self._get('get_configs/{}'.format(project_id)) def add(self,", "\"\"\" def __repr__(self): return '<TestRailAPI config>' def get(self, project_id): \"\"\"", "the configuration group \"\"\" return self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name)) def delete_group(self, config_group_id):", "configuration (requires TestRail 5.2 or later). :param config_group_id: The ID", "should be added to :param name: The name of the", "project_id: The ID of the project \"\"\" return self._get('get_configs/{}'.format(project_id)) def", "name=''): \"\"\" Updates an existing configuration (requires TestRail 5.2 or", "or later). :param config_group_id: The ID of the configuration \"\"\"", "\"\"\" return self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name)) def delete_group(self, config_group_id): \"\"\" Deletes an", "groups (requires TestRail 3.1 or later). :param project_id: The ID", "a new configuration (requires TestRail 5.2 or later). :param config_group_id:", "to create or modify configurations. \"\"\" def __repr__(self): return '<TestRailAPI", "be added to :param name: str, The name of the", "details about configurations and to create or modify configurations. \"\"\"", "self._post('update_config/{}'.format(config_group_id), json=dict(name=name)) def delete(self, config_id): \"\"\" Deletes an existing configuration", "\"\"\" Creates a new configuration group (requires TestRail 5.2 or", "name: The name of the configuration group \"\"\" return self._post('update_config_group/{}'.format(config_group_id),", "configuration should be added to :param name: str, The name", ":param name: The name of the configuration group (required) \"\"\"", "about configurations and to create or modify configurations. \"\"\" def", "TestRail 5.2 or later). :param project_id:The ID of the project", "and to create or modify configurations. \"\"\" def __repr__(self): return", "by configuration groups (requires TestRail 3.1 or later). :param project_id:", "def update(self, config_group_id, name=''): \"\"\" Updates an existing configuration (requires", "the configuration should be added to :param name: str, The", "Config(TestRailAPIBase): \"\"\" Use the following API methods to request details", "json=dict(name=name)) def update(self, config_group_id, name=''): \"\"\" Updates an existing configuration", "\"\"\" Updates an existing configuration group (requires TestRail 5.2 or", "configuration group should be added to :param name: The name", "the configuration group the configuration should be added to :param", "name of the configuration (required) \"\"\" return self._post('update_config/{}'.format(config_group_id), json=dict(name=name)) def", "group (requires TestRail 5.2 or later). :param config_group_id: The ID", "an existing configuration (requires TestRail 5.2 or later). :param config_group_id:", "TestRail 5.2 or later). :param project_id: The ID of the", "(requires TestRail 3.1 or later). :param project_id: The ID of", "config>' def get(self, project_id): \"\"\" Returns a list of available", "The ID of the configuration group the configuration should be", "of the project the configuration group should be added to", "list of available priorities. \"\"\" return self._get('get_priorities') def template(self, project_id):", "or later). :param config_group_id: The ID of the configuration group", "\"\"\" Returns a list of available configurations, grouped by configuration", "The ID of the configuration \"\"\" return self._post('delete_config_group/{}'.format(config_group_id)) def priority(self):", "be added to :param name: The name of the configuration", "later). :param project_id:The ID of the project \"\"\" return self._get('get_templates/{}'.format(project_id))", "__repr__(self): return '<TestRailAPI config>' def get(self, project_id): \"\"\" Returns a", "<reponame>tonybearpan/testrail-lib #!/usr/bin/env python # -*- coding: utf-8 -*- from .base", "an existing configuration (requires TestRail 5.2 or later). :param config_id:", "\"\"\" return self._post('delete_config/{}'.format(config_id)) def add_group(self, project_id, name=''): \"\"\" Creates a", "str, The name of the configuration (required) \"\"\" return self._post('update_config/{}'.format(config_group_id),", "name of the configuration (required) \"\"\" return self._post('add_config/{}'.format(config_group_id), json=dict(name=name)) def", ":param config_group_id: The ID of the configuration group :param name:", "a list of available priorities. \"\"\" return self._get('get_priorities') def template(self,", "\"\"\" return self._get('get_priorities') def template(self, project_id): \"\"\" Returns a list", "Returns a list of available priorities. \"\"\" return self._get('get_priorities') def", "group :param name: The name of the configuration group \"\"\"", "self._get('get_priorities') def template(self, project_id): \"\"\" Returns a list of available", "delete(self, config_id): \"\"\" Deletes an existing configuration (requires TestRail 5.2", "of the configuration group (required) \"\"\" return self._post('add_config_group/{}'.format(project_id), json=dict(name=name)) def", "The ID of the configuration group :param name: The name", "project \"\"\" return self._get('get_configs/{}'.format(project_id)) def add(self, config_group_id, name=''): \"\"\" Creates", "the configuration (required) \"\"\" return self._post('update_config/{}'.format(config_group_id), json=dict(name=name)) def delete(self, config_id):", "configuration group \"\"\" return self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name)) def delete_group(self, config_group_id): \"\"\"", "config_group_id, name=''): \"\"\" Updates an existing configuration (requires TestRail 5.2", "Returns a list of available configurations, grouped by configuration groups", "config_group_id: The ID of the configuration \"\"\" return self._post('delete_config_group/{}'.format(config_group_id)) def", "name: str, The name of the configuration (required) \"\"\" return", "TestRail 5.2 or later). :param config_id: \"\"\" return self._post('delete_config/{}'.format(config_id)) def", "of the configuration (required) \"\"\" return self._post('add_config/{}'.format(config_group_id), json=dict(name=name)) def update(self,", "configurations, grouped by configuration groups (requires TestRail 3.1 or later).", "configuration group :param name: The name of the configuration group", "\"\"\" Use the following API methods to request details about", "group \"\"\" return self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name)) def delete_group(self, config_group_id): \"\"\" Deletes", "import TestRailAPIBase class Config(TestRailAPIBase): \"\"\" Use the following API methods", "configurations. \"\"\" def __repr__(self): return '<TestRailAPI config>' def get(self, project_id):", "ID of the configuration \"\"\" return self._post('delete_config_group/{}'.format(config_group_id)) def priority(self): \"\"\"", "config_group_id): \"\"\" Deletes an existing configuration (requires TestRail 5.2 or", "\"\"\" return self._post('add_config/{}'.format(config_group_id), json=dict(name=name)) def update(self, config_group_id, name=''): \"\"\" Updates", "the following API methods to request details about configurations and", "the configuration (required) \"\"\" return self._post('add_config/{}'.format(config_group_id), json=dict(name=name)) def update(self, config_group_id,", "of available priorities. \"\"\" return self._get('get_priorities') def template(self, project_id): \"\"\"", "configuration (required) \"\"\" return self._post('update_config/{}'.format(config_group_id), json=dict(name=name)) def delete(self, config_id): \"\"\"", "return self._post('update_config/{}'.format(config_group_id), json=dict(name=name)) def delete(self, config_id): \"\"\" Deletes an existing", "self._post('add_config_group/{}'.format(project_id), json=dict(name=name)) def update_group(self, config_group_id, name): \"\"\" Updates an existing", "existing configuration (requires TestRail 5.2 or later). :param config_group_id: The", "-*- coding: utf-8 -*- from .base import TestRailAPIBase class Config(TestRailAPIBase):", "of available configurations, grouped by configuration groups (requires TestRail 3.1", "grouped by configuration groups (requires TestRail 3.1 or later). :param", "API methods to request details about configurations and to create", "the configuration group :param name: The name of the configuration", "return self._post('delete_config_group/{}'.format(config_group_id)) def priority(self): \"\"\" Returns a list of available", ":param project_id: The ID of the project \"\"\" return self._get('get_configs/{}'.format(project_id))", "configuration (requires TestRail 5.2 or later). :param config_id: \"\"\" return", "TestRail 3.1 or later). :param project_id: The ID of the", ":param config_group_id: The ID of the configuration \"\"\" return self._post('delete_config_group/{}'.format(config_group_id))", "or later). :param project_id: The ID of the project \"\"\"", "group (requires TestRail 5.2 or later). :param project_id: The ID", "to :param name: The name of the configuration group (required)", "def update_group(self, config_group_id, name): \"\"\" Updates an existing configuration group", "available priorities. \"\"\" return self._get('get_priorities') def template(self, project_id): \"\"\" Returns", "return self._get('get_configs/{}'.format(project_id)) def add(self, config_group_id, name=''): \"\"\" Creates a new", ":param name: The name of the configuration group \"\"\" return", "The ID of the project the configuration group should be", "Creates a new configuration (requires TestRail 5.2 or later). :param", "create or modify configurations. \"\"\" def __repr__(self): return '<TestRailAPI config>'", "Updates an existing configuration (requires TestRail 5.2 or later). :param", "the configuration \"\"\" return self._post('delete_config_group/{}'.format(config_group_id)) def priority(self): \"\"\" Returns a", "available configurations, grouped by configuration groups (requires TestRail 3.1 or", "a list of available templates (requires TestRail 5.2 or later).", "coding: utf-8 -*- from .base import TestRailAPIBase class Config(TestRailAPIBase): \"\"\"", "'<TestRailAPI config>' def get(self, project_id): \"\"\" Returns a list of", "\"\"\" return self._get('get_configs/{}'.format(project_id)) def add(self, config_group_id, name=''): \"\"\" Creates a", "list of available configurations, grouped by configuration groups (requires TestRail", "\"\"\" Updates an existing configuration (requires TestRail 5.2 or later).", "of the configuration group the configuration should be added to", "(requires TestRail 5.2 or later). :param config_id: \"\"\" return self._post('delete_config/{}'.format(config_id))", ":param project_id: The ID of the project the configuration group", "existing configuration group (requires TestRail 5.2 or later). :param config_group_id:", "utf-8 -*- from .base import TestRailAPIBase class Config(TestRailAPIBase): \"\"\" Use", "config_id: \"\"\" return self._post('delete_config/{}'.format(config_id)) def add_group(self, project_id, name=''): \"\"\" Creates", "5.2 or later). :param project_id: The ID of the project", "python # -*- coding: utf-8 -*- from .base import TestRailAPIBase", "or later). :param project_id: The ID of the project the", "config_group_id, name=''): \"\"\" Creates a new configuration (requires TestRail 5.2", "config_group_id, name): \"\"\" Updates an existing configuration group (requires TestRail", "return self._post('delete_config/{}'.format(config_id)) def add_group(self, project_id, name=''): \"\"\" Creates a new", "ID of the configuration group :param name: The name of", "Updates an existing configuration group (requires TestRail 5.2 or later).", "\"\"\" Returns a list of available priorities. \"\"\" return self._get('get_priorities')", "self._get('get_configs/{}'.format(project_id)) def add(self, config_group_id, name=''): \"\"\" Creates a new configuration", "template(self, project_id): \"\"\" Returns a list of available templates (requires", "# -*- coding: utf-8 -*- from .base import TestRailAPIBase class", "Returns a list of available templates (requires TestRail 5.2 or", "#!/usr/bin/env python # -*- coding: utf-8 -*- from .base import", "3.1 or later). :param project_id: The ID of the project", "request details about configurations and to create or modify configurations.", "(requires TestRail 5.2 or later). :param project_id: The ID of", "(required) \"\"\" return self._post('add_config_group/{}'.format(project_id), json=dict(name=name)) def update_group(self, config_group_id, name): \"\"\"", "Deletes an existing configuration (requires TestRail 5.2 or later). :param", "added to :param name: str, The name of the configuration", "TestRail 5.2 or later). :param config_group_id: The ID of the", "group should be added to :param name: The name of", "name): \"\"\" Updates an existing configuration group (requires TestRail 5.2", "later). :param config_id: \"\"\" return self._post('delete_config/{}'.format(config_id)) def add_group(self, project_id, name=''):", "(requires TestRail 5.2 or later). :param project_id:The ID of the", "str, The name of the configuration (required) \"\"\" return self._post('add_config/{}'.format(config_group_id),", "to request details about configurations and to create or modify", "def delete(self, config_id): \"\"\" Deletes an existing configuration (requires TestRail", ".base import TestRailAPIBase class Config(TestRailAPIBase): \"\"\" Use the following API", "to :param name: str, The name of the configuration (required)", "def get(self, project_id): \"\"\" Returns a list of available configurations,", "json=dict(name=name)) def delete(self, config_id): \"\"\" Deletes an existing configuration (requires", "(requires TestRail 5.2 or later). :param config_group_id: The ID of", "return self._post('add_config_group/{}'.format(project_id), json=dict(name=name)) def update_group(self, config_group_id, name): \"\"\" Updates an", "(required) \"\"\" return self._post('update_config/{}'.format(config_group_id), json=dict(name=name)) def delete(self, config_id): \"\"\" Deletes", "return self._post('add_config/{}'.format(config_group_id), json=dict(name=name)) def update(self, config_group_id, name=''): \"\"\" Updates an", "json=dict(name=name)) def delete_group(self, config_group_id): \"\"\" Deletes an existing configuration (requires", "add(self, config_group_id, name=''): \"\"\" Creates a new configuration (requires TestRail", "get(self, project_id): \"\"\" Returns a list of available configurations, grouped", "5.2 or later). :param config_group_id: The ID of the configuration", "or later). :param config_id: \"\"\" return self._post('delete_config/{}'.format(config_id)) def add_group(self, project_id,", ":param name: str, The name of the configuration (required) \"\"\"", "configuration group (requires TestRail 5.2 or later). :param project_id: The", "name of the configuration group \"\"\" return self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name)) def", "def template(self, project_id): \"\"\" Returns a list of available templates", "a list of available configurations, grouped by configuration groups (requires", "\"\"\" return self._post('add_config_group/{}'.format(project_id), json=dict(name=name)) def update_group(self, config_group_id, name): \"\"\" Updates", "the configuration group should be added to :param name: The", "\"\"\" Returns a list of available templates (requires TestRail 5.2", "of available templates (requires TestRail 5.2 or later). :param project_id:The", "def __repr__(self): return '<TestRailAPI config>' def get(self, project_id): \"\"\" Returns", "a new configuration group (requires TestRail 5.2 or later). :param", "or modify configurations. \"\"\" def __repr__(self): return '<TestRailAPI config>' def", "The name of the configuration group \"\"\" return self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name))", "later). :param config_group_id: The ID of the configuration group :param", "following API methods to request details about configurations and to", "name of the configuration group (required) \"\"\" return self._post('add_config_group/{}'.format(project_id), json=dict(name=name))", "should be added to :param name: str, The name of", "configuration group (required) \"\"\" return self._post('add_config_group/{}'.format(project_id), json=dict(name=name)) def update_group(self, config_group_id,", "def delete_group(self, config_group_id): \"\"\" Deletes an existing configuration (requires TestRail", "config_group_id: The ID of the configuration group :param name: The", "later). :param project_id: The ID of the project \"\"\" return", "modify configurations. \"\"\" def __repr__(self): return '<TestRailAPI config>' def get(self,", "project the configuration group should be added to :param name:", "of the configuration group :param name: The name of the", "config_id): \"\"\" Deletes an existing configuration (requires TestRail 5.2 or", "project_id, name=''): \"\"\" Creates a new configuration group (requires TestRail", "new configuration group (requires TestRail 5.2 or later). :param project_id:", "priority(self): \"\"\" Returns a list of available priorities. \"\"\" return", "templates (requires TestRail 5.2 or later). :param project_id:The ID of", "self._post('add_config/{}'.format(config_group_id), json=dict(name=name)) def update(self, config_group_id, name=''): \"\"\" Updates an existing", "configuration group (requires TestRail 5.2 or later). :param config_group_id: The", "self._post('delete_config/{}'.format(config_id)) def add_group(self, project_id, name=''): \"\"\" Creates a new configuration", "added to :param name: The name of the configuration group", "existing configuration (requires TestRail 5.2 or later). :param config_id: \"\"\"", "configuration (required) \"\"\" return self._post('add_config/{}'.format(config_group_id), json=dict(name=name)) def update(self, config_group_id, name=''):", "of the configuration (required) \"\"\" return self._post('update_config/{}'.format(config_group_id), json=dict(name=name)) def delete(self,", "project_id): \"\"\" Returns a list of available templates (requires TestRail", "available templates (requires TestRail 5.2 or later). :param project_id:The ID", "ID of the project \"\"\" return self._get('get_configs/{}'.format(project_id)) def add(self, config_group_id,", "The name of the configuration (required) \"\"\" return self._post('add_config/{}'.format(config_group_id), json=dict(name=name))", ":param config_id: \"\"\" return self._post('delete_config/{}'.format(config_id)) def add_group(self, project_id, name=''): \"\"\"", "config_group_id: The ID of the configuration group the configuration should", "def add_group(self, project_id, name=''): \"\"\" Creates a new configuration group", "self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name)) def delete_group(self, config_group_id): \"\"\" Deletes an existing configuration", "TestRailAPIBase class Config(TestRailAPIBase): \"\"\" Use the following API methods to", "(required) \"\"\" return self._post('add_config/{}'.format(config_group_id), json=dict(name=name)) def update(self, config_group_id, name=''): \"\"\"", "of the configuration \"\"\" return self._post('delete_config_group/{}'.format(config_group_id)) def priority(self): \"\"\" Returns", "name: The name of the configuration group (required) \"\"\" return", "name=''): \"\"\" Creates a new configuration (requires TestRail 5.2 or", "ID of the project the configuration group should be added", "or later). :param project_id:The ID of the project \"\"\" return", "later). :param project_id: The ID of the project the configuration", "5.2 or later). :param config_id: \"\"\" return self._post('delete_config/{}'.format(config_id)) def add_group(self,", "def priority(self): \"\"\" Returns a list of available priorities. \"\"\"", "delete_group(self, config_group_id): \"\"\" Deletes an existing configuration (requires TestRail 5.2", "class Config(TestRailAPIBase): \"\"\" Use the following API methods to request", "of the project \"\"\" return self._get('get_configs/{}'.format(project_id)) def add(self, config_group_id, name=''):", "\"\"\" Deletes an existing configuration (requires TestRail 5.2 or later).", "add_group(self, project_id, name=''): \"\"\" Creates a new configuration group (requires", ":param config_group_id: The ID of the configuration group the configuration", "update(self, config_group_id, name=''): \"\"\" Updates an existing configuration (requires TestRail", "the configuration group (required) \"\"\" return self._post('add_config_group/{}'.format(project_id), json=dict(name=name)) def update_group(self,", "project_id): \"\"\" Returns a list of available configurations, grouped by", "group (required) \"\"\" return self._post('add_config_group/{}'.format(project_id), json=dict(name=name)) def update_group(self, config_group_id, name):", "methods to request details about configurations and to create or", "5.2 or later). :param project_id:The ID of the project \"\"\"", "configuration groups (requires TestRail 3.1 or later). :param project_id: The", "later). :param config_group_id: The ID of the configuration group the", "from .base import TestRailAPIBase class Config(TestRailAPIBase): \"\"\" Use the following", "Creates a new configuration group (requires TestRail 5.2 or later).", "group the configuration should be added to :param name: str,", "-*- from .base import TestRailAPIBase class Config(TestRailAPIBase): \"\"\" Use the", "configuration \"\"\" return self._post('delete_config_group/{}'.format(config_group_id)) def priority(self): \"\"\" Returns a list", "Use the following API methods to request details about configurations", "ID of the configuration group the configuration should be added", "The name of the configuration group (required) \"\"\" return self._post('add_config_group/{}'.format(project_id),", "The name of the configuration (required) \"\"\" return self._post('update_config/{}'.format(config_group_id), json=dict(name=name))", "name=''): \"\"\" Creates a new configuration group (requires TestRail 5.2", "configurations and to create or modify configurations. \"\"\" def __repr__(self):", "update_group(self, config_group_id, name): \"\"\" Updates an existing configuration group (requires", "an existing configuration group (requires TestRail 5.2 or later). :param", "def add(self, config_group_id, name=''): \"\"\" Creates a new configuration (requires", "priorities. \"\"\" return self._get('get_priorities') def template(self, project_id): \"\"\" Returns a", "the project \"\"\" return self._get('get_configs/{}'.format(project_id)) def add(self, config_group_id, name=''): \"\"\"", "new configuration (requires TestRail 5.2 or later). :param config_group_id: The", "self._post('delete_config_group/{}'.format(config_group_id)) def priority(self): \"\"\" Returns a list of available priorities.", "the project the configuration group should be added to :param", "later). :param config_group_id: The ID of the configuration \"\"\" return", "\"\"\" return self._post('delete_config_group/{}'.format(config_group_id)) def priority(self): \"\"\" Returns a list of", "configuration group the configuration should be added to :param name:", "return self._get('get_priorities') def template(self, project_id): \"\"\" Returns a list of", "project_id: The ID of the project the configuration group should", "return self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name)) def delete_group(self, config_group_id): \"\"\" Deletes an existing", "of the configuration group \"\"\" return self._post('update_config_group/{}'.format(config_group_id), json=dict(name=name)) def delete_group(self,", "json=dict(name=name)) def update_group(self, config_group_id, name): \"\"\" Updates an existing configuration", "return '<TestRailAPI config>' def get(self, project_id): \"\"\" Returns a list", "\"\"\" Creates a new configuration (requires TestRail 5.2 or later).", "list of available templates (requires TestRail 5.2 or later). :param" ]
[ "def assert_of_type(wanted_type, wanted_object, message=\"\"): if not message: message = f\"{wanted_object}", "found in list {searched_list} \\n \" \\ f\"although it should", "not equal to expected \" \\ f\"result {expected_result}\" assert actual_result", "= f\"{actual_result} resulted with None\" assert actual_result, message def assert_equal(actual_result,", "not message: message = f\"{actual_result} is not equal to expected", "\\ f\"result {expected_result}\" assert actual_result == expected_result, message def assert_in_list(searched_list,", "list {searched_list}\" assert wanted_element in searched_list, message def assert_not_in_list(searched_list, unwanted_element,", "= f\"{wanted_object} is not of type: {wanted_type}\" assert isinstance(wanted_object, wanted_type),", "def assert_not_in_list(searched_list, unwanted_element, message=\"\"): if not message: message = f\"'{unwanted_element}'", "to expected \" \\ f\"result {expected_result}\" assert actual_result == expected_result,", "if not message: message = f\"'{unwanted_element}' found in list {searched_list}", "message = f\"Failed to find '{wanted_element}' in list {searched_list}\" assert", "{searched_list} \\n \" \\ f\"although it should not be\" assert", "f\"'{unwanted_element}' found in list {searched_list} \\n \" \\ f\"although it", "message=\"\"): if not message: message = f\"{actual_result} is not equal", "message: message = f\"{wanted_object} is not of type: {wanted_type}\" assert", "assert_equal(actual_result, expected_result, message=\"\"): if not message: message = f\"{actual_result} is", "not message: message = f\"'{unwanted_element}' found in list {searched_list} \\n", "= f\"Failed to find '{wanted_element}' in list {searched_list}\" assert wanted_element", "in searched_list, message def assert_of_type(wanted_type, wanted_object, message=\"\"): if not message:", "assert_not_none(actual_result, message=\"\"): if not message: message = f\"{actual_result} resulted with", "find '{wanted_element}' in list {searched_list}\" assert wanted_element in searched_list, message", "\" \\ f\"result {expected_result}\" assert actual_result == expected_result, message def", "in list {searched_list} \\n \" \\ f\"although it should not", "message = f\"'{unwanted_element}' found in list {searched_list} \\n \" \\", "'{wanted_element}' in list {searched_list}\" assert wanted_element in searched_list, message def", "if not message: message = f\"{actual_result} resulted with None\" assert", "searched_list, message def assert_not_in_list(searched_list, unwanted_element, message=\"\"): if not message: message", "\\n \" \\ f\"although it should not be\" assert unwanted_element", "{searched_list}\" assert wanted_element in searched_list, message def assert_not_in_list(searched_list, unwanted_element, message=\"\"):", "expected \" \\ f\"result {expected_result}\" assert actual_result == expected_result, message", "in searched_list, message def assert_not_in_list(searched_list, unwanted_element, message=\"\"): if not message:", "expected_result, message def assert_in_list(searched_list, wanted_element, message=\"\"): if not message: message", "message def assert_in_list(searched_list, wanted_element, message=\"\"): if not message: message =", "assert_not_in_list(searched_list, unwanted_element, message=\"\"): if not message: message = f\"'{unwanted_element}' found", "def assert_in_list(searched_list, wanted_element, message=\"\"): if not message: message = f\"Failed", "message: message = f\"'{unwanted_element}' found in list {searched_list} \\n \"", "= f\"'{unwanted_element}' found in list {searched_list} \\n \" \\ f\"although", "def assert_not_none(actual_result, message=\"\"): if not message: message = f\"{actual_result} resulted", "not message: message = f\"Failed to find '{wanted_element}' in list", "None\" assert actual_result, message def assert_equal(actual_result, expected_result, message=\"\"): if not", "wanted_object, message=\"\"): if not message: message = f\"{wanted_object} is not", "message=\"\"): if not message: message = f\"{wanted_object} is not of", "f\"Failed to find '{wanted_element}' in list {searched_list}\" assert wanted_element in", "message=\"\"): if not message: message = f\"{actual_result} resulted with None\"", "actual_result == expected_result, message def assert_in_list(searched_list, wanted_element, message=\"\"): if not", "def assert_equal(actual_result, expected_result, message=\"\"): if not message: message = f\"{actual_result}", "message: message = f\"Failed to find '{wanted_element}' in list {searched_list}\"", "unwanted_element, message=\"\"): if not message: message = f\"'{unwanted_element}' found in", "unwanted_element not in searched_list, message def assert_of_type(wanted_type, wanted_object, message=\"\"): if", "to find '{wanted_element}' in list {searched_list}\" assert wanted_element in searched_list,", "message def assert_equal(actual_result, expected_result, message=\"\"): if not message: message =", "f\"{wanted_object} is not of type: {wanted_type}\" assert isinstance(wanted_object, wanted_type), message", "{expected_result}\" assert actual_result == expected_result, message def assert_in_list(searched_list, wanted_element, message=\"\"):", "if not message: message = f\"{wanted_object} is not of type:", "not message: message = f\"{wanted_object} is not of type: {wanted_type}\"", "resulted with None\" assert actual_result, message def assert_equal(actual_result, expected_result, message=\"\"):", "assert unwanted_element not in searched_list, message def assert_of_type(wanted_type, wanted_object, message=\"\"):", "wanted_element, message=\"\"): if not message: message = f\"Failed to find", "f\"{actual_result} is not equal to expected \" \\ f\"result {expected_result}\"", "message: message = f\"{actual_result} is not equal to expected \"", "message=\"\"): if not message: message = f\"Failed to find '{wanted_element}'", "it should not be\" assert unwanted_element not in searched_list, message", "if not message: message = f\"Failed to find '{wanted_element}' in", "not be\" assert unwanted_element not in searched_list, message def assert_of_type(wanted_type,", "list {searched_list} \\n \" \\ f\"although it should not be\"", "== expected_result, message def assert_in_list(searched_list, wanted_element, message=\"\"): if not message:", "be\" assert unwanted_element not in searched_list, message def assert_of_type(wanted_type, wanted_object,", "\\ f\"although it should not be\" assert unwanted_element not in", "in list {searched_list}\" assert wanted_element in searched_list, message def assert_not_in_list(searched_list,", "searched_list, message def assert_of_type(wanted_type, wanted_object, message=\"\"): if not message: message", "expected_result, message=\"\"): if not message: message = f\"{actual_result} is not", "not in searched_list, message def assert_of_type(wanted_type, wanted_object, message=\"\"): if not", "message = f\"{actual_result} resulted with None\" assert actual_result, message def", "should not be\" assert unwanted_element not in searched_list, message def", "wanted_element in searched_list, message def assert_not_in_list(searched_list, unwanted_element, message=\"\"): if not", "if not message: message = f\"{actual_result} is not equal to", "equal to expected \" \\ f\"result {expected_result}\" assert actual_result ==", "message def assert_not_in_list(searched_list, unwanted_element, message=\"\"): if not message: message =", "\" \\ f\"although it should not be\" assert unwanted_element not", "message = f\"{wanted_object} is not of type: {wanted_type}\" assert isinstance(wanted_object,", "message = f\"{actual_result} is not equal to expected \" \\", "actual_result, message def assert_equal(actual_result, expected_result, message=\"\"): if not message: message", "message def assert_of_type(wanted_type, wanted_object, message=\"\"): if not message: message =", "assert_of_type(wanted_type, wanted_object, message=\"\"): if not message: message = f\"{wanted_object} is", "f\"although it should not be\" assert unwanted_element not in searched_list,", "message: message = f\"{actual_result} resulted with None\" assert actual_result, message", "= f\"{actual_result} is not equal to expected \" \\ f\"result", "f\"result {expected_result}\" assert actual_result == expected_result, message def assert_in_list(searched_list, wanted_element,", "is not equal to expected \" \\ f\"result {expected_result}\" assert", "assert wanted_element in searched_list, message def assert_not_in_list(searched_list, unwanted_element, message=\"\"): if", "assert actual_result == expected_result, message def assert_in_list(searched_list, wanted_element, message=\"\"): if", "assert actual_result, message def assert_equal(actual_result, expected_result, message=\"\"): if not message:", "with None\" assert actual_result, message def assert_equal(actual_result, expected_result, message=\"\"): if", "message=\"\"): if not message: message = f\"'{unwanted_element}' found in list", "assert_in_list(searched_list, wanted_element, message=\"\"): if not message: message = f\"Failed to", "f\"{actual_result} resulted with None\" assert actual_result, message def assert_equal(actual_result, expected_result,", "not message: message = f\"{actual_result} resulted with None\" assert actual_result," ]
[ "License. import numpy as np import unittest from srl import", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state) def test_act_accumulates_score(self): w = world.World.parse('@.') sim = simulation.Simulation(world.Static(w))", "w = world.World.parse('$.@^#') sim = simulation.Simulation(world.Static(w)) self.assertTrue( (np.array([[2, 3, 4,", "sim = simulation.Simulation(world.Static(w)) self.assertTrue( (np.array([[2, 3, 4, 5, 1]], dtype=np.int8)", "distributed under the License is distributed on an \"AS IS\"", "permissions and # limitations under the License. import numpy as", "the specific language governing permissions and # limitations under the", "2017 Google Inc. # # Licensed under the Apache License,", "# limitations under the License. import numpy as np import", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "import numpy as np import unittest from srl import movement", "except in compliance with the License. # You may obtain", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "sim.act(movement.ACTION_LEFT) self.assertEqual(-2, sim.score) def test_to_array(self): w = world.World.parse('$.@^#') sim =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "as np import unittest from srl import movement from srl", "world class TestSimulation(unittest.TestCase): def test_in_terminal_state(self): w = world.World.parse('@^') sim =", "not use this file except in compliance with the License.", "limitations under the License. import numpy as np import unittest", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "you may not use this file except in compliance with", "test_act_accumulates_score(self): w = world.World.parse('@.') sim = simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT) self.assertEqual(-2,", "= world.World.parse('@.') sim = simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT) self.assertEqual(-2, sim.score) def", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "language governing permissions and # limitations under the License. import", "self.assertTrue( (np.array([[2, 3, 4, 5, 1]], dtype=np.int8) == sim.to_array()) .all())", "= simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state) def test_act_accumulates_score(self): w = world.World.parse('@.')", "def test_in_terminal_state(self): w = world.World.parse('@^') sim = simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT)", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "test_to_array(self): w = world.World.parse('$.@^#') sim = simulation.Simulation(world.Static(w)) self.assertTrue( (np.array([[2, 3,", "CONDITIONS OF ANY KIND, either express or implied. # See", "from srl import world class TestSimulation(unittest.TestCase): def test_in_terminal_state(self): w =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "import unittest from srl import movement from srl import simulation", "srl import simulation from srl import world class TestSimulation(unittest.TestCase): def", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "from srl import simulation from srl import world class TestSimulation(unittest.TestCase):", "sim = simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT) self.assertEqual(-2, sim.score) def test_to_array(self): w", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "test_in_terminal_state(self): w = world.World.parse('@^') sim = simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state)", "w = world.World.parse('@.') sim = simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT) self.assertEqual(-2, sim.score)", "= world.World.parse('$.@^#') sim = simulation.Simulation(world.Static(w)) self.assertTrue( (np.array([[2, 3, 4, 5,", "world.World.parse('@.') sim = simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT) self.assertEqual(-2, sim.score) def test_to_array(self):", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "import movement from srl import simulation from srl import world", "= simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT) self.assertEqual(-2, sim.score) def test_to_array(self): w =", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License for the specific language governing permissions and # limitations", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "numpy as np import unittest from srl import movement from", "Copyright 2017 Google Inc. # # Licensed under the Apache", "Google Inc. # # Licensed under the Apache License, Version", "sim.score) def test_to_array(self): w = world.World.parse('$.@^#') sim = simulation.Simulation(world.Static(w)) self.assertTrue(", "self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state) def test_act_accumulates_score(self): w = world.World.parse('@.') sim =", "the License for the specific language governing permissions and #", "np import unittest from srl import movement from srl import", "sim = simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state) def test_act_accumulates_score(self): w =", "TestSimulation(unittest.TestCase): def test_in_terminal_state(self): w = world.World.parse('@^') sim = simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state)", "(the \"License\"); # you may not use this file except", "srl import world class TestSimulation(unittest.TestCase): def test_in_terminal_state(self): w = world.World.parse('@^')", "Apache License, Version 2.0 (the \"License\"); # you may not", "# you may not use this file except in compliance", "either express or implied. # See the License for the", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "the License is distributed on an \"AS IS\" BASIS, #", "in compliance with the License. # You may obtain a", "the License. import numpy as np import unittest from srl", "= simulation.Simulation(world.Static(w)) self.assertTrue( (np.array([[2, 3, 4, 5, 1]], dtype=np.int8) ==", "software # distributed under the License is distributed on an", "= world.World.parse('@^') sim = simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state) def test_act_accumulates_score(self):", "governing permissions and # limitations under the License. import numpy", "# Copyright 2017 Google Inc. # # Licensed under the", "# # Unless required by applicable law or agreed to", "self.assertEqual(-2, sim.score) def test_to_array(self): w = world.World.parse('$.@^#') sim = simulation.Simulation(world.Static(w))", "class TestSimulation(unittest.TestCase): def test_in_terminal_state(self): w = world.World.parse('@^') sim = simulation.Simulation(world.Static(w))", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "import simulation from srl import world class TestSimulation(unittest.TestCase): def test_in_terminal_state(self):", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "simulation.Simulation(world.Static(w)) self.assertTrue( (np.array([[2, 3, 4, 5, 1]], dtype=np.int8) == sim.to_array())", "Version 2.0 (the \"License\"); # you may not use this", "law or agreed to in writing, software # distributed under", "from srl import movement from srl import simulation from srl", "<gh_stars>10-100 # Copyright 2017 Google Inc. # # Licensed under", "srl import movement from srl import simulation from srl import", "implied. # See the License for the specific language governing", "simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state) def test_act_accumulates_score(self): w = world.World.parse('@.') sim", "under the Apache License, Version 2.0 (the \"License\"); # you", "\"License\"); # you may not use this file except in", "movement from srl import simulation from srl import world class", "sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT) self.assertEqual(-2, sim.score) def test_to_array(self): w = world.World.parse('$.@^#') sim", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "import world class TestSimulation(unittest.TestCase): def test_in_terminal_state(self): w = world.World.parse('@^') sim", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "and # limitations under the License. import numpy as np", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "unittest from srl import movement from srl import simulation from", "def test_to_array(self): w = world.World.parse('$.@^#') sim = simulation.Simulation(world.Static(w)) self.assertTrue( (np.array([[2,", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "self.assertTrue(sim.in_terminal_state) def test_act_accumulates_score(self): w = world.World.parse('@.') sim = simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT)", "to in writing, software # distributed under the License is", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "# See the License for the specific language governing permissions", "world.World.parse('@^') sim = simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state) def test_act_accumulates_score(self): w", "world.World.parse('$.@^#') sim = simulation.Simulation(world.Static(w)) self.assertTrue( (np.array([[2, 3, 4, 5, 1]],", "simulation from srl import world class TestSimulation(unittest.TestCase): def test_in_terminal_state(self): w", "You may obtain a copy of the License at #", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "under the License. import numpy as np import unittest from", "required by applicable law or agreed to in writing, software", "simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT) self.assertEqual(-2, sim.score) def test_to_array(self): w = world.World.parse('$.@^#')", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "def test_act_accumulates_score(self): w = world.World.parse('@.') sim = simulation.Simulation(world.Static(w)) sim.act(movement.ACTION_RIGHT) sim.act(movement.ACTION_LEFT)", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "the Apache License, Version 2.0 (the \"License\"); # you may", "w = world.World.parse('@^') sim = simulation.Simulation(world.Static(w)) self.assertFalse(sim.in_terminal_state) sim.act(movement.ACTION_RIGHT) self.assertTrue(sim.in_terminal_state) def" ]
[ "= False target = fetch_input_varnode(builder, pcode.find(\"input_0\")) if not target.type.is_pointer: target", "block = ir_func.append_basic_block(\"entry\") blocks[\"entry\"] = block builders[\"entry\"] = ir.IRBuilder(block) for", "lhs, rhs) result = builder.icmp_unsigned('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "= fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.or_(lhs, rhs) update_output(builder,", "lhs = fetch_input_varnode(builder, input_0) rhs = fetch_input_varnode(builder, input_1) target =", "check_shift_inputs(builder, lhs, rhs, target) output = builder.ashr(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "= builder.ptrtoint(rhs, rhs.type.pointee) output = builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder,", "output = builder.shl(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "False for instruction in function.find(\"instructions\"): if quiter: break address =", "ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text, 0)) else: source = fetch_input_varnode(builder, pcode.find(\"input_0\")) update_output(builder, pcode.find(\"output\"),", "populate_cfg(function, builders, blocks): builder = builders[\"entry\"] stack_size = 10 *", "fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(lhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NEGATE\": val = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "lhs, rhs, target) output = builder.mul(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(lhs) update_output(builder, pcode.find(\"output\"), result)", "rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs,", "builder.icmp_signed('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_ZEXT\":", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_CEIL\": raise Exception(\"Not implemented\") elif", "= fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "output) elif mnemonic.text == \"BOOL_NEGATE\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) result", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS_EQUAL\": lhs = fetch_input_varnode(builder,", "input_1.get(\"storage\") == \"unique\" and output.get(\"storage\") == \"unique\": # This is", "[]) elif mnemonic.text == \"CBRANCH\": true_target = blocks[pcode.find(\"input_0\").text[2:-2]] false_target =", "= builder.sub(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_CARRY\":", "defined\") return uniques[name.text] elif var_type == \"constant\": var = ir.Constant(ir.IntType(var_size),", "rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.and_(lhs, rhs)", "{} internal_functions = {} memory = {} flags = [\"ZF\",", "\"BOOL_NEGATE\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(lhs) update_output(builder, pcode.find(\"output\"),", "\"FLOAT_NEG\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ABS\": raise Exception(\"Not", "fnty, \"bit_extraction\") internal_functions[\"bit_extraction\"] = ir_func for function in root.findall('function'): name", "== \"INT_CARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "blocks[pcode.find(\"input_0\").text[2:-2]] false_target = list(blocks.values())[block_iterator + 1] condition = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "mnemonic.text == \"FLOAT_ROUND\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NAN\":", "target) output = builder.shl(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "Exception(\"Not a standard pcode instruction\") block_iterator += 1 instr +=", "rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.or_(lhs, rhs)", "= builder.icmp_signed('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "lhs2.type != rhs.type.as_pointer(): lhs2 = builder.bitcast(lhs2, rhs.type.as_pointer()) builder.store(rhs, lhs2) elif", "'internal' registers[register.get('name')] = var elif register.get('name') in pointers: var =", "builder.bitcast(lhs2, rhs.type.as_pointer()) builder.store(rhs, lhs2) elif mnemonic.text == \"BRANCH\": value =", "lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.sadd_with_overflow(lhs, rhs)", "= name.get(\"storage\") var_size = int(name.get(\"size\")) * 8 if var_type ==", "\"memory\": return memory[name.text] def update_output(builder, name, output): var_type = name.get(\"storage\")", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs, rhs =", "lhs, rhs) result = builder.icmp_signed('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('!=', lhs, rhs)", "int(register.get('size'))), None) var.linkage = 'internal' registers[register.get('name')] = var for memory_location", "== \"FLOAT_ROUND\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NAN\": raise", "elif mnemonic.text == \"INT_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "ir_func) if blocks == {}: return populate_cfg(function, builders, blocks) def", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_CARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "mnemonic.text == \"INT_DIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "\"INT_RIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "\"INT_SBORROW\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "int(name.get(\"size\")) * 8 if var_type == \"register\": return builder.load(registers[name.text]) elif", "1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SBORROW\": lhs =", "fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "= ir.Constant(ir.IntType(1), None) var.linkage = 'internal' registers[register.get('name')] = var elif", "else: lhs, rhs = int_check_inputs(builder, lhs, rhs, target) result =", "int_comparison_check_inputs(builder, lhs, rhs) result = builder.sadd_with_overflow(lhs, rhs) result = builder.extract_value(result,", "def build_function(name, module): func_return = ir.VoidType() fnty = ir.FunctionType(func_return, [])", "target) else: rhs = builder.zext(rhs, target) return lhs, rhs def", "\"INT_SDIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "== \"FLOAT_NOTEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESS\": raise", "var_type == \"unique\": uniques[name.text] = output def fetch_output_varnode(name): var_type =", "return builder.load(registers[name.text]) elif var_type == \"unique\": if name.text not in", "[]) ir_func = ir.Function(module, fnty, \"call_indirect\") internal_functions[\"call_indirect\"] = ir_func func_return", "mnemonic.text == \"INT_CARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "output) elif mnemonic.text == \"INT_LEFT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "rhs = check_shift_inputs(builder, lhs, rhs, target) output = builder.ashr(lhs, rhs)", "stack_size = 10 * 1024 * 1024 stack = builder.alloca(ir.IntType(8),", "populate_func(ir_func, function): builders, blocks = build_cfg(function, ir_func) if blocks ==", "== \"PIECE\": raise Exception(\"PIECE operation needs to be tested\") elif", "= builder.lshr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SRIGHT\":", "raise Exception(\"Not implemented\") elif mnemonic.text == \"MULTIEQUAL\": raise Exception(\"Not implemented\")", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SCARRY\": lhs = fetch_input_varnode(builder,", "= 0 no_branch = True for pcode in pcodes: pc", "\"FLOAT_NAN\": raise Exception(\"Not implemented\") elif mnemonic.text == \"INT2FLOAT\": raise Exception(\"Not", "target = pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"], []) elif mnemonic.text == \"USERDEFINED\": raise", "mnemonic.text == \"MULTIEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"INDIRECT\":", "return builders, blocks # noinspection DuplicatedCode def populate_cfg(function, builders, blocks):", "== \"INT_NOTEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "if lhs.type.is_pointer: lhs2 = lhs lhs = builder.ptrtoint(lhs, target) if", "rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee)", "return lhs, rhs def check_shift_inputs(builder, lhs, rhs, target): if lhs.type", "if name.text not in uniques: uniques[name.text] = None return uniques[name.text]", "fetch_input_varnode(builder, input_1) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) if input_0.text in", "result) elif mnemonic.text == \"INT_SUB\": input_0 = pcode.find(\"input_0\") input_1 =", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ABS\": raise Exception(\"Not implemented\") elif", "mnemonic.text == \"INT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT2FLOAT\":", "pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee) output = builder.sext(rhs,", "if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee) output = builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\"))", "target) output = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "int_comparison_check_inputs(builder, lhs, rhs): # For integer comparison operations. We assume", "result = builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "uniques[name.text] = None return uniques[name.text] def int_check_inputs(builder, lhs, rhs, target):", "= int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<=', lhs, rhs) update_output(builder,", "== \"INDIRECT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"PTRADD\": raise", "= pcode.find(\"input_1\") no_branch = False if input_1 is None: builder.ret_void()", "mnemonic.text == \"INT_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "== \"unique\": # This is incorrect. This is treating it", "block_iterator += 1 instr += 1 if block_iterator < len(blocks)", "= ir.Function(module, fnty, \"bit_extraction\") internal_functions[\"bit_extraction\"] = ir_func for function in", "* 1024 stack = builder.alloca(ir.IntType(8), stack_size, name=\"stack\") stack_top = builder.gep(stack,", "jump into some label in another function # might be", "ir_func = ir.Function(module, fnty, \"intra_function_branch\") internal_functions[\"intra_function_branch\"] = ir_func func_return =", "= builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "instruction? builder.call(internal_functions[\"intra_function_branch\"], []) elif mnemonic.text == \"CBRANCH\": true_target = blocks[pcode.find(\"input_0\").text[2:-2]]", "elif mnemonic.text == \"LOAD\": input_1 = pcode.find(\"input_1\") output = pcode.find(\"output\")", "result) elif mnemonic.text == \"INT_2COMP\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result", "blocks # noinspection DuplicatedCode def populate_cfg(function, builders, blocks): builder =", "target) return lhs, rhs def int_comparison_check_inputs(builder, lhs, rhs): # For", "0)]) if lhs2.type != rhs.type.as_pointer(): lhs2 = builder.bitcast(lhs2, rhs.type.as_pointer()) builder.store(rhs,", "registers[\"RSP\"]) builder.branch(list(blocks.values())[1]) block_iterator = 1 instr = 0 quiter =", "elif mnemonic.text == \"MULTIEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "comparison operations. We assume rhs is the correct type. if", "== \"INT_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "function) return module def populate_func(ir_func, function): builders, blocks = build_cfg(function,", "== \"INT_2COMP\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.not_(val) update_output(builder,", "result) elif mnemonic.text == \"INT_LESSEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "== \"CALL\": target = functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target, []) elif mnemonic.text ==", "Exception(\"Not implemented\") elif mnemonic.text == \"INT2FLOAT\": raise Exception(\"Not implemented\") elif", "= ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, name) return ir_func", "register in root.find('globals').findall('register'): if register.get('name') in flags: var = ir.GlobalVariable(module,", "if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) else: rhs = builder.zext(rhs,", "elif mnemonic.text == \"INT_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "Exception(\"Return value being passed\") elif mnemonic.text == \"PIECE\": raise Exception(\"PIECE", "builder.ptrtoint(rhs, rhs.type.pointee) output = builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"),", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_DIV\": raise Exception(\"Not implemented\")", "elif mnemonic.text == \"NEW\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "implemented\") elif mnemonic.text == \"FLOAT_SUB\": raise Exception(\"Not implemented\") elif mnemonic.text", "!= target: if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, target) else: lhs", "var = ir.GlobalVariable(module, ir.IntType(8 * int(register.get('size'))), register.get('name')) var.initializer = ir.Constant(ir.IntType(8", "= ir.VoidType() function_names = [] registers, functions, uniques, extracts =", "builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "value in functions: target = functions[value][0] builder.call(target, []) elif value", "builder.not_(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NEGATE\": val =", "\"INT_MULT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "def int_comparison_check_inputs(builder, lhs, rhs): # For integer comparison operations. We", "== \"FLOAT_EQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NOTEQUAL\": raise", "builder.gep(lhs, [ir.Constant(int64, int(input_1.text, 16))]) else: lhs, rhs = int_check_inputs(builder, lhs,", "var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)), None) var.linkage = 'internal' registers[register.get('name')] = var", "elif mnemonic.text == \"CBRANCH\": true_target = blocks[pcode.find(\"input_0\").text[2:-2]] false_target = list(blocks.values())[block_iterator", "ir.Constant(ir.IntType(1), None) var.linkage = 'internal' registers[register.get('name')] = var elif register.get('name')", "pcode.find(\"input_1\")) no_branch = False builder.cbranch(condition, true_target, false_target) elif mnemonic.text ==", "lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESSEQUAL\": lhs", "output) elif mnemonic.text == \"INT_DIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "uniques: uniques[name.text] = None return uniques[name.text] def int_check_inputs(builder, lhs, rhs,", "rhs) result = builder.sadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1) update_output(builder,", "output.text in flags and pcode.find(\"input_0\").get(\"storage\") == \"constant\": source = ir.Constant(ir.IntType(1),", "!= target and lhs != rhs: if rhs.type.is_pointer: rhs =", "for function in root.findall('function'): name = function.get('name') x = 1", "== \"constant\": result = builder.gep(lhs, [ir.Constant(int64, int(input_1.text, 16))]) else: lhs,", "xml.etree.ElementTree as et int32 = ir.IntType(32) int64 = ir.IntType(64) int1", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NEG\": raise Exception(\"Not implemented\") elif", "no_branch = False builder.cbranch(condition, true_target, false_target) elif mnemonic.text == \"BRANCHIND\":", "target.type.as_pointer()) builder.branch_indirect(target) elif mnemonic.text == \"CALL\": target = functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target,", "rhs: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) return lhs, rhs", "\"INT_DIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.xor(lhs, rhs)", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_RIGHT\": lhs = fetch_input_varnode(builder,", "mnemonic.text == \"FLOAT_NEG\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ABS\":", "def update_output(builder, name, output): var_type = name.get(\"storage\") if var_type ==", "ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SEXT\":", "\"CALLIND\": # target = pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"], []) elif mnemonic.text ==", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "mnemonic.text == \"INT_LESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "= builder.add(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SUB\":", "rhs, target) output = builder.shl(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "var elif var_type == \"memory\": return memory[name.text] def update_output(builder, name,", "elif mnemonic.text == \"FLOAT_CEIL\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "input_1 = pcode.find(\"input_1\") no_branch = False if input_1 is None:", "result = builder.sadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"),", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SQRT\": raise Exception(\"Not implemented\") elif", "== \"FLOAT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"TRUNC\": raise", "input_1 = pcode.find(\"input_1\") output = pcode.find(\"output\") rhs = fetch_input_varnode(builder, input_1)", "if instructions: block = ir_func.append_basic_block(\"entry\") blocks[\"entry\"] = block builders[\"entry\"] =", "rhs, target) output = builder.urem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "= builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.and_(lhs, rhs)", "rhs = fetch_input_varnode(builder, input_1) if input_1.get(\"storage\") == \"unique\" and output.get(\"storage\")", "= builder.load(rhs) update_output(builder, output, result) elif mnemonic.text == \"STORE\": input_1", "0 no_branch = True for pcode in pcodes: pc +=", "raise Exception(\"Not implemented\") elif mnemonic.text == \"INT2FLOAT\": raise Exception(\"Not implemented\")", "pcode instruction\") block_iterator += 1 instr += 1 if block_iterator", "instruction.find(\"pcodes\") pc = 0 no_branch = True for pcode in", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS\": lhs = fetch_input_varnode(builder,", "module def populate_func(ir_func, function): builders, blocks = build_cfg(function, ir_func) if", "rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<', lhs, rhs)", "\"constant\": source = ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text, 0)) else: source = fetch_input_varnode(builder,", "== \"INT_SBORROW\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "target) else: lhs = builder.zext(lhs, target) if rhs.type != target:", "builder.store(output, reg) elif var_type == \"unique\": uniques[name.text] = output def", "elif mnemonic.text == \"FLOAT_ADD\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "input_0) result = builder.trunc(val, ir.IntType(int(output.get(\"size\")) * 8)) update_output(builder, output, result)", "\"FLOAT_LESSEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ADD\": raise Exception(\"Not", "mnemonic.text == \"CALL\": target = functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target, []) elif mnemonic.text", "rhs, target) output = builder.sdiv(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "[]) ir_func = ir.Function(module, fnty, \"bit_extraction\") internal_functions[\"bit_extraction\"] = ir_func for", "rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.urem(lhs, rhs)", "correct type. if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, rhs.type) return lhs,", "builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_OR\": lhs", "pcode.find(\"input_0\")) result = builder.not_(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NAN\": raise Exception(\"Not implemented\") elif", "== \"constant\": var = ir.Constant(ir.IntType(var_size), int(name.text, 0)) return var elif", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_OR\": lhs =", "None) var.linkage = 'internal' registers[register.get('name')] = var elif register.get('name') in", "'internal' memory[memory_location.get('name')] = var func_return = ir.VoidType() fnty = ir.FunctionType(func_return,", "output = builder.lshr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "\"STORE\": input_1 = pcode.find(\"input_1\") # target input_2 = pcode.find(\"input_2\") #", "lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS_EQUAL\": lhs", "\"register\": reg = registers[name.text] if reg.type != output.type.as_pointer(): reg =", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ROUND\": raise Exception(\"Not implemented\")", "elif var_type == \"unique\": uniques[name.text] = output def fetch_output_varnode(name): var_type", "result) elif mnemonic.text == \"INT_SCARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.sdiv(lhs,", "lhs = builder.ptrtoint(lhs, target) else: lhs = builder.zext(lhs, target) if", "pcode.find(\"input_0\")) result = builder.neg(lhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "= fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "\"RBP\", \"EBP\", \"ESP\"] def lift(filename): root = et.parse(filename).getroot() module =", "{} instructions = function.find(\"instructions\") if instructions: block = ir_func.append_basic_block(\"entry\") blocks[\"entry\"]", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target = ir.IntType(int(pcode.find(\"output\").get(\"size\"))", "source rhs = fetch_input_varnode(builder, input_2) lhs = fetch_output_varnode(input_1) lhs2 =", "= int_check_inputs(builder, lhs, rhs, target) result = builder.add(lhs, rhs) update_output(builder,", "1 mnemonic = pcode.find(\"name\") if mnemonic.text == \"COPY\": output =", "= fetch_input_varnode(builder, input_1) if input_1.get(\"storage\") == \"unique\" and output.get(\"storage\") ==", "= function.find(\"instructions\") if instructions: block = ir_func.append_basic_block(\"entry\") blocks[\"entry\"] = block", "ir_func = ir.Function(module, fnty, \"call_indirect\") internal_functions[\"call_indirect\"] = ir_func func_return =", "lhs, rhs, target) output = builder.sdiv(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "None: builder.ret_void() else: raise Exception(\"Return value being passed\") elif mnemonic.text", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_MULT\": lhs =", "target) output = builder.mul(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "elif mnemonic.text == \"INT_SRIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "builder.ret_void() else: raise Exception(\"Return value being passed\") elif mnemonic.text ==", "pcode.find(\"input_1\") if input_1.text == \"0x0\": val = fetch_input_varnode(builder, input_0) result", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_ADD\": input_0 = pcode.find(\"input_0\")", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ROUND\": raise Exception(\"Not implemented\") elif", "return module def populate_func(ir_func, function): builders, blocks = build_cfg(function, ir_func)", "elif mnemonic.text == \"PIECE\": raise Exception(\"PIECE operation needs to be", "pc += 1 mnemonic = pcode.find(\"name\") if mnemonic.text == \"COPY\":", "result = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "= fetch_output_varnode(input_1) lhs2 = builder.gep(lhs, [ir.Constant(int64, 0)]) if lhs2.type !=", "function # might be solved with callbr instruction? builder.call(internal_functions[\"intra_function_branch\"], [])", "pcode.find(\"output\") input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") if input_1.text ==", "elif mnemonic.text == \"INT_SBORROW\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "elif mnemonic.text == \"FLOAT_SQRT\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "== \"INT_SUB\": input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs =", "pcode.find(\"input_0\")) update_output(builder, pcode.find(\"output\"), source) elif mnemonic.text == \"LOAD\": input_1 =", "# noinspection DuplicatedCode def populate_cfg(function, builders, blocks): builder = builders[\"entry\"]", "uniques[name.text] elif var_type == \"constant\": var = ir.Constant(ir.IntType(var_size), int(name.text, 0))", "ir.Function(module, fnty, name) return ir_func def build_cfg(function, ir_func): builders, blocks", "= blocks[pcode.find(\"input_0\").text[2:-2]] false_target = list(blocks.values())[block_iterator + 1] condition = fetch_input_varnode(builder,", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_XOR\": lhs = fetch_input_varnode(builder,", "target = blocks[value] builder.branch(target) no_branch = False else: # weird", "= ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) if input_0.text in pointers and input_1.get(\"storage\")", "uniques[name.text] = output def fetch_output_varnode(name): var_type = name.get(\"storage\") if var_type", "lhs, rhs, target): if lhs.type != target: if lhs.type.is_pointer: lhs2", "= pcode.find(\"output\") if output.text in flags and pcode.find(\"input_0\").get(\"storage\") == \"constant\":", "if rhs.type != target: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target)", "implemented\") elif mnemonic.text == \"INDIRECT\": raise Exception(\"Not implemented\") elif mnemonic.text", "== \"LOAD\": input_1 = pcode.find(\"input_1\") output = pcode.find(\"output\") rhs =", "rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "lhs, rhs = check_shift_inputs(builder, lhs, rhs, target) output = builder.ashr(lhs,", "= ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"bit_extraction\") internal_functions[\"bit_extraction\"] =", "builders[address] = ir.IRBuilder(block) return builders, blocks # noinspection DuplicatedCode def", "ir_func.append_basic_block(\"entry\") blocks[\"entry\"] = block builders[\"entry\"] = ir.IRBuilder(block) for instruction in", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NOTEQUAL\": raise Exception(\"Not implemented\") elif", "1024 stack = builder.alloca(ir.IntType(8), stack_size, name=\"stack\") stack_top = builder.gep(stack, [ir.Constant(int64,", "mnemonic.text == \"INT_LEFT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "rhs, target): if lhs.type != target: if lhs.type.is_pointer: lhs =", "memory = {} flags = [\"ZF\", \"CF\", \"OF\", \"SF\"] pointers", "pcode.find(\"input_1\") output = pcode.find(\"output\") rhs = fetch_input_varnode(builder, input_1) if input_1.get(\"storage\")", "str(x) x += 1 function_names.append(name) address = function.get('address') functions[address] =", "else: raise Exception(\"Not a standard pcode instruction\") block_iterator += 1", "target) output = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "builder.ptrtoint(rhs, target) else: rhs = builder.zext(rhs, target) return lhs, rhs", "lhs, rhs, target) output = builder.urem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "var else: var = ir.GlobalVariable(module, ir.IntType(8 * int(register.get('size'))), register.get('name')) var.initializer", "in builders: builder = builders[address] pcodes = instruction.find(\"pcodes\") pc =", "elif mnemonic.text == \"BOOL_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "var.linkage = 'internal' memory[memory_location.get('name')] = var func_return = ir.VoidType() fnty", "mnemonic.text == \"INDIRECT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"PTRADD\":", "referenced before defined\") return uniques[name.text] elif var_type == \"constant\": var", "int_comparison_check_inputs(builder, lhs, rhs) result = builder.uadd_with_overflow(lhs, rhs) result = builder.extract_value(result,", "\"FLOAT_ADD\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SUB\": raise Exception(\"Not", "8) lhs, rhs = check_shift_inputs(builder, lhs, rhs, target) output =", "\"INT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT2FLOAT\": raise Exception(\"Not", "result = builder.gep(lhs, [ir.Constant(int64, int(input_1.text, 16))]) else: lhs, rhs =", "{}, {} instructions = function.find(\"instructions\") if instructions: block = ir_func.append_basic_block(\"entry\")", "not target.type.is_pointer: target = builder.inttoptr(target, target.type.as_pointer()) builder.branch_indirect(target) elif mnemonic.text ==", "register.get('name')) var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)), None) var.linkage = 'internal' registers[register.get('name')] =", "= int_check_inputs(builder, lhs, rhs, target) output = builder.mul(lhs, rhs) update_output(builder,", "* 8 if var_type == \"register\": return builder.load(registers[name.text]) elif var_type", "= fetch_input_varnode(builder, pcode.find(\"input_1\")) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "mnemonic.text == \"CBRANCH\": true_target = blocks[pcode.find(\"input_0\").text[2:-2]] false_target = list(blocks.values())[block_iterator +", "stack_top = builder.gep(stack, [ir.Constant(int64, stack_size - 8)], name=\"stack_top\") builder.store(stack_top, registers[\"RSP\"])", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_REM\": lhs =", "\"_\" + str(x) x += 1 function_names.append(name) address = function.get('address')", "\"constant\": result = builder.gep(lhs, [ir.Constant(int64, int(input_1.text, 16))]) else: lhs, rhs", "\"INT_CARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "elif mnemonic.text == \"FLOAT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "== \"INT_SDIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "int(register.get('size'))), register.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(register.get('size'))), None) var.linkage =", "if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, target) else: lhs = builder.zext(lhs,", "result = builder.uadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"),", "elif mnemonic.text == \"SUBPIECE\": output = pcode.find(\"output\") input_0 = pcode.find(\"input_0\")", "no_branch = False target = fetch_input_varnode(builder, pcode.find(\"input_0\")) if not target.type.is_pointer:", "mnemonic.text == \"INT_REM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "1 function_names.append(name) address = function.get('address') functions[address] = [build_function(name, module), function]", "ir.IntType(1), register.get('name')) var.initializer = ir.Constant(ir.IntType(1), None) var.linkage = 'internal' registers[register.get('name')]", "var func_return = ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func =", "mnemonic.text == \"INT_SREM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "{}: return populate_cfg(function, builders, blocks) def build_function(name, module): func_return =", "ir.IntType(int(output.get(\"size\")) * 8)) update_output(builder, output, result) else: builder.call(internal_functions['bit_extraction'], []) elif", "var_type = name.get(\"storage\") var_size = int(name.get(\"size\")) * 8 if var_type", "import ir import xml.etree.ElementTree as et int32 = ir.IntType(32) int64", "lhs2 = lhs lhs = builder.ptrtoint(lhs, target) if lhs2 ==", "pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs,", "= int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<', lhs, rhs) update_output(builder,", "\"intra_function_branch\") internal_functions[\"intra_function_branch\"] = ir_func func_return = ir.VoidType() fnty = ir.FunctionType(func_return,", "8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_ADD\": input_0 =", "builder.cbranch(condition, true_target, false_target) elif mnemonic.text == \"BRANCHIND\": no_branch = False", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SBORROW\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "elif mnemonic.text == \"TRUNC\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "stack_size, name=\"stack\") stack_top = builder.gep(stack, [ir.Constant(int64, stack_size - 8)], name=\"stack_top\")", "no_branch = False else: # weird jump into some label", "else: lhs = builder.zext(lhs, target) if rhs.type != target: if", "mnemonic.text == \"INT_RIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "lhs, rhs, target) output = builder.srem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "== \"INT_DIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "= builder.ptrtoint(rhs, target) else: rhs = builder.zext(rhs, target) return lhs,", "elif mnemonic.text == \"INT_2COMP\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result =", "pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.sadd_with_overflow(lhs,", "builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_AND\": lhs", "== \"INT_NEGATE\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(val) update_output(builder,", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_MULT\": raise Exception(\"Not implemented\") elif", "reg) elif var_type == \"unique\": uniques[name.text] = output def fetch_output_varnode(name):", "pc = 0 no_branch = True for pcode in pcodes:", "var_type = name.get(\"storage\") if var_type == \"register\": return registers[name.text] elif", "8) lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output =", "1] condition = fetch_input_varnode(builder, pcode.find(\"input_1\")) no_branch = False builder.cbranch(condition, true_target,", "= builder.neg(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_XOR\": lhs", "rhs is the correct type. if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs,", "elif mnemonic.text == \"INT_ADD\": input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\")", "= int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('!=', lhs, rhs) update_output(builder,", "pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.uadd_with_overflow(lhs,", "name, output): var_type = name.get(\"storage\") if var_type == \"register\": reg", "if not target.type.is_pointer: target = builder.inttoptr(target, target.type.as_pointer()) builder.branch_indirect(target) elif mnemonic.text", "builder = builders[\"entry\"] stack_size = 10 * 1024 * 1024", "= 1 instr = 0 quiter = False for instruction", "input_1 = pcode.find(\"input_1\") if input_1.text == \"0x0\": val = fetch_input_varnode(builder,", "address = instruction.find(\"address\").text block = ir_func.append_basic_block(address) blocks[address] = block builders[address]", "in pointers and input_1.get(\"storage\") == \"constant\": result = builder.gep(lhs, [ir.Constant(int64,", "elif mnemonic.text == \"INT_SLESS_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "lhs, rhs, target): if lhs.type != target: if lhs.type.is_pointer: lhs", "int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<', lhs, rhs) update_output(builder, pcode.find(\"output\"),", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ADD\": raise Exception(\"Not implemented\") elif", "elif mnemonic.text == \"INT_LESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "elif var_type == \"memory\": return memory[name.text] def update_output(builder, name, output):", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee) output", "builder.store(stack_top, registers[\"RSP\"]) builder.branch(list(blocks.values())[1]) block_iterator = 1 instr = 0 quiter", "rhs = builder.gep(rhs, [ir.Constant(int64, 0)]) result = builder.load(rhs) update_output(builder, output,", "input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") if input_1.text == \"0x0\":", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SRIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "being passed\") elif mnemonic.text == \"PIECE\": raise Exception(\"PIECE operation needs", "pcode in pcodes: pc += 1 mnemonic = pcode.find(\"name\") if", "\"FLOAT_FLOOR\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ROUND\": raise Exception(\"Not", "+= 1 if block_iterator < len(blocks) and no_branch: builder.branch(list(blocks.values())[block_iterator]) def", "result = builder.gep(lhs, [ir.Constant(int64, -int(input_1.text, 16))]) else: lhs, rhs =", "mnemonic.text == \"INT_SCARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "function.find(\"instructions\") if instructions: block = ir_func.append_basic_block(\"entry\") blocks[\"entry\"] = block builders[\"entry\"]", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESSEQUAL\": lhs = fetch_input_varnode(builder,", "rhs, target): if lhs.type != target: if lhs.type.is_pointer: lhs2 =", "rhs) result = builder.icmp_unsigned('!=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "pointers and input_1.get(\"storage\") == \"constant\": result = builder.gep(lhs, [ir.Constant(int64, -int(input_1.text,", "-int(input_1.text, 16))]) else: lhs, rhs = int_check_inputs(builder, lhs, rhs, target)", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_REM\": lhs = fetch_input_varnode(builder,", "builder.call(target, []) elif value in blocks: target = blocks[value] builder.branch(target)", "functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target, []) elif mnemonic.text == \"CALLIND\": # target =", "target) if rhs.type != target: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs,", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ABS\": raise Exception(\"Not implemented\")", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NEG\": raise Exception(\"Not implemented\")", "+ str(x) x += 1 function_names.append(name) address = function.get('address') functions[address]", "= builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_OR\":", "ir.IRBuilder(block) return builders, blocks # noinspection DuplicatedCode def populate_cfg(function, builders,", "\"INT_LESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "elif mnemonic.text == \"INT_MULT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "output) elif mnemonic.text == \"INT_SEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if", "\"BRANCH\": value = pcode.find(\"input_0\").text[2:-2] if value in functions: target =", "function_names: name = name + \"_\" + str(x) x +=", "10 * 1024 * 1024 stack = builder.alloca(ir.IntType(8), stack_size, name=\"stack\")", "et int32 = ir.IntType(32) int64 = ir.IntType(64) int1 = ir.IntType(1)", "builder.load(registers[name.text]) elif var_type == \"unique\": if name.text not in list(uniques.keys()):", "8)) update_output(builder, output, result) else: builder.call(internal_functions['bit_extraction'], []) elif mnemonic.text ==", "ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"intra_function_branch\") internal_functions[\"intra_function_branch\"] = ir_func", "elif mnemonic.text == \"CPOOLREF\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "= {}, {}, {}, {} internal_functions = {} memory =", "= builder.inttoptr(target, target.type.as_pointer()) builder.branch_indirect(target) elif mnemonic.text == \"CALL\": target =", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SUB\": raise Exception(\"Not implemented\") elif", "\"INT_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "[ir.Constant(int64, int(input_1.text, 16))]) else: lhs, rhs = int_check_inputs(builder, lhs, rhs,", "= builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SCARRY\":", "populate_func(ir_func, function) return module def populate_func(ir_func, function): builders, blocks =", "elif mnemonic.text == \"INT_ZEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer:", "rhs def int_comparison_check_inputs(builder, lhs, rhs): # For integer comparison operations.", "mnemonic.text == \"BRANCHIND\": no_branch = False target = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "= int_check_inputs(builder, lhs, rhs, target) output = builder.xor(lhs, rhs) update_output(builder,", "\"INT_ADD\": input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs = fetch_input_varnode(builder,", "target) output = builder.ashr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") if input_1.text == \"0x0\": val =", "= ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"call_indirect\") internal_functions[\"call_indirect\"] =", "0)]) result = builder.load(rhs) update_output(builder, output, result) elif mnemonic.text ==", "= ir.Function(module, fnty, \"intra_function_branch\") internal_functions[\"intra_function_branch\"] = ir_func func_return = ir.VoidType()", "elif mnemonic.text == \"BRANCHIND\": no_branch = False target = fetch_input_varnode(builder,", "= pcode.find(\"output\") input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") if input_1.text", "== \"unique\" and output.get(\"storage\") == \"unique\": # This is incorrect.", "builder.uadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif", "ir.IntType(8 * int(memory_location.get('size'))), memory_location.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(memory_location.get('size'))), None)", "check_shift_inputs(builder, lhs, rhs, target) output = builder.lshr(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "output) elif mnemonic.text == \"INT_SDIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "raise Exception(\"Not implemented\") elif mnemonic.text == \"CPOOLREF\": raise Exception(\"Not implemented\")", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) result = builder.add(lhs,", "1 if block_iterator < len(blocks) and no_branch: builder.branch(list(blocks.values())[block_iterator]) def fetch_input_varnode(builder,", "output = pcode.find(\"output\") input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") if", "== \"CPOOLREF\": raise Exception(\"Not implemented\") elif mnemonic.text == \"NEW\": raise", "elif mnemonic.text == \"FLOAT_SUB\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "target) output = builder.sdiv(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "output def fetch_output_varnode(name): var_type = name.get(\"storage\") if var_type == \"register\":", "16))]) else: lhs, rhs = int_check_inputs(builder, lhs, rhs, target) result", "builder.gep(stack, [ir.Constant(int64, stack_size - 8)], name=\"stack_top\") builder.store(stack_top, registers[\"RSP\"]) builder.branch(list(blocks.values())[1]) block_iterator", "input_1 is None: builder.ret_void() else: raise Exception(\"Return value being passed\")", "rhs.type != target: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) else:", "elif mnemonic.text == \"INT_LEFT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "1 update_output(builder, output, rhs) else: if input_1.text in pointers: rhs", "builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "= {} flags = [\"ZF\", \"CF\", \"OF\", \"SF\"] pointers =", "== \"CAST\": raise Exception(\"Not implemented\") else: raise Exception(\"Not a standard", "implemented\") elif mnemonic.text == \"RETURN\": input_1 = pcode.find(\"input_1\") no_branch =", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.xor(lhs,", "if reg.type != output.type.as_pointer(): reg = builder.bitcast(reg, output.type.as_pointer()) builder.store(output, reg)", "target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs = check_shift_inputs(builder, lhs,", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"BOOL_NEGATE\": lhs =", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"FLOAT_EQUAL\": raise Exception(\"Not implemented\")", "result) elif mnemonic.text == \"INT_SLESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "elif mnemonic.text == \"USERDEFINED\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "var elif register.get('name') in pointers: var = ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name'))", "fetch_input_varnode(builder, input_2) lhs = fetch_output_varnode(input_1) lhs2 = builder.gep(lhs, [ir.Constant(int64, 0)])", "implemented\") elif mnemonic.text == \"TRUNC\": raise Exception(\"Not implemented\") elif mnemonic.text", "elif value in blocks: target = blocks[value] builder.branch(target) no_branch =", "\"CBRANCH\": true_target = blocks[pcode.find(\"input_0\").text[2:-2]] false_target = list(blocks.values())[block_iterator + 1] condition", "registers[register.get('name')] = var for memory_location in root.find('memory').findall('memory'): var = ir.GlobalVariable(module,", "internal_functions[\"intra_function_branch\"] = ir_func func_return = ir.VoidType() fnty = ir.FunctionType(func_return, [])", "elif mnemonic.text == \"CALLIND\": # target = pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"], [])", "None) var.linkage = 'internal' registers[register.get('name')] = var else: var =", "int_check_inputs(builder, lhs, rhs, target) output = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "= ir.IRBuilder(block) return builders, blocks # noinspection DuplicatedCode def populate_cfg(function,", "output.type.as_pointer(): reg = builder.bitcast(reg, output.type.as_pointer()) builder.store(output, reg) elif var_type ==", "[ir.Constant(int64, 0)]) result = builder.load(rhs) update_output(builder, output, result) elif mnemonic.text", "ir.Constant(ir.IntType(var_size), int(name.text, 0)) return var elif var_type == \"memory\": return", "registers[register.get('name')] = var else: var = ir.GlobalVariable(module, ir.IntType(8 * int(register.get('size'))),", "var.initializer = ir.Constant(ir.IntType(1), None) var.linkage = 'internal' registers[register.get('name')] = var", "output = builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output) elif", "\"NEW\": raise Exception(\"Not implemented\") elif mnemonic.text == \"MULTIEQUAL\": raise Exception(\"Not", "- 8)], name=\"stack_top\") builder.store(stack_top, registers[\"RSP\"]) builder.branch(list(blocks.values())[1]) block_iterator = 1 instr", "elif mnemonic.text == \"INT_SREM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "in another function # might be solved with callbr instruction?", "+= 1 instr += 1 if block_iterator < len(blocks) and", "= ir.Module(name=\"lifted\") for register in root.find('globals').findall('register'): if register.get('name') in flags:", "ir.Function(module, fnty, \"call_indirect\") internal_functions[\"call_indirect\"] = ir_func func_return = ir.VoidType() fnty", "and pcode.find(\"input_0\").get(\"storage\") == \"constant\": source = ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text, 0)) else:", "1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_2COMP\": val =", "for register in root.find('globals').findall('register'): if register.get('name') in flags: var =", "for address in functions: ir_func, function = functions[address] populate_func(ir_func, function)", "def fetch_input_varnode(builder, name): var_type = name.get(\"storage\") var_size = int(name.get(\"size\")) *", "rhs = builder.ptrtoint(rhs, rhs.type.pointee) output = builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8))", "\"FLOAT_CEIL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_FLOOR\": raise Exception(\"Not", "build_cfg(function, ir_func) if blocks == {}: return populate_cfg(function, builders, blocks)", "if address in builders: builder = builders[address] pcodes = instruction.find(\"pcodes\")", "builders, blocks = build_cfg(function, ir_func) if blocks == {}: return", "block builders[\"entry\"] = ir.IRBuilder(block) for instruction in instructions: address =", "ir_func = ir.Function(module, fnty, \"bit_extraction\") internal_functions[\"bit_extraction\"] = ir_func for function", "if lhs2.type != rhs.type.as_pointer(): lhs2 = builder.bitcast(lhs2, rhs.type.as_pointer()) builder.store(rhs, lhs2)", "elif mnemonic.text == \"FLOAT_EQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "mnemonic.text == \"SUBPIECE\": output = pcode.find(\"output\") input_0 = pcode.find(\"input_0\") input_1", "name.get(\"storage\") var_size = int(name.get(\"size\")) * 8 if var_type == \"register\":", "= ir_func for function in root.findall('function'): name = function.get('name') x", "\"INT_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "builders[\"entry\"] stack_size = 10 * 1024 * 1024 stack =", "output = builder.sdiv(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "builder.icmp_unsigned('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS_EQUAL\":", "elif mnemonic.text == \"STORE\": input_1 = pcode.find(\"input_1\") # target input_2", "target and lhs != rhs: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs,", "internal_functions[\"bit_extraction\"] = ir_func for function in root.findall('function'): name = function.get('name')", "\"PTRSUB\": raise Exception(\"Not implemented\") elif mnemonic.text == \"CAST\": raise Exception(\"Not", "= {}, {} instructions = function.find(\"instructions\") if instructions: block =", "elif mnemonic.text == \"FLOAT_NOTEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "raise Exception(\"Not implemented\") elif mnemonic.text == \"TRUNC\": raise Exception(\"Not implemented\")", "raise Exception(\"Not implemented\") elif mnemonic.text == \"PTRADD\": raise Exception(\"Not implemented\")", "= builder.not_(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NEGATE\": val", "lhs, rhs, target) output = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "if lhs.type != target: if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, target)", "= [build_function(name, module), function] for address in functions: ir_func, function", "implemented\") elif mnemonic.text == \"PTRADD\": raise Exception(\"Not implemented\") elif mnemonic.text", "= int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<=', lhs, rhs) update_output(builder,", "type. if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, rhs.type) return lhs, rhs", "builder.sadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif", "result) elif mnemonic.text == \"INT_SLESS_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "== \"INT_MULT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "= builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_AND\":", "= builder.shl(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_RIGHT\":", "* int(memory_location.get('size'))), memory_location.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(memory_location.get('size'))), None) var.linkage", "operations. We assume rhs is the correct type. if lhs.type.is_pointer:", "\"FLOAT_DIV\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NEG\": raise Exception(\"Not", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.and_(lhs,", "builder.sub(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_CARRY\": lhs", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "def build_cfg(function, ir_func): builders, blocks = {}, {} instructions =", "\"ESP\"] def lift(filename): root = et.parse(filename).getroot() module = ir.Module(name=\"lifted\") for", "ir.Constant(ir.PointerType(ir.IntType(8)), None) var.linkage = 'internal' registers[register.get('name')] = var else: var", "if mnemonic.text == \"COPY\": output = pcode.find(\"output\") if output.text in", "mnemonic.text == \"INT_SBORROW\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_DIV\": lhs = fetch_input_varnode(builder,", "mnemonic.text == \"FLOAT_NOTEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESS\":", "mnemonic.text == \"NEW\": raise Exception(\"Not implemented\") elif mnemonic.text == \"MULTIEQUAL\":", "some label in another function # might be solved with", "mnemonic.text == \"BOOL_NEGATE\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(lhs)", "== \"BOOL_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "var = ir.Constant(ir.IntType(var_size), int(name.text, 0)) return var elif var_type ==", "update_output(builder, pcode.find(\"output\"), source) elif mnemonic.text == \"LOAD\": input_1 = pcode.find(\"input_1\")", "\"RIP\", \"RBP\", \"EBP\", \"ESP\"] def lift(filename): root = et.parse(filename).getroot() module", "* int(memory_location.get('size'))), None) var.linkage = 'internal' memory[memory_location.get('name')] = var func_return", "elif mnemonic.text == \"FLOAT_NAN\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "var.linkage = 'internal' registers[register.get('name')] = var else: var = ir.GlobalVariable(module,", "ir_func, function = functions[address] populate_func(ir_func, function) return module def populate_func(ir_func,", "= int_check_inputs(builder, lhs, rhs, target) output = builder.srem(lhs, rhs) update_output(builder,", "target) output = builder.div(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "= var elif register.get('name') in pointers: var = ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)),", "'internal' registers[register.get('name')] = var else: var = ir.GlobalVariable(module, ir.IntType(8 *", "fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "in flags and pcode.find(\"input_0\").get(\"storage\") == \"constant\": source = ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text,", "builder.gep(lhs, [ir.Constant(int64, -int(input_1.text, 16))]) else: lhs, rhs = int_check_inputs(builder, lhs,", "lhs, rhs, target) output = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "mnemonic.text == \"FLOAT_SUB\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_MULT\":", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT2FLOAT\": raise Exception(\"Not implemented\")", "lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<=', lhs,", "= builders[address] pcodes = instruction.find(\"pcodes\") pc = 0 no_branch =", "= int_comparison_check_inputs(builder, lhs, rhs) result = builder.sadd_with_overflow(lhs, rhs) result =", "rhs.type.as_pointer(): lhs2 = builder.bitcast(lhs2, rhs.type.as_pointer()) builder.store(rhs, lhs2) elif mnemonic.text ==", "mnemonic.text == \"INT_SDIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "value being passed\") elif mnemonic.text == \"PIECE\": raise Exception(\"PIECE operation", "fnty, \"intra_function_branch\") internal_functions[\"intra_function_branch\"] = ir_func func_return = ir.VoidType() fnty =", "lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<', lhs,", "flags: var = ir.GlobalVariable(module, ir.IntType(1), register.get('name')) var.initializer = ir.Constant(ir.IntType(1), None)", "pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.xor(lhs, rhs) update_output(builder,", "pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<',", "mnemonic.text == \"RETURN\": input_1 = pcode.find(\"input_1\") no_branch = False if", "val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(val) update_output(builder, pcode.find(\"output\"), result)", "input_1 = pcode.find(\"input_1\") # target input_2 = pcode.find(\"input_2\") # source", "passed\") elif mnemonic.text == \"PIECE\": raise Exception(\"PIECE operation needs to", "== \"SUBPIECE\": output = pcode.find(\"output\") input_0 = pcode.find(\"input_0\") input_1 =", "= functions[value][0] builder.call(target, []) elif value in blocks: target =", "import xml.etree.ElementTree as et int32 = ir.IntType(32) int64 = ir.IntType(64)", "\"SUBPIECE\": output = pcode.find(\"output\") input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\")", "target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) if input_0.text in pointers and", "target) if lhs2 == rhs: rhs = lhs if rhs.type", "output) elif mnemonic.text == \"INT_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "elif mnemonic.text == \"PTRADD\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "elif mnemonic.text == \"CAST\": raise Exception(\"Not implemented\") else: raise Exception(\"Not", "= var else: var = ir.GlobalVariable(module, ir.IntType(8 * int(register.get('size'))), register.get('name'))", "rhs = lhs if rhs.type != target and lhs !=", "mnemonic.text == \"FLOAT_SQRT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_CEIL\":", "result) elif mnemonic.text == \"INT_CARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESS\": raise Exception(\"Not implemented\")", "label in another function # might be solved with callbr", "= block builders[address] = ir.IRBuilder(block) return builders, blocks # noinspection", "function.find(\"instructions\"): if quiter: break address = instruction.find(\"address\").text if address in", "pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('==',", "lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result =", "name + \"_\" + str(x) x += 1 function_names.append(name) address", "\"COPY\": output = pcode.find(\"output\") if output.text in flags and pcode.find(\"input_0\").get(\"storage\")", "raise Exception(\"Not implemented\") elif mnemonic.text == \"INDIRECT\": raise Exception(\"Not implemented\")", "== \"0x0\": val = fetch_input_varnode(builder, input_0) result = builder.trunc(val, ir.IntType(int(output.get(\"size\"))", "= pcode.find(\"input_2\") # source rhs = fetch_input_varnode(builder, input_2) lhs =", "pcode.find(\"output\") rhs = fetch_input_varnode(builder, input_1) if input_1.get(\"storage\") == \"unique\" and", "input_1 = pcode.find(\"input_1\") lhs = fetch_input_varnode(builder, input_0) rhs = fetch_input_varnode(builder,", "int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('==', lhs, rhs) update_output(builder, pcode.find(\"output\"),", "rhs) result = builder.icmp_unsigned('==', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "fetch_input_varnode(builder, input_1) if input_1.get(\"storage\") == \"unique\" and output.get(\"storage\") == \"unique\":", "lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_ZEXT\": rhs", "elif mnemonic.text == \"BRANCH\": value = pcode.find(\"input_0\").text[2:-2] if value in", "builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SBORROW\": lhs", "= builders[\"entry\"] stack_size = 10 * 1024 * 1024 stack", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_RIGHT\": lhs =", "builder.ptrtoint(rhs, target) return lhs, rhs def check_shift_inputs(builder, lhs, rhs, target):", "= fetch_input_varnode(builder, input_0) result = builder.trunc(val, ir.IntType(int(output.get(\"size\")) * 8)) update_output(builder,", "None) var.linkage = 'internal' memory[memory_location.get('name')] = var func_return = ir.VoidType()", "'internal' registers[register.get('name')] = var for memory_location in root.find('memory').findall('memory'): var =", "ir.PointerType(ir.IntType(8)), register.get('name')) var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)), None) var.linkage = 'internal' registers[register.get('name')]", "output = pcode.find(\"output\") rhs = fetch_input_varnode(builder, input_1) if input_1.get(\"storage\") ==", "\"constant\": var = ir.Constant(ir.IntType(var_size), int(name.text, 0)) return var elif var_type", "0)) return var elif var_type == \"memory\": return memory[name.text] def", "= builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_2COMP\":", "mnemonic.text == \"FLOAT_LESSEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ADD\":", "rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) return lhs, rhs def check_shift_inputs(builder,", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SQRT\": raise Exception(\"Not implemented\")", "= ir.IntType(64) int1 = ir.IntType(1) void_type = ir.VoidType() function_names =", "elif var_type == \"unique\": if name.text not in uniques: uniques[name.text]", "in functions: ir_func, function = functions[address] populate_func(ir_func, function) return module", "== \"STORE\": input_1 = pcode.find(\"input_1\") # target input_2 = pcode.find(\"input_2\")", "lhs, rhs) result = builder.icmp_unsigned('==', lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "be solved with callbr instruction? builder.call(internal_functions[\"intra_function_branch\"], []) elif mnemonic.text ==", "instr += 1 if block_iterator < len(blocks) and no_branch: builder.branch(list(blocks.values())[block_iterator])", "builder.ptrtoint(rhs, rhs.type.pointee) output = builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"),", "[] registers, functions, uniques, extracts = {}, {}, {}, {}", "for instruction in function.find(\"instructions\"): if quiter: break address = instruction.find(\"address\").text", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_OR\": lhs = fetch_input_varnode(builder,", "pcode.find(\"name\") if mnemonic.text == \"COPY\": output = pcode.find(\"output\") if output.text", "pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.and_(lhs, rhs) update_output(builder,", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESS\": raise Exception(\"Not implemented\") elif", "builders[address] pcodes = instruction.find(\"pcodes\") pc = 0 no_branch = True", "and input_1.get(\"storage\") == \"constant\": result = builder.gep(lhs, [ir.Constant(int64, int(input_1.text, 16))])", "\"RETURN\": input_1 = pcode.find(\"input_1\") no_branch = False if input_1 is", "Exception(\"Temporary variable referenced before defined\") return uniques[name.text] elif var_type ==", "mnemonic.text == \"INT_NEGATE\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(val)", "function_names = [] registers, functions, uniques, extracts = {}, {},", "memory_location in root.find('memory').findall('memory'): var = ir.GlobalVariable(module, ir.IntType(8 * int(memory_location.get('size'))), memory_location.get('name'))", "before defined\") return uniques[name.text] elif var_type == \"constant\": var =", "var_type == \"memory\": return memory[name.text] def update_output(builder, name, output): var_type", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(val) update_output(builder, pcode.find(\"output\"), result) elif", "lhs != rhs: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) return", "== \"INT_SREM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "in list(uniques.keys()): raise Exception(\"Temporary variable referenced before defined\") return uniques[name.text]", "mnemonic.text == \"COPY\": output = pcode.find(\"output\") if output.text in flags", "module = ir.Module(name=\"lifted\") for register in root.find('globals').findall('register'): if register.get('name') in", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_LEFT\": lhs = fetch_input_varnode(builder,", "else: if input_1.text in pointers: rhs = builder.gep(rhs, [ir.Constant(int64, 0)])", "no_branch = False if input_1 is None: builder.ret_void() else: raise", "target) output = builder.lshr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "copy, should load the memory address in the input 1", "register.get('name') in flags: var = ir.GlobalVariable(module, ir.IntType(1), register.get('name')) var.initializer =", "update_output(builder, output, result) elif mnemonic.text == \"STORE\": input_1 = pcode.find(\"input_1\")", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT2FLOAT\": raise Exception(\"Not implemented\") elif", "and no_branch: builder.branch(list(blocks.values())[block_iterator]) def fetch_input_varnode(builder, name): var_type = name.get(\"storage\") var_size", "[build_function(name, module), function] for address in functions: ir_func, function =", "check_shift_inputs(builder, lhs, rhs, target): if lhs.type != target: if lhs.type.is_pointer:", "blocks = build_cfg(function, ir_func) if blocks == {}: return populate_cfg(function,", "builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_2COMP\": val", "= var func_return = ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func", "ir.IntType(64) int1 = ir.IntType(1) void_type = ir.VoidType() function_names = []", "mnemonic.text == \"BRANCH\": value = pcode.find(\"input_0\").text[2:-2] if value in functions:", "raise Exception(\"Not implemented\") elif mnemonic.text == \"CAST\": raise Exception(\"Not implemented\")", "\"INT_SREM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "= fetch_input_varnode(builder, input_0) rhs = fetch_input_varnode(builder, input_1) target = ir.IntType(int(pcode.find(\"output\").get(\"size\"))", "= builder.alloca(ir.IntType(8), stack_size, name=\"stack\") stack_top = builder.gep(stack, [ir.Constant(int64, stack_size -", "1 instr = 0 quiter = False for instruction in", "implemented\") elif mnemonic.text == \"FLOAT_FLOOR\": raise Exception(\"Not implemented\") elif mnemonic.text", "memory[memory_location.get('name')] = var func_return = ir.VoidType() fnty = ir.FunctionType(func_return, [])", "== \"CALLIND\": # target = pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"], []) elif mnemonic.text", "lhs, rhs def int_comparison_check_inputs(builder, lhs, rhs): # For integer comparison", "input_0.text in pointers and input_1.get(\"storage\") == \"constant\": result = builder.gep(lhs,", "if output.text in flags and pcode.find(\"input_0\").get(\"storage\") == \"constant\": source =", "= ir.Function(module, fnty, name) return ir_func def build_cfg(function, ir_func): builders,", "void_type = ir.VoidType() function_names = [] registers, functions, uniques, extracts", "builder.gep(lhs, [ir.Constant(int64, 0)]) if lhs2.type != rhs.type.as_pointer(): lhs2 = builder.bitcast(lhs2,", "rhs, target) output = builder.lshr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "== \"constant\": source = ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text, 0)) else: source =", "elif mnemonic.text == \"BOOL_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.not_(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"call_indirect\")", "False else: # weird jump into some label in another", "output = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "rhs, target) output = builder.mul(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "= pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") if input_1.text == \"0x0\": val", "mnemonic.text == \"INT_MULT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "int1 = ir.IntType(1) void_type = ir.VoidType() function_names = [] registers,", "block builders[address] = ir.IRBuilder(block) return builders, blocks # noinspection DuplicatedCode", "int(memory_location.get('size'))), None) var.linkage = 'internal' memory[memory_location.get('name')] = var func_return =", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"FLOAT_EQUAL\": raise Exception(\"Not", "from llvmlite import ir import xml.etree.ElementTree as et int32 =", "= instruction.find(\"address\").text block = ir_func.append_basic_block(address) blocks[address] = block builders[address] =", "rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.srem(lhs, rhs)", "mnemonic.text == \"PIECE\": raise Exception(\"PIECE operation needs to be tested\")", "pointers: var = ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name')) var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)), None)", "= int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('==', lhs, rhs) update_output(builder,", "# For integer comparison operations. We assume rhs is the", "= builder.sdiv(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SREM\":", "= ir_func.append_basic_block(\"entry\") blocks[\"entry\"] = block builders[\"entry\"] = ir.IRBuilder(block) for instruction", "operation needs to be tested\") elif mnemonic.text == \"SUBPIECE\": output", "[]) ir_func = ir.Function(module, fnty, \"intra_function_branch\") internal_functions[\"intra_function_branch\"] = ir_func func_return", "\"BRANCHIND\": no_branch = False target = fetch_input_varnode(builder, pcode.find(\"input_0\")) if not", "lift(filename): root = et.parse(filename).getroot() module = ir.Module(name=\"lifted\") for register in", "ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, name)", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESS\": lhs = fetch_input_varnode(builder,", "output = builder.div(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "blocks[value] builder.branch(target) no_branch = False else: # weird jump into", "\"TRUNC\": raise Exception(\"Not implemented\") elif mnemonic.text == \"CPOOLREF\": raise Exception(\"Not", "pcodes = instruction.find(\"pcodes\") pc = 0 no_branch = True for", "rhs) result = builder.icmp_unsigned('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "= builder.div(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_REM\":", "[\"RSP\", \"RIP\", \"RBP\", \"EBP\", \"ESP\"] def lift(filename): root = et.parse(filename).getroot()", "rhs) result = builder.icmp_signed('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "output) elif mnemonic.text == \"INT_SREM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SDIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "builder.icmp_unsigned('!=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESS\":", "is None: builder.ret_void() else: raise Exception(\"Return value being passed\") elif", "ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"call_indirect\") internal_functions[\"call_indirect\"] = ir_func", "result = builder.icmp_signed('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "implemented\") elif mnemonic.text == \"CAST\": raise Exception(\"Not implemented\") else: raise", "pcode.find(\"input_1\")) result = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "implemented\") else: raise Exception(\"Not a standard pcode instruction\") block_iterator +=", "output = pcode.find(\"output\") if output.text in flags and pcode.find(\"input_0\").get(\"storage\") ==", "\"INT_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "int_check_inputs(builder, lhs, rhs, target) result = builder.sub(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "mnemonic.text == \"INT_SRIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "instruction in function.find(\"instructions\"): if quiter: break address = instruction.find(\"address\").text if", "fnty, name) return ir_func def build_cfg(function, ir_func): builders, blocks =", "lhs2 = builder.gep(lhs, [ir.Constant(int64, 0)]) if lhs2.type != rhs.type.as_pointer(): lhs2", "fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"bit_extraction\") internal_functions[\"bit_extraction\"]", "= builder.zext(rhs, target) return lhs, rhs def int_comparison_check_inputs(builder, lhs, rhs):", "= builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SBORROW\":", "condition = fetch_input_varnode(builder, pcode.find(\"input_1\")) no_branch = False builder.cbranch(condition, true_target, false_target)", "builder.add(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SUB\": input_0", "populate_cfg(function, builders, blocks) def build_function(name, module): func_return = ir.VoidType() fnty", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_ZEXT\": rhs =", "true_target = blocks[pcode.find(\"input_0\").text[2:-2]] false_target = list(blocks.values())[block_iterator + 1] condition =", "noinspection DuplicatedCode def populate_cfg(function, builders, blocks): builder = builders[\"entry\"] stack_size", "it as a copy, should load the memory address in", "if input_1.text in pointers: rhs = builder.gep(rhs, [ir.Constant(int64, 0)]) result", "implemented\") elif mnemonic.text == \"INT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_MULT\": lhs = fetch_input_varnode(builder,", "elif mnemonic.text == \"PTRSUB\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee) output = builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) *", "stack_size - 8)], name=\"stack_top\") builder.store(stack_top, registers[\"RSP\"]) builder.branch(list(blocks.values())[1]) block_iterator = 1", "fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee) output =", "function_names.append(name) address = function.get('address') functions[address] = [build_function(name, module), function] for", "standard pcode instruction\") block_iterator += 1 instr += 1 if", "int(name.text, 0)) return var elif var_type == \"memory\": return memory[name.text]", "rhs = int_check_inputs(builder, lhs, rhs, target) result = builder.add(lhs, rhs)", "elif mnemonic.text == \"FLOAT_FLOOR\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<=', lhs, rhs)", "Exception(\"Not implemented\") elif mnemonic.text == \"CAST\": raise Exception(\"Not implemented\") else:", "== \"BRANCHIND\": no_branch = False target = fetch_input_varnode(builder, pcode.find(\"input_0\")) if", "fetch_output_varnode(name): var_type = name.get(\"storage\") if var_type == \"register\": return registers[name.text]", "rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<=', lhs, rhs)", "= int_check_inputs(builder, lhs, rhs, target) output = builder.or_(lhs, rhs) update_output(builder,", "= [] registers, functions, uniques, extracts = {}, {}, {},", "in pointers: rhs = builder.gep(rhs, [ir.Constant(int64, 0)]) result = builder.load(rhs)", "\"INT_SLESS_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "mnemonic = pcode.find(\"name\") if mnemonic.text == \"COPY\": output = pcode.find(\"output\")", "# might be solved with callbr instruction? builder.call(internal_functions[\"intra_function_branch\"], []) elif", "rhs = builder.zext(rhs, target) return lhs, rhs def int_comparison_check_inputs(builder, lhs,", "= pcode.find(\"input_1\") # target input_2 = pcode.find(\"input_2\") # source rhs", "lhs2 == rhs: rhs = lhs if rhs.type != target", "lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target =", "result = builder.icmp_unsigned('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"FLOAT_EQUAL\": raise", "result) elif mnemonic.text == \"INT_NOTEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_FLOOR\": raise Exception(\"Not implemented\")", "8) if input_0.text in pointers and input_1.get(\"storage\") == \"constant\": result", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_MULT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "pcode.find(\"output\"), output) elif mnemonic.text == \"BOOL_NEGATE\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "not in list(uniques.keys()): raise Exception(\"Temporary variable referenced before defined\") return", "\"FLOAT_MULT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_DIV\": raise Exception(\"Not", "== {}: return populate_cfg(function, builders, blocks) def build_function(name, module): func_return", "pcode.find(\"output\"), result) elif mnemonic.text == \"FLOAT_EQUAL\": raise Exception(\"Not implemented\") elif", "raise Exception(\"Temporary variable referenced before defined\") return uniques[name.text] elif var_type", "address in builders: builder = builders[address] pcodes = instruction.find(\"pcodes\") pc", "== \"FLOAT_LESSEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ADD\": raise", "register.get('name')) var.initializer = ir.Constant(ir.IntType(1), None) var.linkage = 'internal' registers[register.get('name')] =", "= ir.Function(module, fnty, \"call_indirect\") internal_functions[\"call_indirect\"] = ir_func func_return = ir.VoidType()", "and input_1.get(\"storage\") == \"constant\": result = builder.gep(lhs, [ir.Constant(int64, -int(input_1.text, 16))])", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS\": lhs =", "rhs) result = builder.uadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1) update_output(builder,", "fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.or_(lhs, rhs)", "Exception(\"Not implemented\") elif mnemonic.text == \"MULTIEQUAL\": raise Exception(\"Not implemented\") elif", "if lhs.type != target: if lhs.type.is_pointer: lhs2 = lhs lhs", "lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NOTEQUAL\": lhs", "rhs, target) output = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "builder.lshr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SRIGHT\": lhs", "builder.call(internal_functions['bit_extraction'], []) elif mnemonic.text == \"INT_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SRIGHT\": lhs =", "builder.icmp_unsigned('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS\":", "== \"INT_SCARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "if block_iterator < len(blocks) and no_branch: builder.branch(list(blocks.values())[block_iterator]) def fetch_input_varnode(builder, name):", "in flags: var = ir.GlobalVariable(module, ir.IntType(1), register.get('name')) var.initializer = ir.Constant(ir.IntType(1),", "\"INT_SLESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "\"FLOAT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"TRUNC\": raise Exception(\"Not", "builder.srem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"BOOL_NEGATE\": lhs", "!= target: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) else: rhs", "fetch_input_varnode(builder, input_0) result = builder.trunc(val, ir.IntType(int(output.get(\"size\")) * 8)) update_output(builder, output,", "result = builder.not_(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NEGATE\":", "be tested\") elif mnemonic.text == \"SUBPIECE\": output = pcode.find(\"output\") input_0", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "ir.IntType(8 * int(register.get('size'))), register.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(register.get('size'))), None)", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_CARRY\": lhs =", "int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('!=', lhs, rhs) update_output(builder, pcode.find(\"output\"),", "== \"FLOAT_SUB\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_MULT\": raise", "ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, name) return ir_func def", "builders, blocks) def build_function(name, module): func_return = ir.VoidType() fnty =", "== \"FLOAT_CEIL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_FLOOR\": raise", "implemented\") elif mnemonic.text == \"NEW\": raise Exception(\"Not implemented\") elif mnemonic.text", "int_check_inputs(builder, lhs, rhs, target) result = builder.add(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"intra_function_branch\") internal_functions[\"intra_function_branch\"]", "mnemonic.text == \"INT_NOTEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "!= target: if lhs.type.is_pointer: lhs2 = lhs lhs = builder.ptrtoint(lhs,", "builder.call(internal_functions[\"call_indirect\"], []) elif mnemonic.text == \"USERDEFINED\": raise Exception(\"Not implemented\") elif", "in functions: target = functions[value][0] builder.call(target, []) elif value in", "= builder.gep(lhs, [ir.Constant(int64, -int(input_1.text, 16))]) else: lhs, rhs = int_check_inputs(builder,", "= ir.IRBuilder(block) for instruction in instructions: address = instruction.find(\"address\").text block", "pcode.find(\"input_1\") # target input_2 = pcode.find(\"input_2\") # source rhs =", "input_1.text == \"0x0\": val = fetch_input_varnode(builder, input_0) result = builder.trunc(val,", "= pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"], []) elif mnemonic.text == \"USERDEFINED\": raise Exception(\"Not", "output, result) elif mnemonic.text == \"STORE\": input_1 = pcode.find(\"input_1\") #", "\"INT_ZEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs,", "function in root.findall('function'): name = function.get('name') x = 1 while", "blocks[\"entry\"] = block builders[\"entry\"] = ir.IRBuilder(block) for instruction in instructions:", "implemented\") elif mnemonic.text == \"FLOAT_ADD\": raise Exception(\"Not implemented\") elif mnemonic.text", "input_0) rhs = fetch_input_varnode(builder, input_1) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)", "target) output = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "update_output(builder, output, rhs) else: if input_1.text in pointers: rhs =", "This is incorrect. This is treating it as a copy,", "integer comparison operations. We assume rhs is the correct type.", "in function_names: name = name + \"_\" + str(x) x", "and output.get(\"storage\") == \"unique\": # This is incorrect. This is", "functions: target = functions[value][0] builder.call(target, []) elif value in blocks:", "\"INT_SCARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "= int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<', lhs, rhs) update_output(builder,", "== \"memory\": return memory[name.text] def update_output(builder, name, output): var_type =", "fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder,", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ADD\": raise Exception(\"Not implemented\")", "= ir_func.append_basic_block(address) blocks[address] = block builders[address] = ir.IRBuilder(block) return builders,", "result) elif mnemonic.text == \"FLOAT_EQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text", "pointers: rhs = builder.gep(rhs, [ir.Constant(int64, 0)]) result = builder.load(rhs) update_output(builder,", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_AND\": lhs = fetch_input_varnode(builder,", "instruction\") block_iterator += 1 instr += 1 if block_iterator <", "mnemonic.text == \"FLOAT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"TRUNC\":", "elif mnemonic.text == \"INT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "ir_func func_return = ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func =", "fnty, \"call_indirect\") internal_functions[\"call_indirect\"] = ir_func func_return = ir.VoidType() fnty =", "= True for pcode in pcodes: pc += 1 mnemonic", "== \"BRANCH\": value = pcode.find(\"input_0\").text[2:-2] if value in functions: target", "if var_type == \"register\": reg = registers[name.text] if reg.type !=", "\"MULTIEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"INDIRECT\": raise Exception(\"Not", "elif mnemonic.text == \"FLOAT_NEG\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "{}, {}, {}, {} internal_functions = {} memory = {}", "rhs, target) output = builder.div(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "int_check_inputs(builder, lhs, rhs, target) output = builder.sdiv(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "elif mnemonic.text == \"INT_SEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer:", "and lhs != rhs: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target)", "x = 1 while name in function_names: name = name", "= int(name.get(\"size\")) * 8 if var_type == \"register\": return builder.load(registers[name.text])", "= ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text, 0)) else: source = fetch_input_varnode(builder, pcode.find(\"input_0\")) update_output(builder,", "== \"INT_REM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "result) elif mnemonic.text == \"BOOL_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "= build_cfg(function, ir_func) if blocks == {}: return populate_cfg(function, builders,", "lhs, rhs, target) output = builder.lshr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "x += 1 function_names.append(name) address = function.get('address') functions[address] = [build_function(name,", "elif mnemonic.text == \"INT_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_LEFT\": lhs", "mnemonic.text == \"BOOL_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "builder.call(internal_functions[\"intra_function_branch\"], []) elif mnemonic.text == \"CBRANCH\": true_target = blocks[pcode.find(\"input_0\").text[2:-2]] false_target", "quiter = False for instruction in function.find(\"instructions\"): if quiter: break", "elif mnemonic.text == \"INT_LESSEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "builder.icmp_signed('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESSEQUAL\":", "builders, blocks = {}, {} instructions = function.find(\"instructions\") if instructions:", "== \"BOOL_NEGATE\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(lhs) update_output(builder,", "= pcode.find(\"input_1\") output = pcode.find(\"output\") rhs = fetch_input_varnode(builder, input_1) if", "false_target) elif mnemonic.text == \"BRANCHIND\": no_branch = False target =", "builder.zext(lhs, target) if rhs.type != target: if rhs.type.is_pointer: rhs =", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_AND\": lhs = fetch_input_varnode(builder,", "input_1) if input_1.get(\"storage\") == \"unique\" and output.get(\"storage\") == \"unique\": #", "== \"USERDEFINED\": raise Exception(\"Not implemented\") elif mnemonic.text == \"RETURN\": input_1", "pointers = [\"RSP\", \"RIP\", \"RBP\", \"EBP\", \"ESP\"] def lift(filename): root", "the input 1 update_output(builder, output, rhs) else: if input_1.text in", "rhs = check_shift_inputs(builder, lhs, rhs, target) output = builder.shl(lhs, rhs)", "if var_type == \"register\": return builder.load(registers[name.text]) elif var_type == \"unique\":", "rhs = int_check_inputs(builder, lhs, rhs, target) result = builder.sub(lhs, rhs)", "lhs, rhs): # For integer comparison operations. We assume rhs", "name.text not in uniques: uniques[name.text] = None return uniques[name.text] def", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_AND\": lhs =", "pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"], []) elif mnemonic.text == \"USERDEFINED\": raise Exception(\"Not implemented\")", "= instruction.find(\"address\").text if address in builders: builder = builders[address] pcodes", "into some label in another function # might be solved", "rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "= builder.ptrtoint(rhs, target) return lhs, rhs def check_shift_inputs(builder, lhs, rhs,", "result = builder.trunc(val, ir.IntType(int(output.get(\"size\")) * 8)) update_output(builder, output, result) else:", "var_type == \"register\": return registers[name.text] elif var_type == \"unique\": if", "input_1.get(\"storage\") == \"constant\": result = builder.gep(lhs, [ir.Constant(int64, int(input_1.text, 16))]) else:", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NEGATE\": val = fetch_input_varnode(builder,", "lhs, rhs, target) output = builder.shl(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "\"FLOAT_SUB\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_MULT\": raise Exception(\"Not", "fetch_input_varnode(builder, name): var_type = name.get(\"storage\") var_size = int(name.get(\"size\")) * 8", "# target = pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"], []) elif mnemonic.text == \"USERDEFINED\":", "lhs = fetch_output_varnode(input_1) lhs2 = builder.gep(lhs, [ir.Constant(int64, 0)]) if lhs2.type", "is treating it as a copy, should load the memory", "builder.ashr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_MULT\": lhs", "= lhs lhs = builder.ptrtoint(lhs, target) if lhs2 == rhs:", "elif mnemonic.text == \"FLOAT_DIV\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "mnemonic.text == \"BOOL_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "lhs if rhs.type != target and lhs != rhs: if", "extracts = {}, {}, {}, {} internal_functions = {} memory", "llvmlite import ir import xml.etree.ElementTree as et int32 = ir.IntType(32)", "= function.get('address') functions[address] = [build_function(name, module), function] for address in", "\"unique\" and output.get(\"storage\") == \"unique\": # This is incorrect. This", "== \"INT_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "name = function.get('name') x = 1 while name in function_names:", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_XOR\": lhs = fetch_input_varnode(builder,", "reg = builder.bitcast(reg, output.type.as_pointer()) builder.store(output, reg) elif var_type == \"unique\":", "flags = [\"ZF\", \"CF\", \"OF\", \"SF\"] pointers = [\"RSP\", \"RIP\",", "= instruction.find(\"pcodes\") pc = 0 no_branch = True for pcode", "for pcode in pcodes: pc += 1 mnemonic = pcode.find(\"name\")", "builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_OR\": lhs", "[ir.Constant(int64, -int(input_1.text, 16))]) else: lhs, rhs = int_check_inputs(builder, lhs, rhs,", "block = ir_func.append_basic_block(address) blocks[address] = block builders[address] = ir.IRBuilder(block) return", "implemented\") elif mnemonic.text == \"FLOAT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text", "= fetch_input_varnode(builder, input_2) lhs = fetch_output_varnode(input_1) lhs2 = builder.gep(lhs, [ir.Constant(int64,", "name): var_type = name.get(\"storage\") var_size = int(name.get(\"size\")) * 8 if", "block_iterator < len(blocks) and no_branch: builder.branch(list(blocks.values())[block_iterator]) def fetch_input_varnode(builder, name): var_type", "def populate_cfg(function, builders, blocks): builder = builders[\"entry\"] stack_size = 10", "== \"INT_SLESS_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "= ir.Constant(ir.PointerType(ir.IntType(8)), None) var.linkage = 'internal' registers[register.get('name')] = var else:", "mnemonic.text == \"FLOAT_CEIL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_FLOOR\":", "\"OF\", \"SF\"] pointers = [\"RSP\", \"RIP\", \"RBP\", \"EBP\", \"ESP\"] def", "input_2 = pcode.find(\"input_2\") # source rhs = fetch_input_varnode(builder, input_2) lhs", "[]) ir_func = ir.Function(module, fnty, name) return ir_func def build_cfg(function,", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) if not target.type.is_pointer: target = builder.inttoptr(target, target.type.as_pointer())", "lhs, rhs, target) output = builder.div(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "build_function(name, module): func_return = ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func", "ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs = int_check_inputs(builder, lhs, rhs, target)", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_RIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('!=', lhs,", "quiter: break address = instruction.find(\"address\").text if address in builders: builder", "\"FLOAT_SQRT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_CEIL\": raise Exception(\"Not", "load the memory address in the input 1 update_output(builder, output,", "= int_check_inputs(builder, lhs, rhs, target) output = builder.sdiv(lhs, rhs) update_output(builder,", "mnemonic.text == \"TRUNC\": raise Exception(\"Not implemented\") elif mnemonic.text == \"CPOOLREF\":", "elif mnemonic.text == \"FLOAT_ABS\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "elif mnemonic.text == \"INT_SUB\": input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\")", "This is treating it as a copy, should load the", "implemented\") elif mnemonic.text == \"FLOAT_NAN\": raise Exception(\"Not implemented\") elif mnemonic.text", "DuplicatedCode def populate_cfg(function, builders, blocks): builder = builders[\"entry\"] stack_size =", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_LEFT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "False target = fetch_input_varnode(builder, pcode.find(\"input_0\")) if not target.type.is_pointer: target =", "result = builder.icmp_signed('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs = fetch_input_varnode(builder, input_0)", "int_check_inputs(builder, lhs, rhs, target): if lhs.type != target: if lhs.type.is_pointer:", "{}, {}, {} internal_functions = {} memory = {} flags", "= functions[address] populate_func(ir_func, function) return module def populate_func(ir_func, function): builders,", "mnemonic.text == \"PTRSUB\": raise Exception(\"Not implemented\") elif mnemonic.text == \"CAST\":", "\"0x0\": val = fetch_input_varnode(builder, input_0) result = builder.trunc(val, ir.IntType(int(output.get(\"size\")) *", "= False builder.cbranch(condition, true_target, false_target) elif mnemonic.text == \"BRANCHIND\": no_branch", "pcodes: pc += 1 mnemonic = pcode.find(\"name\") if mnemonic.text ==", "output = builder.srem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "* 8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SEXT\": rhs", "ir_func def build_cfg(function, ir_func): builders, blocks = {}, {} instructions", "== \"CBRANCH\": true_target = blocks[pcode.find(\"input_0\").text[2:-2]] false_target = list(blocks.values())[block_iterator + 1]", "for instruction in instructions: address = instruction.find(\"address\").text block = ir_func.append_basic_block(address)", "mnemonic.text == \"FLOAT_DIV\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NEG\":", "rhs def check_shift_inputs(builder, lhs, rhs, target): if lhs.type != target:", "\"CPOOLREF\": raise Exception(\"Not implemented\") elif mnemonic.text == \"NEW\": raise Exception(\"Not", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_DIV\": raise Exception(\"Not implemented\") elif", "Exception(\"PIECE operation needs to be tested\") elif mnemonic.text == \"SUBPIECE\":", "\"unique\": uniques[name.text] = output def fetch_output_varnode(name): var_type = name.get(\"storage\") if", "\"BOOL_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result", "= builder.ashr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_MULT\":", "if value in functions: target = functions[value][0] builder.call(target, []) elif", "var_type == \"unique\": if name.text not in uniques: uniques[name.text] =", "output) elif mnemonic.text == \"INT_REM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('==', lhs, rhs)", "target) result = builder.add(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "lhs lhs = builder.ptrtoint(lhs, target) if lhs2 == rhs: rhs", "ir.IntType(1) void_type = ir.VoidType() function_names = [] registers, functions, uniques,", "\"PIECE\": raise Exception(\"PIECE operation needs to be tested\") elif mnemonic.text", "output): var_type = name.get(\"storage\") if var_type == \"register\": reg =", "* 1024 * 1024 stack = builder.alloca(ir.IntType(8), stack_size, name=\"stack\") stack_top", "= builder.mul(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_DIV\":", "implemented\") elif mnemonic.text == \"FLOAT_SQRT\": raise Exception(\"Not implemented\") elif mnemonic.text", "elif var_type == \"constant\": var = ir.Constant(ir.IntType(var_size), int(name.text, 0)) return", "= pcode.find(\"name\") if mnemonic.text == \"COPY\": output = pcode.find(\"output\") if", "mnemonic.text == \"USERDEFINED\": raise Exception(\"Not implemented\") elif mnemonic.text == \"RETURN\":", "registers[name.text] if reg.type != output.type.as_pointer(): reg = builder.bitcast(reg, output.type.as_pointer()) builder.store(output,", "builder.call(target, []) elif mnemonic.text == \"CALLIND\": # target = pcode.find(\"input_0\").text[2:-2]", "rhs, target) result = builder.sub(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "uniques, extracts = {}, {}, {}, {} internal_functions = {}", "fetch_input_varnode(builder, pcode.find(\"input_1\")) no_branch = False builder.cbranch(condition, true_target, false_target) elif mnemonic.text", "output = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "elif mnemonic.text == \"INT_DIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "Exception(\"Not implemented\") elif mnemonic.text == \"RETURN\": input_1 = pcode.find(\"input_1\") no_branch", "lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs, rhs", "builder = builders[address] pcodes = instruction.find(\"pcodes\") pc = 0 no_branch", "elif mnemonic.text == \"CALL\": target = functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target, []) elif", "fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "1024 * 1024 stack = builder.alloca(ir.IntType(8), stack_size, name=\"stack\") stack_top =", "if input_0.text in pointers and input_1.get(\"storage\") == \"constant\": result =", "ir.VoidType() function_names = [] registers, functions, uniques, extracts = {},", "rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "= int_check_inputs(builder, lhs, rhs, target) output = builder.and_(lhs, rhs) update_output(builder,", "var_type = name.get(\"storage\") if var_type == \"register\": reg = registers[name.text]", "result = builder.load(rhs) update_output(builder, output, result) elif mnemonic.text == \"STORE\":", "root.findall('function'): name = function.get('name') x = 1 while name in", "= builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_LEFT\":", "= 'internal' registers[register.get('name')] = var elif register.get('name') in pointers: var", "Exception(\"Not implemented\") elif mnemonic.text == \"TRUNC\": raise Exception(\"Not implemented\") elif", "not in uniques: uniques[name.text] = None return uniques[name.text] def int_check_inputs(builder,", "= 1 while name in function_names: name = name +", "the correct type. if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, rhs.type) return", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.or_(lhs,", "pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<=',", "lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('==', lhs,", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.not_(val) update_output(builder, pcode.find(\"output\"), result) elif", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NAN\": raise Exception(\"Not implemented\")", "name.get(\"storage\") if var_type == \"register\": return registers[name.text] elif var_type ==", "= ir.Constant(ir.IntType(8 * int(memory_location.get('size'))), None) var.linkage = 'internal' memory[memory_location.get('name')] =", "implemented\") elif mnemonic.text == \"PTRSUB\": raise Exception(\"Not implemented\") elif mnemonic.text", "lhs.type != target: if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, target) else:", "= builder.trunc(val, ir.IntType(int(output.get(\"size\")) * 8)) update_output(builder, output, result) else: builder.call(internal_functions['bit_extraction'],", "\"INT_SRIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "+= 1 function_names.append(name) address = function.get('address') functions[address] = [build_function(name, module),", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_OR\": lhs =", "= ir.GlobalVariable(module, ir.IntType(8 * int(register.get('size'))), register.get('name')) var.initializer = ir.Constant(ir.IntType(8 *", "elif mnemonic.text == \"BOOL_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "= list(blocks.values())[block_iterator + 1] condition = fetch_input_varnode(builder, pcode.find(\"input_1\")) no_branch =", "is incorrect. This is treating it as a copy, should", "== \"INT_SLESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "mnemonic.text == \"INT_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "elif mnemonic.text == \"FLOAT_MULT\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "= 10 * 1024 * 1024 stack = builder.alloca(ir.IntType(8), stack_size,", "rhs: rhs = lhs if rhs.type != target and lhs", "lhs, rhs = check_shift_inputs(builder, lhs, rhs, target) output = builder.shl(lhs,", "\"BOOL_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result", "mnemonic.text == \"INT_2COMP\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.not_(val)", "raise Exception(\"Not implemented\") elif mnemonic.text == \"PTRSUB\": raise Exception(\"Not implemented\")", "8 if var_type == \"register\": return builder.load(registers[name.text]) elif var_type ==", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "function = functions[address] populate_func(ir_func, function) return module def populate_func(ir_func, function):", "if input_1.get(\"storage\") == \"unique\" and output.get(\"storage\") == \"unique\": # This", "implemented\") elif mnemonic.text == \"FLOAT_CEIL\": raise Exception(\"Not implemented\") elif mnemonic.text", "as et int32 = ir.IntType(32) int64 = ir.IntType(64) int1 =", "lhs2) elif mnemonic.text == \"BRANCH\": value = pcode.find(\"input_0\").text[2:-2] if value", "assume rhs is the correct type. if lhs.type.is_pointer: lhs =", "name) return ir_func def build_cfg(function, ir_func): builders, blocks = {},", "function] for address in functions: ir_func, function = functions[address] populate_func(ir_func,", "lhs, rhs) result = builder.uadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1)", "* 8) lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output", "= check_shift_inputs(builder, lhs, rhs, target) output = builder.shl(lhs, rhs) update_output(builder,", "1 while name in function_names: name = name + \"_\"", "function): builders, blocks = build_cfg(function, ir_func) if blocks == {}:", "= ir.GlobalVariable(module, ir.IntType(1), register.get('name')) var.initializer = ir.Constant(ir.IntType(1), None) var.linkage =", "== \"FLOAT_NAN\": raise Exception(\"Not implemented\") elif mnemonic.text == \"INT2FLOAT\": raise", "target) result = builder.sub(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESSEQUAL\": raise Exception(\"Not implemented\") elif", "\"unique\": # This is incorrect. This is treating it as", "rhs = builder.ptrtoint(rhs, target) return lhs, rhs def check_shift_inputs(builder, lhs,", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "== \"NEW\": raise Exception(\"Not implemented\") elif mnemonic.text == \"MULTIEQUAL\": raise", "lhs, rhs def check_shift_inputs(builder, lhs, rhs, target): if lhs.type !=", "[]) elif mnemonic.text == \"USERDEFINED\": raise Exception(\"Not implemented\") elif mnemonic.text", "Exception(\"Not implemented\") elif mnemonic.text == \"INDIRECT\": raise Exception(\"Not implemented\") elif", "= builder.ptrtoint(rhs, rhs.type.pointee) output = builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder,", "mnemonic.text == \"BOOL_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "implemented\") elif mnemonic.text == \"FLOAT_ABS\": raise Exception(\"Not implemented\") elif mnemonic.text", "target: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) else: rhs =", "in function.find(\"instructions\"): if quiter: break address = instruction.find(\"address\").text if address", "result) elif mnemonic.text == \"INT_LESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "var_type == \"constant\": var = ir.Constant(ir.IntType(var_size), int(name.text, 0)) return var", "elif mnemonic.text == \"INDIRECT\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "elif var_type == \"unique\": if name.text not in list(uniques.keys()): raise", "var_type == \"register\": reg = registers[name.text] if reg.type != output.type.as_pointer():", "int_check_inputs(builder, lhs, rhs, target) output = builder.div(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "target = builder.inttoptr(target, target.type.as_pointer()) builder.branch_indirect(target) elif mnemonic.text == \"CALL\": target", "mnemonic.text == \"PTRADD\": raise Exception(\"Not implemented\") elif mnemonic.text == \"PTRSUB\":", "\"CAST\": raise Exception(\"Not implemented\") else: raise Exception(\"Not a standard pcode", "rhs.type.pointee) output = builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output)", "target: if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, target) else: lhs =", "pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<',", "result) elif mnemonic.text == \"INT_ZEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if", "= builder.gep(lhs, [ir.Constant(int64, int(input_1.text, 16))]) else: lhs, rhs = int_check_inputs(builder,", "else: raise Exception(\"Return value being passed\") elif mnemonic.text == \"PIECE\":", "input_1.get(\"storage\") == \"constant\": result = builder.gep(lhs, [ir.Constant(int64, -int(input_1.text, 16))]) else:", "\"INDIRECT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"PTRADD\": raise Exception(\"Not", "callbr instruction? builder.call(internal_functions[\"intra_function_branch\"], []) elif mnemonic.text == \"CBRANCH\": true_target =", "target = functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target, []) elif mnemonic.text == \"CALLIND\": #", "elif mnemonic.text == \"INT_RIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "block_iterator = 1 instr = 0 quiter = False for", "lhs.type != target: if lhs.type.is_pointer: lhs2 = lhs lhs =", "== \"BOOL_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "rhs, target) output = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<', lhs, rhs) update_output(builder, pcode.find(\"output\"),", "no_branch = True for pcode in pcodes: pc += 1", "= builder.srem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"BOOL_NEGATE\":", "[ir.Constant(int64, 0)]) if lhs2.type != rhs.type.as_pointer(): lhs2 = builder.bitcast(lhs2, rhs.type.as_pointer())", "raise Exception(\"Return value being passed\") elif mnemonic.text == \"PIECE\": raise", "int_check_inputs(builder, lhs, rhs, target) output = builder.mul(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_AND\": lhs =", "check_shift_inputs(builder, lhs, rhs, target) output = builder.shl(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "= builder.zext(lhs, target) if rhs.type != target: if rhs.type.is_pointer: rhs", "= None return uniques[name.text] def int_check_inputs(builder, lhs, rhs, target): if", "elif mnemonic.text == \"BOOL_NEGATE\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) result =", "def int_check_inputs(builder, lhs, rhs, target): if lhs.type != target: if", "ir_func for function in root.findall('function'): name = function.get('name') x =", "== rhs: rhs = lhs if rhs.type != target and", "raise Exception(\"Not implemented\") elif mnemonic.text == \"RETURN\": input_1 = pcode.find(\"input_1\")", "if lhs2 == rhs: rhs = lhs if rhs.type !=", "functions[address] = [build_function(name, module), function] for address in functions: ir_func,", "internal_functions = {} memory = {} flags = [\"ZF\", \"CF\",", "builder.zext(rhs, target) return lhs, rhs def int_comparison_check_inputs(builder, lhs, rhs): #", "[]) elif mnemonic.text == \"INT_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee) output = builder.zext(rhs,", "\"register\": return registers[name.text] elif var_type == \"unique\": if name.text not", "var.linkage = 'internal' registers[register.get('name')] = var elif register.get('name') in pointers:", "8)], name=\"stack_top\") builder.store(stack_top, registers[\"RSP\"]) builder.branch(list(blocks.values())[1]) block_iterator = 1 instr =", "== \"PTRADD\": raise Exception(\"Not implemented\") elif mnemonic.text == \"PTRSUB\": raise", "pcode.find(\"input_0\")) result = builder.neg(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee) output = builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) *", "= ir.IntType(32) int64 = ir.IntType(64) int1 = ir.IntType(1) void_type =", "needs to be tested\") elif mnemonic.text == \"SUBPIECE\": output =", "ir_func): builders, blocks = {}, {} instructions = function.find(\"instructions\") if", "lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<=', lhs,", "mnemonic.text == \"FLOAT_FLOOR\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ROUND\":", "value = pcode.find(\"input_0\").text[2:-2] if value in functions: target = functions[value][0]", "= ir.IntType(1) void_type = ir.VoidType() function_names = [] registers, functions,", "pcode.find(\"input_0\").text[2:-2] if value in functions: target = functions[value][0] builder.call(target, [])", "False builder.cbranch(condition, true_target, false_target) elif mnemonic.text == \"BRANCHIND\": no_branch =", "pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('!=',", "implemented\") elif mnemonic.text == \"MULTIEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text", "raise Exception(\"Not implemented\") elif mnemonic.text == \"NEW\": raise Exception(\"Not implemented\")", "= pcode.find(\"input_1\") if input_1.text == \"0x0\": val = fetch_input_varnode(builder, input_0)", "* int(register.get('size'))), None) var.linkage = 'internal' registers[register.get('name')] = var for", "== \"FLOAT_MULT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_DIV\": raise", "== \"INT_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "rhs) result = builder.icmp_unsigned('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "rhs) result = builder.icmp_signed('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "= builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_AND\":", "ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"bit_extraction\")", "ir.Constant(ir.IntType(8 * int(memory_location.get('size'))), None) var.linkage = 'internal' memory[memory_location.get('name')] = var", "None return uniques[name.text] def int_check_inputs(builder, lhs, rhs, target): if lhs.type", "rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.div(lhs, rhs)", "== \"register\": return builder.load(registers[name.text]) elif var_type == \"unique\": if name.text", "mnemonic.text == \"STORE\": input_1 = pcode.find(\"input_1\") # target input_2 =", "pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)", "blocks = {}, {} instructions = function.find(\"instructions\") if instructions: block", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SREM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "ir.IRBuilder(block) for instruction in instructions: address = instruction.find(\"address\").text block =", "pcode.find(\"output\") if output.text in flags and pcode.find(\"input_0\").get(\"storage\") == \"constant\": source", "return uniques[name.text] def int_check_inputs(builder, lhs, rhs, target): if lhs.type !=", "elif mnemonic.text == \"INT_REM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "address = function.get('address') functions[address] = [build_function(name, module), function] for address", "output, result) else: builder.call(internal_functions['bit_extraction'], []) elif mnemonic.text == \"INT_EQUAL\": lhs", "mnemonic.text == \"CAST\": raise Exception(\"Not implemented\") else: raise Exception(\"Not a", "elif mnemonic.text == \"INT_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "internal_functions[\"call_indirect\"] = ir_func func_return = ir.VoidType() fnty = ir.FunctionType(func_return, [])", "\"INT_SUB\": input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs = fetch_input_varnode(builder,", "input 1 update_output(builder, output, rhs) else: if input_1.text in pointers:", "fetch_output_varnode(input_1) lhs2 = builder.gep(lhs, [ir.Constant(int64, 0)]) if lhs2.type != rhs.type.as_pointer():", "== \"FLOAT_DIV\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NEG\": raise", "var_size = int(name.get(\"size\")) * 8 if var_type == \"register\": return", "output) elif mnemonic.text == \"INT_RIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SUB\": input_0 = pcode.find(\"input_0\")", "rhs = builder.ptrtoint(rhs, target) else: rhs = builder.zext(rhs, target) return", "else: # weird jump into some label in another function", "target.type.is_pointer: target = builder.inttoptr(target, target.type.as_pointer()) builder.branch_indirect(target) elif mnemonic.text == \"CALL\":", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SEXT\": rhs = fetch_input_varnode(builder,", "ir.Constant(ir.IntType(8 * int(register.get('size'))), None) var.linkage = 'internal' registers[register.get('name')] = var", "registers[name.text] elif var_type == \"unique\": if name.text not in uniques:", "builder.ptrtoint(lhs, target) if lhs2 == rhs: rhs = lhs if", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SREM\": lhs = fetch_input_varnode(builder,", "registers[register.get('name')] = var elif register.get('name') in pointers: var = ir.GlobalVariable(module,", "= ir.GlobalVariable(module, ir.IntType(8 * int(memory_location.get('size'))), memory_location.get('name')) var.initializer = ir.Constant(ir.IntType(8 *", "pcode.find(\"input_1\")) result = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "= builder.ptrtoint(lhs, target) if lhs2 == rhs: rhs = lhs", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SRIGHT\": lhs = fetch_input_varnode(builder,", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SUB\": input_0 =", "lhs, rhs, target) output = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "== \"FLOAT_SQRT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_CEIL\": raise", "\"INT_LEFT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "* 8) lhs, rhs = check_shift_inputs(builder, lhs, rhs, target) output", "ir_func = ir.Function(module, fnty, name) return ir_func def build_cfg(function, ir_func):", "input_1) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) if input_0.text in pointers", "lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, target) else: lhs = builder.zext(lhs, target)", "rhs = check_shift_inputs(builder, lhs, rhs, target) output = builder.lshr(lhs, rhs)", "name.text not in list(uniques.keys()): raise Exception(\"Temporary variable referenced before defined\")", "fetch_input_varnode(builder, pcode.find(\"input_0\")) if not target.type.is_pointer: target = builder.inttoptr(target, target.type.as_pointer()) builder.branch_indirect(target)", "fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) *", "register.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(register.get('size'))), None) var.linkage = 'internal'", "= {} memory = {} flags = [\"ZF\", \"CF\", \"OF\",", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESSEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SEXT\": rhs =", "= pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs = fetch_input_varnode(builder, input_0) rhs", "mnemonic.text == \"CPOOLREF\": raise Exception(\"Not implemented\") elif mnemonic.text == \"NEW\":", "lhs = builder.ptrtoint(lhs, target) if lhs2 == rhs: rhs =", "source) elif mnemonic.text == \"LOAD\": input_1 = pcode.find(\"input_1\") output =", "< len(blocks) and no_branch: builder.branch(list(blocks.values())[block_iterator]) def fetch_input_varnode(builder, name): var_type =", "= 0 quiter = False for instruction in function.find(\"instructions\"): if", "elif mnemonic.text == \"FLOAT_ROUND\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "= var for memory_location in root.find('memory').findall('memory'): var = ir.GlobalVariable(module, ir.IntType(8", "== \"FLOAT_FLOOR\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ROUND\": raise", "target) output = builder.srem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "mnemonic.text == \"INT_SUB\": input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs", "== \"FLOAT_NEG\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_ABS\": raise", "builder.div(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_REM\": lhs", "output.get(\"storage\") == \"unique\": # This is incorrect. This is treating", "builder.load(rhs) update_output(builder, output, result) elif mnemonic.text == \"STORE\": input_1 =", "elif mnemonic.text == \"INT_SLESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "target) return lhs, rhs def check_shift_inputs(builder, lhs, rhs, target): if", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_ADD\": input_0 = pcode.find(\"input_0\") input_1", "= 'internal' registers[register.get('name')] = var else: var = ir.GlobalVariable(module, ir.IntType(8", "target: if lhs.type.is_pointer: lhs2 = lhs lhs = builder.ptrtoint(lhs, target)", "builder.neg(lhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_XOR\": lhs =", "= ir_func func_return = ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func", "a standard pcode instruction\") block_iterator += 1 instr += 1", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESSEQUAL\": lhs =", "pcode.find(\"input_1\") no_branch = False if input_1 is None: builder.ret_void() else:", "= builder.icmp_unsigned('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "mnemonic.text == \"FLOAT_EQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NOTEQUAL\":", "\"SF\"] pointers = [\"RSP\", \"RIP\", \"RBP\", \"EBP\", \"ESP\"] def lift(filename):", "1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SCARRY\": lhs =", "== \"INT_ZEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs =", "rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.mul(lhs, rhs)", "if input_1.text == \"0x0\": val = fetch_input_varnode(builder, input_0) result =", "root.find('globals').findall('register'): if register.get('name') in flags: var = ir.GlobalVariable(module, ir.IntType(1), register.get('name'))", "== \"COPY\": output = pcode.find(\"output\") if output.text in flags and", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_DIV\": lhs =", "output = builder.zext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output) elif", "pcode.find(\"input_2\") # source rhs = fetch_input_varnode(builder, input_2) lhs = fetch_output_varnode(input_1)", "var.initializer = ir.Constant(ir.IntType(8 * int(register.get('size'))), None) var.linkage = 'internal' registers[register.get('name')]", "result = builder.icmp_unsigned('==', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "int(input_1.text, 16))]) else: lhs, rhs = int_check_inputs(builder, lhs, rhs, target)", "lhs, rhs, target) result = builder.sub(lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_signed('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"),", "as a copy, should load the memory address in the", "builder.branch(target) no_branch = False else: # weird jump into some", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) update_output(builder, pcode.find(\"output\"), source) elif mnemonic.text == \"LOAD\":", "mnemonic.text == \"INT_ADD\": input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs", "rhs = fetch_input_varnode(builder, input_1) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) if", "var.initializer = ir.Constant(ir.IntType(8 * int(memory_location.get('size'))), None) var.linkage = 'internal' memory[memory_location.get('name')]", "in pcodes: pc += 1 mnemonic = pcode.find(\"name\") if mnemonic.text", "val = fetch_input_varnode(builder, input_0) result = builder.trunc(val, ir.IntType(int(output.get(\"size\")) * 8))", "= fetch_input_varnode(builder, input_1) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) if input_0.text", "source = ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text, 0)) else: source = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "= ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs = check_shift_inputs(builder, lhs, rhs,", "ir_func.append_basic_block(address) blocks[address] = block builders[address] = ir.IRBuilder(block) return builders, blocks", "output.type.as_pointer()) builder.store(output, reg) elif var_type == \"unique\": uniques[name.text] = output", "= [\"RSP\", \"RIP\", \"RBP\", \"EBP\", \"ESP\"] def lift(filename): root =", "if quiter: break address = instruction.find(\"address\").text if address in builders:", "target = fetch_input_varnode(builder, pcode.find(\"input_0\")) if not target.type.is_pointer: target = builder.inttoptr(target,", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SDIV\": lhs = fetch_input_varnode(builder,", "lhs, rhs = check_shift_inputs(builder, lhs, rhs, target) output = builder.lshr(lhs,", "ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"bit_extraction\") internal_functions[\"bit_extraction\"] = ir_func", "== \"RETURN\": input_1 = pcode.find(\"input_1\") no_branch = False if input_1", "int_check_inputs(builder, lhs, rhs, target) output = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "None) var.linkage = 'internal' registers[register.get('name')] = var for memory_location in", "blocks == {}: return populate_cfg(function, builders, blocks) def build_function(name, module):", "stack = builder.alloca(ir.IntType(8), stack_size, name=\"stack\") stack_top = builder.gep(stack, [ir.Constant(int64, stack_size", "if var_type == \"register\": return registers[name.text] elif var_type == \"unique\":", "output) elif mnemonic.text == \"INT_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "ir.Function(module, fnty, \"intra_function_branch\") internal_functions[\"intra_function_branch\"] = ir_func func_return = ir.VoidType() fnty", "True for pcode in pcodes: pc += 1 mnemonic =", "int_check_inputs(builder, lhs, rhs, target) output = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "# weird jump into some label in another function #", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_DIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NOTEQUAL\": raise Exception(\"Not implemented\")", "* 8) if input_0.text in pointers and input_1.get(\"storage\") == \"constant\":", "= builder.bitcast(reg, output.type.as_pointer()) builder.store(output, reg) elif var_type == \"unique\": uniques[name.text]", "= builder.gep(rhs, [ir.Constant(int64, 0)]) result = builder.load(rhs) update_output(builder, output, result)", "= builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"FLOAT_EQUAL\":", "Exception(\"Not implemented\") elif mnemonic.text == \"PTRADD\": raise Exception(\"Not implemented\") elif", "if name.text not in list(uniques.keys()): raise Exception(\"Temporary variable referenced before", "return ir_func def build_cfg(function, ir_func): builders, blocks = {}, {}", "var.linkage = 'internal' registers[register.get('name')] = var for memory_location in root.find('memory').findall('memory'):", "target) output = builder.urem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text", "\"INT_SEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs,", "in blocks: target = blocks[value] builder.branch(target) no_branch = False else:", "elif mnemonic.text == \"RETURN\": input_1 = pcode.find(\"input_1\") no_branch = False", "\"bit_extraction\") internal_functions[\"bit_extraction\"] = ir_func for function in root.findall('function'): name =", "rhs = builder.ptrtoint(rhs, rhs.type.pointee) output = builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8))", "lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.uadd_with_overflow(lhs, rhs)", "module): func_return = ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func =", "else: source = fetch_input_varnode(builder, pcode.find(\"input_0\")) update_output(builder, pcode.find(\"output\"), source) elif mnemonic.text", "mnemonic.text == \"INT_ZEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs", "len(blocks) and no_branch: builder.branch(list(blocks.values())[block_iterator]) def fetch_input_varnode(builder, name): var_type = name.get(\"storage\")", "while name in function_names: name = name + \"_\" +", "int_check_inputs(builder, lhs, rhs, target) output = builder.urem(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "== \"INT_LESSEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_ZEXT\": rhs = fetch_input_varnode(builder,", "pcode.find(\"input_1\")) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs = int_check_inputs(builder,", "== \"FLOAT_ABS\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SQRT\": raise", "implemented\") elif mnemonic.text == \"FLOAT_LESS\": raise Exception(\"Not implemented\") elif mnemonic.text", "= int_comparison_check_inputs(builder, lhs, rhs) result = builder.uadd_with_overflow(lhs, rhs) result =", "might be solved with callbr instruction? builder.call(internal_functions[\"intra_function_branch\"], []) elif mnemonic.text", "rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.uadd_with_overflow(lhs, rhs) result", "# This is incorrect. This is treating it as a", "implemented\") elif mnemonic.text == \"CPOOLREF\": raise Exception(\"Not implemented\") elif mnemonic.text", "== \"constant\": result = builder.gep(lhs, [ir.Constant(int64, -int(input_1.text, 16))]) else: lhs,", "reg.type != output.type.as_pointer(): reg = builder.bitcast(reg, output.type.as_pointer()) builder.store(output, reg) elif", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.and_(lhs,", "= check_shift_inputs(builder, lhs, rhs, target) output = builder.ashr(lhs, rhs) update_output(builder,", "target): if lhs.type != target: if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs,", "builder.branch(list(blocks.values())[1]) block_iterator = 1 instr = 0 quiter = False", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_LEFT\": lhs =", "pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs = fetch_input_varnode(builder, input_0) rhs =", "= pcode.find(\"input_1\") lhs = fetch_input_varnode(builder, input_0) rhs = fetch_input_varnode(builder, input_1)", "= ir.Constant(ir.IntType(var_size), int(name.text, 0)) return var elif var_type == \"memory\":", "result = builder.sub(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "else: builder.call(internal_functions['bit_extraction'], []) elif mnemonic.text == \"INT_EQUAL\": lhs = fetch_input_varnode(builder,", "== \"INT_RIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "\"LOAD\": input_1 = pcode.find(\"input_1\") output = pcode.find(\"output\") rhs = fetch_input_varnode(builder,", "raise Exception(\"Not implemented\") else: raise Exception(\"Not a standard pcode instruction\")", "def fetch_output_varnode(name): var_type = name.get(\"storage\") if var_type == \"register\": return", "blocks: target = blocks[value] builder.branch(target) no_branch = False else: #", "mnemonic.text == \"INT_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "builders: builder = builders[address] pcodes = instruction.find(\"pcodes\") pc = 0", "pcode.find(\"input_1\") lhs = fetch_input_varnode(builder, input_0) rhs = fetch_input_varnode(builder, input_1) target", "rhs = fetch_input_varnode(builder, input_2) lhs = fetch_output_varnode(input_1) lhs2 = builder.gep(lhs,", "ir.Module(name=\"lifted\") for register in root.find('globals').findall('register'): if register.get('name') in flags: var", "def check_shift_inputs(builder, lhs, rhs, target): if lhs.type != target: if", "\"BOOL_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result", "* 8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_ADD\": input_0", "var_type == \"register\": return builder.load(registers[name.text]) elif var_type == \"unique\": if", "\"PTRADD\": raise Exception(\"Not implemented\") elif mnemonic.text == \"PTRSUB\": raise Exception(\"Not", "output) elif mnemonic.text == \"INT_MULT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.sadd_with_overflow(lhs, rhs) result", "1 instr += 1 if block_iterator < len(blocks) and no_branch:", "blocks) def build_function(name, module): func_return = ir.VoidType() fnty = ir.FunctionType(func_return,", "= [\"ZF\", \"CF\", \"OF\", \"SF\"] pointers = [\"RSP\", \"RIP\", \"RBP\",", "= builder.gep(stack, [ir.Constant(int64, stack_size - 8)], name=\"stack_top\") builder.store(stack_top, registers[\"RSP\"]) builder.branch(list(blocks.values())[1])", "return memory[name.text] def update_output(builder, name, output): var_type = name.get(\"storage\") if", "\"FLOAT_ABS\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SQRT\": raise Exception(\"Not", "in pointers: var = ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name')) var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)),", "result = builder.icmp_unsigned('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "lhs, rhs) result = builder.sadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1)", "= registers[name.text] if reg.type != output.type.as_pointer(): reg = builder.bitcast(reg, output.type.as_pointer())", "builder.alloca(ir.IntType(8), stack_size, name=\"stack\") stack_top = builder.gep(stack, [ir.Constant(int64, stack_size - 8)],", "result = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "result) elif mnemonic.text == \"BOOL_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "rhs.type != target and lhs != rhs: if rhs.type.is_pointer: rhs", "== \"BOOL_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "functions[address] populate_func(ir_func, function) return module def populate_func(ir_func, function): builders, blocks", "mnemonic.text == \"INT_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "\"constant\": result = builder.gep(lhs, [ir.Constant(int64, -int(input_1.text, 16))]) else: lhs, rhs", "elif mnemonic.text == \"INT_SCARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.urem(lhs,", "rhs, target) result = builder.add(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "fetch_input_varnode(builder, pcode.find(\"input_1\")) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs =", "mnemonic.text == \"FLOAT_NAN\": raise Exception(\"Not implemented\") elif mnemonic.text == \"INT2FLOAT\":", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.xor(lhs,", "== \"INT2FLOAT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT2FLOAT\": raise", "= pcode.find(\"output\") rhs = fetch_input_varnode(builder, input_1) if input_1.get(\"storage\") == \"unique\"", "instruction.find(\"address\").text if address in builders: builder = builders[address] pcodes =", "== \"INT_LESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "fetch_input_varnode(builder, pcode.find(\"input_0\")) update_output(builder, pcode.find(\"output\"), source) elif mnemonic.text == \"LOAD\": input_1", "output = builder.mul(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "+ \"_\" + str(x) x += 1 function_names.append(name) address =", "\"INT_NEGATE\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(val) update_output(builder, pcode.find(\"output\"),", "a copy, should load the memory address in the input", "int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"),", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SUB\": input_0 = pcode.find(\"input_0\") input_1", "= function.get('name') x = 1 while name in function_names: name", "instr = 0 quiter = False for instruction in function.find(\"instructions\"):", "incorrect. This is treating it as a copy, should load", "elif mnemonic.text == \"FLOAT_LESSEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "\"INT_LESSEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "builder.urem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SDIV\": lhs", "source = fetch_input_varnode(builder, pcode.find(\"input_0\")) update_output(builder, pcode.find(\"output\"), source) elif mnemonic.text ==", "var = ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name')) var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)), None) var.linkage", "should load the memory address in the input 1 update_output(builder,", "lhs, rhs) result = builder.icmp_unsigned('!=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "solved with callbr instruction? builder.call(internal_functions[\"intra_function_branch\"], []) elif mnemonic.text == \"CBRANCH\":", "fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result =", "0 quiter = False for instruction in function.find(\"instructions\"): if quiter:", "ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_ADD\":", "== \"INT_LEFT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "output) elif mnemonic.text == \"INT_ADD\": input_0 = pcode.find(\"input_0\") input_1 =", "reg = registers[name.text] if reg.type != output.type.as_pointer(): reg = builder.bitcast(reg,", "target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs = int_check_inputs(builder, lhs,", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.mul(lhs,", "func_return = ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module,", "elif mnemonic.text == \"INT_CARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "input_1.text in pointers: rhs = builder.gep(rhs, [ir.Constant(int64, 0)]) result =", "# source rhs = fetch_input_varnode(builder, input_2) lhs = fetch_output_varnode(input_1) lhs2", "\"unique\": if name.text not in uniques: uniques[name.text] = None return", "input_2) lhs = fetch_output_varnode(input_1) lhs2 = builder.gep(lhs, [ir.Constant(int64, 0)]) if", "fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, name) return", "== \"register\": return registers[name.text] elif var_type == \"unique\": if name.text", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SUB\": raise Exception(\"Not implemented\")", "== \"INT_SEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs =", "return registers[name.text] elif var_type == \"unique\": if name.text not in", "[]) elif mnemonic.text == \"CALLIND\": # target = pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"],", "raise Exception(\"Not a standard pcode instruction\") block_iterator += 1 instr", "False if input_1 is None: builder.ret_void() else: raise Exception(\"Return value", "= fetch_input_varnode(builder, pcode.find(\"input_1\")) no_branch = False builder.cbranch(condition, true_target, false_target) elif", "output = builder.urem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "target = functions[value][0] builder.call(target, []) elif value in blocks: target", "lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS\": lhs", "the memory address in the input 1 update_output(builder, output, rhs)", "== \"unique\": if name.text not in uniques: uniques[name.text] = None", "raise Exception(\"PIECE operation needs to be tested\") elif mnemonic.text ==", "return uniques[name.text] elif var_type == \"constant\": var = ir.Constant(ir.IntType(var_size), int(name.text,", "builders, blocks): builder = builders[\"entry\"] stack_size = 10 * 1024", "output) elif mnemonic.text == \"INT_SRIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "lhs, rhs, target) result = builder.add(lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "\"CALL\": target = functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target, []) elif mnemonic.text == \"CALLIND\":", "instruction in instructions: address = instruction.find(\"address\").text block = ir_func.append_basic_block(address) blocks[address]", "[]) elif value in blocks: target = blocks[value] builder.branch(target) no_branch", "elif mnemonic.text == \"INT_NOTEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "functions[value][0] builder.call(target, []) elif value in blocks: target = blocks[value]", "if register.get('name') in flags: var = ir.GlobalVariable(module, ir.IntType(1), register.get('name')) var.initializer", "implemented\") elif mnemonic.text == \"FLOAT_LESSEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text", "int64 = ir.IntType(64) int1 = ir.IntType(1) void_type = ir.VoidType() function_names", "output, rhs) else: if input_1.text in pointers: rhs = builder.gep(rhs,", "builder.gep(rhs, [ir.Constant(int64, 0)]) result = builder.load(rhs) update_output(builder, output, result) elif", "target): if lhs.type != target: if lhs.type.is_pointer: lhs2 = lhs", "root.find('memory').findall('memory'): var = ir.GlobalVariable(module, ir.IntType(8 * int(memory_location.get('size'))), memory_location.get('name')) var.initializer =", "in uniques: uniques[name.text] = None return uniques[name.text] def int_check_inputs(builder, lhs,", "\"FLOAT_LESS\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESSEQUAL\": raise Exception(\"Not", "result) elif mnemonic.text == \"INT_NEGATE\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result", "lhs = builder.zext(lhs, target) if rhs.type != target: if rhs.type.is_pointer:", "lhs, rhs) result = builder.icmp_signed('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "builder.store(rhs, lhs2) elif mnemonic.text == \"BRANCH\": value = pcode.find(\"input_0\").text[2:-2] if", "rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) else: rhs = builder.zext(rhs, target)", "mnemonic.text == \"LOAD\": input_1 = pcode.find(\"input_1\") output = pcode.find(\"output\") rhs", "= builder.icmp_unsigned('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "name=\"stack_top\") builder.store(stack_top, registers[\"RSP\"]) builder.branch(list(blocks.values())[1]) block_iterator = 1 instr = 0", "= name.get(\"storage\") if var_type == \"register\": reg = registers[name.text] if", "rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs)", "in instructions: address = instruction.find(\"address\").text block = ir_func.append_basic_block(address) blocks[address] =", "name in function_names: name = name + \"_\" + str(x)", "result = builder.neg(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_XOR\":", "in root.find('memory').findall('memory'): var = ir.GlobalVariable(module, ir.IntType(8 * int(memory_location.get('size'))), memory_location.get('name')) var.initializer", "mnemonic.text == \"CALLIND\": # target = pcode.find(\"input_0\").text[2:-2] builder.call(internal_functions[\"call_indirect\"], []) elif", "pcode.find(\"input_1\")) result = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "false_target = list(blocks.values())[block_iterator + 1] condition = fetch_input_varnode(builder, pcode.find(\"input_1\")) no_branch", "= ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty,", "another function # might be solved with callbr instruction? builder.call(internal_functions[\"intra_function_branch\"],", "is the correct type. if lhs.type.is_pointer: lhs = builder.ptrtoint(lhs, rhs.type)", "memory[name.text] def update_output(builder, name, output): var_type = name.get(\"storage\") if var_type", "pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_OR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "= int_check_inputs(builder, lhs, rhs, target) output = builder.div(lhs, rhs) update_output(builder,", "mnemonic.text == \"INT_LESSEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "memory_location.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(memory_location.get('size'))), None) var.linkage = 'internal'", "with callbr instruction? builder.call(internal_functions[\"intra_function_branch\"], []) elif mnemonic.text == \"CBRANCH\": true_target", "rhs, target) output = builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "== \"TRUNC\": raise Exception(\"Not implemented\") elif mnemonic.text == \"CPOOLREF\": raise", "int32 = ir.IntType(32) int64 = ir.IntType(64) int1 = ir.IntType(1) void_type", "{} flags = [\"ZF\", \"CF\", \"OF\", \"SF\"] pointers = [\"RSP\",", "builder.sdiv(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SREM\": lhs", "tested\") elif mnemonic.text == \"SUBPIECE\": output = pcode.find(\"output\") input_0 =", "+= 1 mnemonic = pcode.find(\"name\") if mnemonic.text == \"COPY\": output", "weird jump into some label in another function # might", "= ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name')) var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)), None) var.linkage =", "{} memory = {} flags = [\"ZF\", \"CF\", \"OF\", \"SF\"]", "{}, {} internal_functions = {} memory = {} flags =", "value in blocks: target = blocks[value] builder.branch(target) no_branch = False", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.srem(lhs,", "\"EBP\", \"ESP\"] def lift(filename): root = et.parse(filename).getroot() module = ir.Module(name=\"lifted\")", "lhs2 = builder.bitcast(lhs2, rhs.type.as_pointer()) builder.store(rhs, lhs2) elif mnemonic.text == \"BRANCH\":", "implemented\") elif mnemonic.text == \"FLOAT_NEG\": raise Exception(\"Not implemented\") elif mnemonic.text", "address in the input 1 update_output(builder, output, rhs) else: if", "!= output.type.as_pointer(): reg = builder.bitcast(reg, output.type.as_pointer()) builder.store(output, reg) elif var_type", "in root.findall('function'): name = function.get('name') x = 1 while name", "rhs.type.as_pointer()) builder.store(rhs, lhs2) elif mnemonic.text == \"BRANCH\": value = pcode.find(\"input_0\").text[2:-2]", "update_output(builder, output, result) else: builder.call(internal_functions['bit_extraction'], []) elif mnemonic.text == \"INT_EQUAL\":", "for memory_location in root.find('memory').findall('memory'): var = ir.GlobalVariable(module, ir.IntType(8 * int(memory_location.get('size'))),", "true_target, false_target) elif mnemonic.text == \"BRANCHIND\": no_branch = False target", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SCARRY\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "= builder.icmp_unsigned('==', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "no_branch: builder.branch(list(blocks.values())[block_iterator]) def fetch_input_varnode(builder, name): var_type = name.get(\"storage\") var_size =", "if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) return lhs, rhs def", "result) else: builder.call(internal_functions['bit_extraction'], []) elif mnemonic.text == \"INT_EQUAL\": lhs =", "uniques[name.text] def int_check_inputs(builder, lhs, rhs, target): if lhs.type != target:", "\"CF\", \"OF\", \"SF\"] pointers = [\"RSP\", \"RIP\", \"RBP\", \"EBP\", \"ESP\"]", "ir.IntType(32) int64 = ir.IntType(64) int1 = ir.IntType(1) void_type = ir.VoidType()", "= builder.ptrtoint(lhs, target) else: lhs = builder.zext(lhs, target) if rhs.type", "flags and pcode.find(\"input_0\").get(\"storage\") == \"constant\": source = ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text, 0))", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_ZEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "\"unique\": if name.text not in list(uniques.keys()): raise Exception(\"Temporary variable referenced", "builder.ptrtoint(lhs, target) else: lhs = builder.zext(lhs, target) if rhs.type !=", "builder.neg(val) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_XOR\": lhs =", "rhs, target) output = builder.ashr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "ir.VoidType() fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"intra_function_branch\")", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SREM\": lhs =", "builder.mul(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_DIV\": lhs", "fetch_input_varnode(builder, input_0) rhs = fetch_input_varnode(builder, input_1) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) *", "instructions: address = instruction.find(\"address\").text block = ir_func.append_basic_block(address) blocks[address] = block", "elif mnemonic.text == \"FLOAT_LESS\": raise Exception(\"Not implemented\") elif mnemonic.text ==", "break address = instruction.find(\"address\").text if address in builders: builder =", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_CEIL\": raise Exception(\"Not implemented\")", "== \"unique\": uniques[name.text] = output def fetch_output_varnode(name): var_type = name.get(\"storage\")", "int(memory_location.get('size'))), memory_location.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(memory_location.get('size'))), None) var.linkage =", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SBORROW\": lhs = fetch_input_varnode(builder,", "instructions = function.find(\"instructions\") if instructions: block = ir_func.append_basic_block(\"entry\") blocks[\"entry\"] =", "= block builders[\"entry\"] = ir.IRBuilder(block) for instruction in instructions: address", "= pcode.find(\"input_0\").text[2:-2] if value in functions: target = functions[value][0] builder.call(target,", "= builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_OR\":", "= builder.icmp_unsigned('!=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "target input_2 = pcode.find(\"input_2\") # source rhs = fetch_input_varnode(builder, input_2)", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_OR\": lhs = fetch_input_varnode(builder,", "builders, blocks # noinspection DuplicatedCode def populate_cfg(function, builders, blocks): builder", "Exception(\"Not implemented\") elif mnemonic.text == \"PTRSUB\": raise Exception(\"Not implemented\") elif", "var = ir.GlobalVariable(module, ir.IntType(8 * int(memory_location.get('size'))), memory_location.get('name')) var.initializer = ir.Constant(ir.IntType(8", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NOTEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "int_check_inputs(builder, lhs, rhs, target) output = builder.srem(lhs, rhs) update_output(builder, pcode.find(\"output\"),", "= ir.Constant(ir.IntType(8 * int(register.get('size'))), None) var.linkage = 'internal' registers[register.get('name')] =", "result) elif mnemonic.text == \"INT_SBORROW\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "== \"INT_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "output = builder.ashr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "lhs.type.is_pointer: lhs2 = lhs lhs = builder.ptrtoint(lhs, target) if lhs2", "= ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"intra_function_branch\") internal_functions[\"intra_function_branch\"] =", "builder.inttoptr(target, target.type.as_pointer()) builder.branch_indirect(target) elif mnemonic.text == \"CALL\": target = functions[pcode.find(\"input_0\").text[2:-2]][0]", "== \"MULTIEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"INDIRECT\": raise", "Exception(\"Not implemented\") elif mnemonic.text == \"NEW\": raise Exception(\"Not implemented\") elif", "mnemonic.text == \"INT_SLESS_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SCARRY\": lhs", "builder.trunc(val, ir.IntType(int(output.get(\"size\")) * 8)) update_output(builder, output, result) else: builder.call(internal_functions['bit_extraction'], [])", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_CARRY\": lhs = fetch_input_varnode(builder,", "== \"unique\": if name.text not in list(uniques.keys()): raise Exception(\"Temporary variable", "lhs, rhs, target) output = builder.ashr(lhs, rhs) update_output(builder, pcode.find(\"output\"), output)", "result = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "treating it as a copy, should load the memory address", "rhs.type.pointee) output = builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8)) update_output(builder, pcode.find(\"output\"), output)", "pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "= builder.gep(lhs, [ir.Constant(int64, 0)]) if lhs2.type != rhs.type.as_pointer(): lhs2 =", "ir.GlobalVariable(module, ir.IntType(8 * int(register.get('size'))), register.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(register.get('size'))),", "rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SDIV\": lhs =", "\"INT_REM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) target", "blocks): builder = builders[\"entry\"] stack_size = 10 * 1024 *", "= output def fetch_output_varnode(name): var_type = name.get(\"storage\") if var_type ==", "implemented\") elif mnemonic.text == \"FLOAT_MULT\": raise Exception(\"Not implemented\") elif mnemonic.text", "builder.icmp_unsigned('==', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NOTEQUAL\":", "in the input 1 update_output(builder, output, rhs) else: if input_1.text", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_2COMP\": val = fetch_input_varnode(builder,", "if input_1 is None: builder.ret_void() else: raise Exception(\"Return value being", "lhs, rhs) result = builder.icmp_unsigned('<', lhs, rhs) update_output(builder, pcode.find(\"output\"), result)", "= builder.icmp_signed('<=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "== \"PTRSUB\": raise Exception(\"Not implemented\") elif mnemonic.text == \"CAST\": raise", "builder.xor(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_AND\": lhs", "pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<=',", "name.get(\"storage\") if var_type == \"register\": reg = registers[name.text] if reg.type", "result) elif mnemonic.text == \"INT_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) if input_0.text in pointers and input_1.get(\"storage\") ==", "to be tested\") elif mnemonic.text == \"SUBPIECE\": output = pcode.find(\"output\")", "return lhs, rhs def int_comparison_check_inputs(builder, lhs, rhs): # For integer", "[ir.Constant(int64, stack_size - 8)], name=\"stack_top\") builder.store(stack_top, registers[\"RSP\"]) builder.branch(list(blocks.values())[1]) block_iterator =", "rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.sdiv(lhs, rhs)", "builder.bitcast(reg, output.type.as_pointer()) builder.store(output, reg) elif var_type == \"unique\": uniques[name.text] =", "ir import xml.etree.ElementTree as et int32 = ir.IntType(32) int64 =", "implemented\") elif mnemonic.text == \"FLOAT_NOTEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text", "variable referenced before defined\") return uniques[name.text] elif var_type == \"constant\":", "ir.GlobalVariable(module, ir.IntType(8 * int(memory_location.get('size'))), memory_location.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(memory_location.get('size'))),", "\"INT_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "functions, uniques, extracts = {}, {}, {}, {} internal_functions =", "pcode.find(\"input_0\").get(\"storage\") == \"constant\": source = ir.Constant(ir.IntType(1), int(pcode.find(\"input_0\").text, 0)) else: source", "ir.Function(module, fnty, \"bit_extraction\") internal_functions[\"bit_extraction\"] = ir_func for function in root.findall('function'):", "= ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs = int_check_inputs(builder, lhs, rhs,", "[\"ZF\", \"CF\", \"OF\", \"SF\"] pointers = [\"RSP\", \"RIP\", \"RBP\", \"EBP\",", "function.get('name') x = 1 while name in function_names: name =", "instruction.find(\"address\").text block = ir_func.append_basic_block(address) blocks[address] = block builders[address] = ir.IRBuilder(block)", "memory address in the input 1 update_output(builder, output, rhs) else:", "= check_shift_inputs(builder, lhs, rhs, target) output = builder.lshr(lhs, rhs) update_output(builder,", "fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.xor(lhs, rhs)", "= builder.uadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result)", "pcode.find(\"output\"), source) elif mnemonic.text == \"LOAD\": input_1 = pcode.find(\"input_1\") output", "== \"FLOAT_ADD\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SUB\": raise", "pointers and input_1.get(\"storage\") == \"constant\": result = builder.gep(lhs, [ir.Constant(int64, int(input_1.text,", "instructions: block = ir_func.append_basic_block(\"entry\") blocks[\"entry\"] = block builders[\"entry\"] = ir.IRBuilder(block)", "address in functions: ir_func, function = functions[address] populate_func(ir_func, function) return", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.neg(lhs) update_output(builder, pcode.find(\"output\"), result) elif", "def populate_func(ir_func, function): builders, blocks = build_cfg(function, ir_func) if blocks", "pcode.find(\"input_0\")) if not target.type.is_pointer: target = builder.inttoptr(target, target.type.as_pointer()) builder.branch_indirect(target) elif", "= fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.or_(lhs,", "rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<', lhs, rhs)", "!= rhs.type.as_pointer(): lhs2 = builder.bitcast(lhs2, rhs.type.as_pointer()) builder.store(rhs, lhs2) elif mnemonic.text", "mnemonic.text == \"INT_SEXT\": rhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) if rhs.type.is_pointer: rhs", "registers, functions, uniques, extracts = {}, {}, {}, {} internal_functions", "else: rhs = builder.zext(rhs, target) return lhs, rhs def int_comparison_check_inputs(builder,", "update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NOTEQUAL\": lhs = fetch_input_varnode(builder,", "rhs) else: if input_1.text in pointers: rhs = builder.gep(rhs, [ir.Constant(int64,", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS_EQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "= False else: # weird jump into some label in", "elif mnemonic.text == \"INT_SDIV\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs =", "== \"FLOAT_LESS\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESSEQUAL\": raise", "0)) else: source = fetch_input_varnode(builder, pcode.find(\"input_0\")) update_output(builder, pcode.find(\"output\"), source) elif", "* int(register.get('size'))), register.get('name')) var.initializer = ir.Constant(ir.IntType(8 * int(register.get('size'))), None) var.linkage", "update_output(builder, name, output): var_type = name.get(\"storage\") if var_type == \"register\":", "val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.not_(val) update_output(builder, pcode.find(\"output\"), result)", "ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs = check_shift_inputs(builder, lhs, rhs, target)", "= fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result", "builders[\"entry\"] = ir.IRBuilder(block) for instruction in instructions: address = instruction.find(\"address\").text", "var for memory_location in root.find('memory').findall('memory'): var = ir.GlobalVariable(module, ir.IntType(8 *", "blocks[address] = block builders[address] = ir.IRBuilder(block) return builders, blocks #", "builder.shl(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_RIGHT\": lhs", "= builder.neg(lhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_XOR\": lhs", "implemented\") elif mnemonic.text == \"FLOAT_ROUND\": raise Exception(\"Not implemented\") elif mnemonic.text", "builder.branch(list(blocks.values())[block_iterator]) def fetch_input_varnode(builder, name): var_type = name.get(\"storage\") var_size = int(name.get(\"size\"))", "Exception(\"Not implemented\") elif mnemonic.text == \"CPOOLREF\": raise Exception(\"Not implemented\") elif", "rhs) result = builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "builder.branch_indirect(target) elif mnemonic.text == \"CALL\": target = functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target, [])", "\"call_indirect\") internal_functions[\"call_indirect\"] = ir_func func_return = ir.VoidType() fnty = ir.FunctionType(func_return,", "if rhs.type != target and lhs != rhs: if rhs.type.is_pointer:", "address = instruction.find(\"address\").text if address in builders: builder = builders[address]", "= False if input_1 is None: builder.ret_void() else: raise Exception(\"Return", "mnemonic.text == \"FLOAT_ABS\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SQRT\":", "\"FLOAT_NOTEQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESS\": raise Exception(\"Not", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESSEQUAL\": raise Exception(\"Not implemented\")", "\"USERDEFINED\": raise Exception(\"Not implemented\") elif mnemonic.text == \"RETURN\": input_1 =", "pcode.find(\"output\"), result) elif mnemonic.text == \"INT_2COMP\": val = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "= builder.bitcast(lhs2, rhs.type.as_pointer()) builder.store(rhs, lhs2) elif mnemonic.text == \"BRANCH\": value", "function.get('address') functions[address] = [build_function(name, module), function] for address in functions:", "mnemonic.text == \"FLOAT_ADD\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_SUB\":", "= lhs if rhs.type != target and lhs != rhs:", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) result = builder.sub(lhs,", "ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name')) var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)), None) var.linkage = 'internal'", "= builder.urem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"INT_SDIV\":", "\"INT_NOTEQUAL\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\")) lhs,", "update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text == \"BOOL_NEGATE\": lhs = fetch_input_varnode(builder,", "pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_AND\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "* 8)) update_output(builder, output, result) else: builder.call(internal_functions['bit_extraction'], []) elif mnemonic.text", "\"FLOAT_EQUAL\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NOTEQUAL\": raise Exception(\"Not", "result) elif mnemonic.text == \"STORE\": input_1 = pcode.find(\"input_1\") # target", "raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_MULT\": raise Exception(\"Not implemented\")", "= int_check_inputs(builder, lhs, rhs, target) output = builder.urem(lhs, rhs) update_output(builder,", "et.parse(filename).getroot() module = ir.Module(name=\"lifted\") for register in root.find('globals').findall('register'): if register.get('name')", "\"INT_2COMP\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result = builder.not_(val) update_output(builder, pcode.find(\"output\"),", "return populate_cfg(function, builders, blocks) def build_function(name, module): func_return = ir.VoidType()", "\"register\": return builder.load(registers[name.text]) elif var_type == \"unique\": if name.text not", "result = builder.add(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text ==", "in root.find('globals').findall('register'): if register.get('name') in flags: var = ir.GlobalVariable(module, ir.IntType(1),", "== \"INT_SRIGHT\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder, pcode.find(\"input_1\"))", "implemented\") elif mnemonic.text == \"FLOAT_DIV\": raise Exception(\"Not implemented\") elif mnemonic.text", "functions: ir_func, function = functions[address] populate_func(ir_func, function) return module def", "list(uniques.keys()): raise Exception(\"Temporary variable referenced before defined\") return uniques[name.text] elif", "# target input_2 = pcode.find(\"input_2\") # source rhs = fetch_input_varnode(builder,", "build_cfg(function, ir_func): builders, blocks = {}, {} instructions = function.find(\"instructions\")", "+ 1] condition = fetch_input_varnode(builder, pcode.find(\"input_1\")) no_branch = False builder.cbranch(condition,", "name = name + \"_\" + str(x) x += 1", "register.get('name') in pointers: var = ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name')) var.initializer =", "\"FLOAT_ROUND\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_NAN\": raise Exception(\"Not", "mnemonic.text == \"FLOAT_LESS\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_LESSEQUAL\":", "= name.get(\"storage\") if var_type == \"register\": return registers[name.text] elif var_type", "= builder.sadd_with_overflow(lhs, rhs) result = builder.extract_value(result, 1) update_output(builder, pcode.find(\"output\"), result)", "root = et.parse(filename).getroot() module = ir.Module(name=\"lifted\") for register in root.find('globals').findall('register'):", "mnemonic.text == \"INT_SLESS\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs = fetch_input_varnode(builder,", "result) elif mnemonic.text == \"BOOL_XOR\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\")) rhs", "mnemonic.text == \"FLOAT_MULT\": raise Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_DIV\":", "ir.GlobalVariable(module, ir.IntType(1), register.get('name')) var.initializer = ir.Constant(ir.IntType(1), None) var.linkage = 'internal'", "elif mnemonic.text == \"INT_NEGATE\": val = fetch_input_varnode(builder, pcode.find(\"input_0\")) result =", "= et.parse(filename).getroot() module = ir.Module(name=\"lifted\") for register in root.find('globals').findall('register'): if", "= name + \"_\" + str(x) x += 1 function_names.append(name)", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_NOTEQUAL\": lhs =", "if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, rhs.type.pointee) output = builder.sext(rhs, ir.IntType(int(pcode.find(\"output\").get(\"size\"))", "= 'internal' registers[register.get('name')] = var for memory_location in root.find('memory').findall('memory'): var", "name=\"stack\") stack_top = builder.gep(stack, [ir.Constant(int64, stack_size - 8)], name=\"stack_top\") builder.store(stack_top,", "fetch_input_varnode(builder, pcode.find(\"input_1\")) result = builder.or_(lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif", "= int_check_inputs(builder, lhs, rhs, target) result = builder.sub(lhs, rhs) update_output(builder,", "Exception(\"Not implemented\") elif mnemonic.text == \"FLOAT_FLOOR\": raise Exception(\"Not implemented\") elif", "== \"register\": reg = registers[name.text] if reg.type != output.type.as_pointer(): reg", "module), function] for address in functions: ir_func, function = functions[address]", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESS\": lhs =", "rhs, target) output = builder.srem(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif", "var_type == \"unique\": if name.text not in list(uniques.keys()): raise Exception(\"Temporary", "!= rhs: if rhs.type.is_pointer: rhs = builder.ptrtoint(rhs, target) return lhs,", "== \"INT_ADD\": input_0 = pcode.find(\"input_0\") input_1 = pcode.find(\"input_1\") lhs =", "fnty = ir.FunctionType(func_return, []) ir_func = ir.Function(module, fnty, \"call_indirect\") internal_functions[\"call_indirect\"]", "elif register.get('name') in pointers: var = ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name')) var.initializer", "lhs, rhs = int_check_inputs(builder, lhs, rhs, target) output = builder.div(lhs,", "list(blocks.values())[block_iterator + 1] condition = fetch_input_varnode(builder, pcode.find(\"input_1\")) no_branch = False", "var = ir.GlobalVariable(module, ir.IntType(1), register.get('name')) var.initializer = ir.Constant(ir.IntType(1), None) var.linkage", "Exception(\"Not implemented\") else: raise Exception(\"Not a standard pcode instruction\") block_iterator", "rhs): # For integer comparison operations. We assume rhs is", "= functions[pcode.find(\"input_0\").text[2:-2]][0] builder.call(target, []) elif mnemonic.text == \"CALLIND\": # target", "def lift(filename): root = et.parse(filename).getroot() module = ir.Module(name=\"lifted\") for register", "= False for instruction in function.find(\"instructions\"): if quiter: break address", "lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_LESS\": lhs", "lhs, rhs = int_comparison_check_inputs(builder, lhs, rhs) result = builder.icmp_unsigned('<', lhs,", "For integer comparison operations. We assume rhs is the correct", "We assume rhs is the correct type. if lhs.type.is_pointer: lhs", "output = builder.and_(lhs, rhs) update_output(builder, pcode.find(\"output\"), output) elif mnemonic.text ==", "else: var = ir.GlobalVariable(module, ir.IntType(8 * int(register.get('size'))), register.get('name')) var.initializer =", "= blocks[value] builder.branch(target) no_branch = False else: # weird jump", "result = builder.icmp_unsigned('!=', lhs, rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text", "= 'internal' memory[memory_location.get('name')] = var func_return = ir.VoidType() fnty =", "pcode.find(\"output\"), output) elif mnemonic.text == \"INT_REM\": lhs = fetch_input_varnode(builder, pcode.find(\"input_0\"))", "int(pcode.find(\"input_0\").text, 0)) else: source = fetch_input_varnode(builder, pcode.find(\"input_0\")) update_output(builder, pcode.find(\"output\"), source)", "if blocks == {}: return populate_cfg(function, builders, blocks) def build_function(name,", "result = builder.neg(lhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"BOOL_XOR\":", "return var elif var_type == \"memory\": return memory[name.text] def update_output(builder,", "rhs) update_output(builder, pcode.find(\"output\"), result) elif mnemonic.text == \"INT_SLESS_EQUAL\": lhs =", "pcode.find(\"input_1\")) target = ir.IntType(int(pcode.find(\"output\").get(\"size\")) * 8) lhs, rhs = check_shift_inputs(builder," ]
[ "# # @url: https://github.com/m4ll0k/WPSeku # @author: <NAME> (M4ll0k) import re", "self.cookie = cookie self.req = wphttp.wphttp( agent=agent,proxy=proxy, redir=redir,time=time ) def", "= url self.cookie = cookie self.req = wphttp.wphttp( agent=agent,proxy=proxy, redir=redir,time=time", "resp._content != None: if resp.url == url: wplisting.out.plus('Dir {} listing", "for path in paths: url = wplisting.chk.path(self.url,path) resp = self.req.send(url,c=self.cookie)", "python # -*- Coding: UTF-8 -*- # # WPSeku: Wordpress", "Coding: UTF-8 -*- # # WPSeku: Wordpress Security Scanner #", "wphttp.wphttp( agent=agent,proxy=proxy, redir=redir,time=time ) def run(self): paths = ['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes'", "from lib import wphttp from lib import wpprint class wplisting:", "url = wplisting.chk.path(self.url,path) resp = self.req.send(url,c=self.cookie) if resp.status_code == 200", "resp = self.req.send(url,c=self.cookie) if resp.status_code == 200 and resp._content !=", "'/wp-content/plugins','/wp-content/themes' ] try: for path in paths: url = wplisting.chk.path(self.url,path)", "resp.status_code == 200 and resp._content != None: if resp.url ==", "# # WPSeku: Wordpress Security Scanner # # @url: https://github.com/m4ll0k/WPSeku", "wplisting.chk.path(self.url,path) resp = self.req.send(url,c=self.cookie) if resp.status_code == 200 and resp._content", "agent=agent,proxy=proxy, redir=redir,time=time ) def run(self): paths = ['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes' ]", "self.url = url self.cookie = cookie self.req = wphttp.wphttp( agent=agent,proxy=proxy,", "lib import wpprint class wplisting: chk = wphttp.UCheck() out =", "paths = ['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes' ] try: for path in paths:", "wpprint.wpprint() def __init__(self,agent,proxy,redir,time,url,cookie): self.url = url self.cookie = cookie self.req", "= wphttp.wphttp( agent=agent,proxy=proxy, redir=redir,time=time ) def run(self): paths = ['/wp-admin','/wp-includes','/wp-content/uploads',", "(M4ll0k) import re from lib import wphttp from lib import", "WPSeku: Wordpress Security Scanner # # @url: https://github.com/m4ll0k/WPSeku # @author:", "# -*- Coding: UTF-8 -*- # # WPSeku: Wordpress Security", "wphttp from lib import wpprint class wplisting: chk = wphttp.UCheck()", "Scanner # # @url: https://github.com/m4ll0k/WPSeku # @author: <NAME> (M4ll0k) import", "try: for path in paths: url = wplisting.chk.path(self.url,path) resp =", "Wordpress Security Scanner # # @url: https://github.com/m4ll0k/WPSeku # @author: <NAME>", "= wphttp.UCheck() out = wpprint.wpprint() def __init__(self,agent,proxy,redir,time,url,cookie): self.url = url", "and resp._content != None: if resp.url == url: wplisting.out.plus('Dir {}", "re from lib import wphttp from lib import wpprint class", "# @url: https://github.com/m4ll0k/WPSeku # @author: <NAME> (M4ll0k) import re from", "wpprint class wplisting: chk = wphttp.UCheck() out = wpprint.wpprint() def", "url: wplisting.out.plus('Dir {} listing enabled under: {}'.format(path,resp.url)) except Exception,e: pass", "= ['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes' ] try: for path in paths: url", "= wpprint.wpprint() def __init__(self,agent,proxy,redir,time,url,cookie): self.url = url self.cookie = cookie", "wplisting: chk = wphttp.UCheck() out = wpprint.wpprint() def __init__(self,agent,proxy,redir,time,url,cookie): self.url", "cookie self.req = wphttp.wphttp( agent=agent,proxy=proxy, redir=redir,time=time ) def run(self): paths", "!= None: if resp.url == url: wplisting.out.plus('Dir {} listing enabled", "out = wpprint.wpprint() def __init__(self,agent,proxy,redir,time,url,cookie): self.url = url self.cookie =", "import wphttp from lib import wpprint class wplisting: chk =", "https://github.com/m4ll0k/WPSeku # @author: <NAME> (M4ll0k) import re from lib import", "run(self): paths = ['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes' ] try: for path in", "@url: https://github.com/m4ll0k/WPSeku # @author: <NAME> (M4ll0k) import re from lib", "self.req.send(url,c=self.cookie) if resp.status_code == 200 and resp._content != None: if", "resp.url == url: wplisting.out.plus('Dir {} listing enabled under: {}'.format(path,resp.url)) except", "<NAME> (M4ll0k) import re from lib import wphttp from lib", "def __init__(self,agent,proxy,redir,time,url,cookie): self.url = url self.cookie = cookie self.req =", "= wplisting.chk.path(self.url,path) resp = self.req.send(url,c=self.cookie) if resp.status_code == 200 and", "# @author: <NAME> (M4ll0k) import re from lib import wphttp", "= cookie self.req = wphttp.wphttp( agent=agent,proxy=proxy, redir=redir,time=time ) def run(self):", "redir=redir,time=time ) def run(self): paths = ['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes' ] try:", ") def run(self): paths = ['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes' ] try: for", "paths: url = wplisting.chk.path(self.url,path) resp = self.req.send(url,c=self.cookie) if resp.status_code ==", "== url: wplisting.out.plus('Dir {} listing enabled under: {}'.format(path,resp.url)) except Exception,e:", "in paths: url = wplisting.chk.path(self.url,path) resp = self.req.send(url,c=self.cookie) if resp.status_code", "self.req = wphttp.wphttp( agent=agent,proxy=proxy, redir=redir,time=time ) def run(self): paths =", "200 and resp._content != None: if resp.url == url: wplisting.out.plus('Dir", "import re from lib import wphttp from lib import wpprint", "['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes' ] try: for path in paths: url =", "] try: for path in paths: url = wplisting.chk.path(self.url,path) resp", "== 200 and resp._content != None: if resp.url == url:", "class wplisting: chk = wphttp.UCheck() out = wpprint.wpprint() def __init__(self,agent,proxy,redir,time,url,cookie):", "= self.req.send(url,c=self.cookie) if resp.status_code == 200 and resp._content != None:", "# WPSeku: Wordpress Security Scanner # # @url: https://github.com/m4ll0k/WPSeku #", "url self.cookie = cookie self.req = wphttp.wphttp( agent=agent,proxy=proxy, redir=redir,time=time )", "from lib import wpprint class wplisting: chk = wphttp.UCheck() out", "def run(self): paths = ['/wp-admin','/wp-includes','/wp-content/uploads', '/wp-content/plugins','/wp-content/themes' ] try: for path", "Security Scanner # # @url: https://github.com/m4ll0k/WPSeku # @author: <NAME> (M4ll0k)", "path in paths: url = wplisting.chk.path(self.url,path) resp = self.req.send(url,c=self.cookie) if", "chk = wphttp.UCheck() out = wpprint.wpprint() def __init__(self,agent,proxy,redir,time,url,cookie): self.url =", "import wpprint class wplisting: chk = wphttp.UCheck() out = wpprint.wpprint()", "-*- Coding: UTF-8 -*- # # WPSeku: Wordpress Security Scanner", "wphttp.UCheck() out = wpprint.wpprint() def __init__(self,agent,proxy,redir,time,url,cookie): self.url = url self.cookie", "lib import wphttp from lib import wpprint class wplisting: chk", "#/usr/bin/env python # -*- Coding: UTF-8 -*- # # WPSeku:", "UTF-8 -*- # # WPSeku: Wordpress Security Scanner # #", "if resp.status_code == 200 and resp._content != None: if resp.url", "__init__(self,agent,proxy,redir,time,url,cookie): self.url = url self.cookie = cookie self.req = wphttp.wphttp(", "if resp.url == url: wplisting.out.plus('Dir {} listing enabled under: {}'.format(path,resp.url))", "None: if resp.url == url: wplisting.out.plus('Dir {} listing enabled under:", "@author: <NAME> (M4ll0k) import re from lib import wphttp from", "-*- # # WPSeku: Wordpress Security Scanner # # @url:" ]
[ "from tw2.jit.widgets.chart import (AreaChart, BarChart, PieChart) from tw2.jit.widgets.graph import (ForceDirectedGraph,", "PieChart) from tw2.jit.widgets.graph import (ForceDirectedGraph, RadialGraph) from tw2.jit.widgets.tree import (SpaceTree,", "from tw2.jit.widgets.graph import (ForceDirectedGraph, RadialGraph) from tw2.jit.widgets.tree import (SpaceTree, HyperTree,", "<gh_stars>1-10 from tw2.jit.widgets.chart import (AreaChart, BarChart, PieChart) from tw2.jit.widgets.graph import", "(SpaceTree, HyperTree, Sunburst, Icicle, TreeMap) from tw2.jit.widgets.ajax import AjaxRadialGraph from", "tw2.jit.widgets.tree import (SpaceTree, HyperTree, Sunburst, Icicle, TreeMap) from tw2.jit.widgets.ajax import", "tw2.jit.widgets.graph import (ForceDirectedGraph, RadialGraph) from tw2.jit.widgets.tree import (SpaceTree, HyperTree, Sunburst,", "HyperTree, Sunburst, Icicle, TreeMap) from tw2.jit.widgets.ajax import AjaxRadialGraph from tw2.jit.widgets.sqla", "import (SpaceTree, HyperTree, Sunburst, Icicle, TreeMap) from tw2.jit.widgets.ajax import AjaxRadialGraph", "RadialGraph) from tw2.jit.widgets.tree import (SpaceTree, HyperTree, Sunburst, Icicle, TreeMap) from", "(AreaChart, BarChart, PieChart) from tw2.jit.widgets.graph import (ForceDirectedGraph, RadialGraph) from tw2.jit.widgets.tree", "Sunburst, Icicle, TreeMap) from tw2.jit.widgets.ajax import AjaxRadialGraph from tw2.jit.widgets.sqla import", "BarChart, PieChart) from tw2.jit.widgets.graph import (ForceDirectedGraph, RadialGraph) from tw2.jit.widgets.tree import", "tw2.jit.widgets.chart import (AreaChart, BarChart, PieChart) from tw2.jit.widgets.graph import (ForceDirectedGraph, RadialGraph)", "Icicle, TreeMap) from tw2.jit.widgets.ajax import AjaxRadialGraph from tw2.jit.widgets.sqla import SQLARadialGraph", "import (AreaChart, BarChart, PieChart) from tw2.jit.widgets.graph import (ForceDirectedGraph, RadialGraph) from", "(ForceDirectedGraph, RadialGraph) from tw2.jit.widgets.tree import (SpaceTree, HyperTree, Sunburst, Icicle, TreeMap)", "from tw2.jit.widgets.tree import (SpaceTree, HyperTree, Sunburst, Icicle, TreeMap) from tw2.jit.widgets.ajax", "import (ForceDirectedGraph, RadialGraph) from tw2.jit.widgets.tree import (SpaceTree, HyperTree, Sunburst, Icicle," ]
[ "allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) cmd = f'ffmpeg", "int, int]: args = shlex.split(cmd) process = await asyncio.create_subprocess_exec( *args,", "= downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update = cbb.message.reply_to_message await", "@xbot.on_message(filters.command('start') & filters.private) async def _start(bot, update): await update.reply_text(f\"I'm TikTokDL!\\nYou", "update.text session = requests.Session() resp = session.head(url, allow_redirects=True) if not", "f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'wm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs)", "START_BUTTONS=[ [ InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project Channel', url='https://t.me/xTeamBots'), ], [InlineKeyboardButton('Author', url='https://t.me/xgorn')],", "os.makedirs(dirs) cbb = cb update = cbb.message.reply_to_message await cb.message.delete() url", "APP_ID = int(os.environ['APP_ID']) BOT_TOKEN = os.environ['BOT_TOKEN'] downloads = './downloads/{}/' #Button", "str, int, int]: args = shlex.split(cmd) process = await asyncio.create_subprocess_exec(", "= resp.url.split('?', 1)[0] else: tt = resp.url ttid = dirs+tt.split('/')[-1]", "run_cmd(cmd: str) -> Tuple[str, str, int, int]: args = shlex.split(cmd)", "os.environ['API_HASH'] APP_ID = int(os.environ['APP_ID']) BOT_TOKEN = os.environ['BOT_TOKEN'] downloads = './downloads/{}/'", "callback_data='wm'), ], [InlineKeyboardButton('Audio', callback_data='audio')], ] # Running bot xbot =", "dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update = cbb.message.reply_to_message", "'./downloads/{}/' #Button START_BUTTONS=[ [ InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project Channel', url='https://t.me/xTeamBots'), ],", "_start(bot, update): await update.reply_text(f\"I'm TikTokDL!\\nYou can download tiktok video/audio using", "'?' in resp.url: tt = resp.url.split('?', 1)[0] else: tt =", "= session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) cmd", "[ InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project Channel', url='https://t.me/xTeamBots'), ], [InlineKeyboardButton('Author', url='https://t.me/xgorn')], ]", "bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'wm': dirs = downloads.format(uuid.uuid4().hex)", "= requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) cmd = f'ffmpeg -i \"{ttid}.mp4\"", "json, requests, os, shlex, asyncio, uuid, shutil from typing import", "elif cb.data == 'wm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb =", "& filters.private) async def _tiktok(bot, update): url = update.text session", "# Helpers # Thanks to FridayUB async def run_cmd(cmd: str)", "cb.data == 'audio': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb", "TikTokDL!\\nYou can download tiktok video/audio using this bot\", True, reply_markup=InlineKeyboardMarkup(START_BUTTONS))", "rs['result']['wm'] resp = session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4',", "reply_markup=InlineKeyboardMarkup(START_BUTTONS)) # Downloader for tiktok @xbot.on_message(filters.regex(pattern='.*http.*') & filters.private) async def", "r.text rs = json.loads(result) link = rs['result']['nowm'] resp = session.head(link,", "= json.loads(result) link = rs['result']['wm'] resp = session.head(link, allow_redirects=True) r", "shutil from typing import Tuple from pyrogram import Client, filters", "for tiktok @xbot.on_message(filters.regex(pattern='.*http.*') & filters.private) async def _tiktok(bot, update): url", "allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',)", "= session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) await", "Client, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery # Configs", "pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery # Configs API_HASH = os.environ['API_HASH']", "2 -ab 192 -f mp3 \"{ttid}.mp3\"' await run_cmd(cmd) await bot.send_audio(update.chat.id,", "-ar 44100 -ac 2 -ab 192 -f mp3 \"{ttid}.mp3\"' await", "downloads = './downloads/{}/' #Button START_BUTTONS=[ [ InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project Channel',", "= dirs+tt.split('/')[-1] r = requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result = r.text rs =", "-> Tuple[str, str, int, int]: args = shlex.split(cmd) process =", ") stdout, stderr = await process.communicate() return ( stdout.decode(\"utf-8\", \"replace\").strip(),", "= await process.communicate() return ( stdout.decode(\"utf-8\", \"replace\").strip(), stderr.decode(\"utf-8\", \"replace\").strip(), process.returncode,", "asyncio, uuid, shutil from typing import Tuple from pyrogram import", "requests.Session() resp = session.head(url, allow_redirects=True) if not 'tiktok.com' in resp.url:", "= r.text rs = json.loads(result) link = rs['result']['nowm'] resp =", "await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'wm': dirs =", "stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() return ( stdout.decode(\"utf-8\",", "rs['result']['nowm'] resp = session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4',", "Channel', url='https://t.me/xTeamBots'), ], [InlineKeyboardButton('Author', url='https://t.me/xgorn')], ] DL_BUTTONS=[ [ InlineKeyboardButton('No Watermark',", "import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery # Configs API_HASH = os.environ['API_HASH'] APP_ID", "await cb.message.delete() url = update.text session = requests.Session() resp =", "os.environ['BOT_TOKEN'] downloads = './downloads/{}/' #Button START_BUTTONS=[ [ InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project", "api_hash=API_HASH, bot_token=BOT_TOKEN) # Helpers # Thanks to FridayUB async def", "shlex.split(cmd) process = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout,", "update = cbb.message.reply_to_message await cb.message.delete() url = update.text session =", "= requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif", "bot_token=BOT_TOKEN) # Helpers # Thanks to FridayUB async def run_cmd(cmd:", "# Thanks to FridayUB async def run_cmd(cmd: str) -> Tuple[str,", "can download tiktok video/audio using this bot\", True, reply_markup=InlineKeyboardMarkup(START_BUTTONS)) #", "requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result = r.text rs = json.loads(result) link = rs['result']['nowm']", "[ InlineKeyboardButton('No Watermark', callback_data='nowm'), InlineKeyboardButton('Watermark', callback_data='wm'), ], [InlineKeyboardButton('Audio', callback_data='audio')], ]", "tiktok video/audio using this bot\", True, reply_markup=InlineKeyboardMarkup(START_BUTTONS)) # Downloader for", "downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update = cbb.message.reply_to_message await cb.message.delete()", "= int(os.environ['APP_ID']) BOT_TOKEN = os.environ['BOT_TOKEN'] downloads = './downloads/{}/' #Button START_BUTTONS=[", "CallbackQuery # Configs API_HASH = os.environ['API_HASH'] APP_ID = int(os.environ['APP_ID']) BOT_TOKEN", "int]: args = shlex.split(cmd) process = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE,", "async def _start(bot, update): await update.reply_text(f\"I'm TikTokDL!\\nYou can download tiktok", ") # Start @xbot.on_message(filters.command('start') & filters.private) async def _start(bot, update):", "= r.text rs = json.loads(result) link = rs['result']['wm'] resp =", "return await update.reply('Select the options below', True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) # Callbacks", "resp = session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content)", "xbot = Client('TikTokDL', api_id=APP_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) # Helpers # Thanks", "await update.reply('Select the options below', True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) # Callbacks @xbot.on_callback_query()", "= cb update = cbb.message.reply_to_message await cb.message.delete() url = update.text", "Helpers # Thanks to FridayUB async def run_cmd(cmd: str) ->", "resp = session.head(url, allow_redirects=True) if not 'tiktok.com' in resp.url: return", "update.text session = requests.Session() resp = session.head(url, allow_redirects=True) if '?'", "else: tt = resp.url ttid = dirs+tt.split('/')[-1] r = requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt)", "f'ffmpeg -i \"{ttid}.mp4\" -vn -ar 44100 -ac 2 -ab 192", "= requests.Session() resp = session.head(url, allow_redirects=True) if '?' in resp.url:", "options below', True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) # Callbacks @xbot.on_callback_query() async def _callbacks(bot,", "_callbacks(bot, cb: CallbackQuery): if cb.data == 'nowm': dirs = downloads.format(uuid.uuid4().hex)", "== 'wm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update", "InlineKeyboardButton('No Watermark', callback_data='nowm'), InlineKeyboardButton('Watermark', callback_data='wm'), ], [InlineKeyboardButton('Audio', callback_data='audio')], ] #", "Client('TikTokDL', api_id=APP_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) # Helpers # Thanks to FridayUB", "update): await update.reply_text(f\"I'm TikTokDL!\\nYou can download tiktok video/audio using this", "Running bot xbot = Client('TikTokDL', api_id=APP_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) # Helpers", "# Start @xbot.on_message(filters.command('start') & filters.private) async def _start(bot, update): await", "= await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr =", "r.text rs = json.loads(result) link = rs['result']['wm'] resp = session.head(link,", "tt = resp.url ttid = dirs+tt.split('/')[-1] r = requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result", "cb.data == 'wm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb", "session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) await bot.send_video(update.chat.id,", "from pyrogram import Client, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup,", "[InlineKeyboardButton('Author', url='https://t.me/xgorn')], ] DL_BUTTONS=[ [ InlineKeyboardButton('No Watermark', callback_data='nowm'), InlineKeyboardButton('Watermark', callback_data='wm'),", "bot xbot = Client('TikTokDL', api_id=APP_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) # Helpers #", "Start @xbot.on_message(filters.command('start') & filters.private) async def _start(bot, update): await update.reply_text(f\"I'm", "True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) # Callbacks @xbot.on_callback_query() async def _callbacks(bot, cb: CallbackQuery):", "shlex, asyncio, uuid, shutil from typing import Tuple from pyrogram", "filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery # Configs API_HASH", "# Running bot xbot = Client('TikTokDL', api_id=APP_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) #", "requests.Session() resp = session.head(url, allow_redirects=True) if '?' in resp.url: tt", "= cbb.message.reply_to_message await cb.message.delete() url = update.text session = requests.Session()", "reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) # Callbacks @xbot.on_callback_query() async def _callbacks(bot, cb: CallbackQuery): if", "resp.url.split('?', 1)[0] else: tt = resp.url ttid = dirs+tt.split('/')[-1] r", "= json.loads(result) link = rs['result']['nowm'] resp = session.head(link, allow_redirects=True) r", "result = r.text rs = json.loads(result) link = rs['result']['wm'] resp", "DL_BUTTONS=[ [ InlineKeyboardButton('No Watermark', callback_data='nowm'), InlineKeyboardButton('Watermark', callback_data='wm'), ], [InlineKeyboardButton('Audio', callback_data='audio')],", "resp.url ttid = dirs+tt.split('/')[-1] r = requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result = r.text", "= rs['result']['wm'] resp = session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True)", "], [InlineKeyboardButton('Author', url='https://t.me/xgorn')], ] DL_BUTTONS=[ [ InlineKeyboardButton('No Watermark', callback_data='nowm'), InlineKeyboardButton('Watermark',", "# Callbacks @xbot.on_callback_query() async def _callbacks(bot, cb: CallbackQuery): if cb.data", "Tuple[str, str, int, int]: args = shlex.split(cmd) process = await", "192 -f mp3 \"{ttid}.mp3\"' await run_cmd(cmd) await bot.send_audio(update.chat.id, f'{ttid}.mp3',) shutil.rmtree(dirs)", "InlineKeyboardButton('Watermark', callback_data='wm'), ], [InlineKeyboardButton('Audio', callback_data='audio')], ] # Running bot xbot", "await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'audio': dirs =", "Watermark', callback_data='nowm'), InlineKeyboardButton('Watermark', callback_data='wm'), ], [InlineKeyboardButton('Audio', callback_data='audio')], ] # Running", "filters.private) async def _tiktok(bot, update): url = update.text session =", "async def run_cmd(cmd: str) -> Tuple[str, str, int, int]: args", "= session.head(url, allow_redirects=True) if '?' in resp.url: tt = resp.url.split('?',", "= os.environ['BOT_TOKEN'] downloads = './downloads/{}/' #Button START_BUTTONS=[ [ InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'),", "Callbacks @xbot.on_callback_query() async def _callbacks(bot, cb: CallbackQuery): if cb.data ==", "link = rs['result']['nowm'] resp = session.head(link, allow_redirects=True) r = requests.get(resp.url,", "= resp.url ttid = dirs+tt.split('/')[-1] r = requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result =", "requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data", "rs = json.loads(result) link = rs['result']['wm'] resp = session.head(link, allow_redirects=True)", "open(f'{ttid}.mp4', 'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'audio':", "str) -> Tuple[str, str, int, int]: args = shlex.split(cmd) process", "video/audio using this bot\", True, reply_markup=InlineKeyboardMarkup(START_BUTTONS)) # Downloader for tiktok", "bot\", True, reply_markup=InlineKeyboardMarkup(START_BUTTONS)) # Downloader for tiktok @xbot.on_message(filters.regex(pattern='.*http.*') & filters.private)", "if cb.data == 'nowm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb =", "import json, requests, os, shlex, asyncio, uuid, shutil from typing", "'wb').write(r.content) cmd = f'ffmpeg -i \"{ttid}.mp4\" -vn -ar 44100 -ac", "InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery # Configs API_HASH = os.environ['API_HASH'] APP_ID =", "update.reply_text(f\"I'm TikTokDL!\\nYou can download tiktok video/audio using this bot\", True,", "process.communicate() return ( stdout.decode(\"utf-8\", \"replace\").strip(), stderr.decode(\"utf-8\", \"replace\").strip(), process.returncode, process.pid, )", "return ( stdout.decode(\"utf-8\", \"replace\").strip(), stderr.decode(\"utf-8\", \"replace\").strip(), process.returncode, process.pid, ) #", "\"replace\").strip(), stderr.decode(\"utf-8\", \"replace\").strip(), process.returncode, process.pid, ) # Start @xbot.on_message(filters.command('start') &", "@xbot.on_message(filters.regex(pattern='.*http.*') & filters.private) async def _tiktok(bot, update): url = update.text", "download tiktok video/audio using this bot\", True, reply_markup=InlineKeyboardMarkup(START_BUTTONS)) # Downloader", "tt = resp.url.split('?', 1)[0] else: tt = resp.url ttid =", "shutil.rmtree(dirs) elif cb.data == 'wm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb", "os, shlex, asyncio, uuid, shutil from typing import Tuple from", "'audio': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update =", "using this bot\", True, reply_markup=InlineKeyboardMarkup(START_BUTTONS)) # Downloader for tiktok @xbot.on_message(filters.regex(pattern='.*http.*')", "tiktok @xbot.on_message(filters.regex(pattern='.*http.*') & filters.private) async def _tiktok(bot, update): url =", "session.head(url, allow_redirects=True) if '?' in resp.url: tt = resp.url.split('?', 1)[0]", "& filters.private) async def _start(bot, update): await update.reply_text(f\"I'm TikTokDL!\\nYou can", "args = shlex.split(cmd) process = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE", "session.head(url, allow_redirects=True) if not 'tiktok.com' in resp.url: return await update.reply('Select", "await update.reply_text(f\"I'm TikTokDL!\\nYou can download tiktok video/audio using this bot\",", "bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'audio': dirs = downloads.format(uuid.uuid4().hex)", "# Downloader for tiktok @xbot.on_message(filters.regex(pattern='.*http.*') & filters.private) async def _tiktok(bot,", "requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result = r.text rs = json.loads(result) link = rs['result']['wm']", "json.loads(result) link = rs['result']['wm'] resp = session.head(link, allow_redirects=True) r =", "= session.head(url, allow_redirects=True) if not 'tiktok.com' in resp.url: return await", "cbb = cb update = cbb.message.reply_to_message await cb.message.delete() url =", "url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project Channel', url='https://t.me/xTeamBots'), ], [InlineKeyboardButton('Author', url='https://t.me/xgorn')], ] DL_BUTTONS=[ [", "Downloader for tiktok @xbot.on_message(filters.regex(pattern='.*http.*') & filters.private) async def _tiktok(bot, update):", "if not 'tiktok.com' in resp.url: return await update.reply('Select the options", "url='https://t.me/xgorn')], ] DL_BUTTONS=[ [ InlineKeyboardButton('No Watermark', callback_data='nowm'), InlineKeyboardButton('Watermark', callback_data='wm'), ],", "async def _callbacks(bot, cb: CallbackQuery): if cb.data == 'nowm': dirs", "result = r.text rs = json.loads(result) link = rs['result']['nowm'] resp", "session = requests.Session() resp = session.head(url, allow_redirects=True) if not 'tiktok.com'", "cb: CallbackQuery): if cb.data == 'nowm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs)", "int(os.environ['APP_ID']) BOT_TOKEN = os.environ['BOT_TOKEN'] downloads = './downloads/{}/' #Button START_BUTTONS=[ [", "stdout.decode(\"utf-8\", \"replace\").strip(), stderr.decode(\"utf-8\", \"replace\").strip(), process.returncode, process.pid, ) # Start @xbot.on_message(filters.command('start')", "\"replace\").strip(), process.returncode, process.pid, ) # Start @xbot.on_message(filters.command('start') & filters.private) async", "stdout, stderr = await process.communicate() return ( stdout.decode(\"utf-8\", \"replace\").strip(), stderr.decode(\"utf-8\",", "= requests.Session() resp = session.head(url, allow_redirects=True) if not 'tiktok.com' in", "json.loads(result) link = rs['result']['nowm'] resp = session.head(link, allow_redirects=True) r =", "session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) cmd =", "== 'audio': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update", "elif cb.data == 'audio': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb =", "Configs API_HASH = os.environ['API_HASH'] APP_ID = int(os.environ['APP_ID']) BOT_TOKEN = os.environ['BOT_TOKEN']", "#Button START_BUTTONS=[ [ InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project Channel', url='https://t.me/xTeamBots'), ], [InlineKeyboardButton('Author',", "44100 -ac 2 -ab 192 -f mp3 \"{ttid}.mp3\"' await run_cmd(cmd)", "cb update = cbb.message.reply_to_message await cb.message.delete() url = update.text session", "below', True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) # Callbacks @xbot.on_callback_query() async def _callbacks(bot, cb:", "resp.url: tt = resp.url.split('?', 1)[0] else: tt = resp.url ttid", "-ac 2 -ab 192 -f mp3 \"{ttid}.mp3\"' await run_cmd(cmd) await", "callback_data='nowm'), InlineKeyboardButton('Watermark', callback_data='wm'), ], [InlineKeyboardButton('Audio', callback_data='audio')], ] # Running bot", "API_HASH = os.environ['API_HASH'] APP_ID = int(os.environ['APP_ID']) BOT_TOKEN = os.environ['BOT_TOKEN'] downloads", "Thanks to FridayUB async def run_cmd(cmd: str) -> Tuple[str, str,", "Tuple from pyrogram import Client, filters from pyrogram.types import InlineKeyboardButton,", "= './downloads/{}/' #Button START_BUTTONS=[ [ InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project Channel', url='https://t.me/xTeamBots'),", "resp = session.head(url, allow_redirects=True) if '?' in resp.url: tt =", "1)[0] else: tt = resp.url ttid = dirs+tt.split('/')[-1] r =", "allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data ==", "open(f'{ttid}.mp4', 'wb').write(r.content) cmd = f'ffmpeg -i \"{ttid}.mp4\" -vn -ar 44100", "this bot\", True, reply_markup=InlineKeyboardMarkup(START_BUTTONS)) # Downloader for tiktok @xbot.on_message(filters.regex(pattern='.*http.*') &", "in resp.url: return await update.reply('Select the options below', True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS))", "typing import Tuple from pyrogram import Client, filters from pyrogram.types", "cb.message.delete() url = update.text session = requests.Session() resp = session.head(url,", "\"{ttid}.mp4\" -vn -ar 44100 -ac 2 -ab 192 -f mp3", "stderr = await process.communicate() return ( stdout.decode(\"utf-8\", \"replace\").strip(), stderr.decode(\"utf-8\", \"replace\").strip(),", "uuid, shutil from typing import Tuple from pyrogram import Client,", "'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'audio': dirs", "in resp.url: tt = resp.url.split('?', 1)[0] else: tt = resp.url", "[InlineKeyboardButton('Audio', callback_data='audio')], ] # Running bot xbot = Client('TikTokDL', api_id=APP_ID,", "( stdout.decode(\"utf-8\", \"replace\").strip(), stderr.decode(\"utf-8\", \"replace\").strip(), process.returncode, process.pid, ) # Start", "InlineKeyboardMarkup, CallbackQuery # Configs API_HASH = os.environ['API_HASH'] APP_ID = int(os.environ['APP_ID'])", "True, reply_markup=InlineKeyboardMarkup(START_BUTTONS)) # Downloader for tiktok @xbot.on_message(filters.regex(pattern='.*http.*') & filters.private) async", "requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) cmd = f'ffmpeg -i \"{ttid}.mp4\" -vn", "cmd = f'ffmpeg -i \"{ttid}.mp4\" -vn -ar 44100 -ac 2", "InlineKeyboardButton('Project Channel', url='https://t.me/xTeamBots'), ], [InlineKeyboardButton('Author', url='https://t.me/xgorn')], ] DL_BUTTONS=[ [ InlineKeyboardButton('No", "url = update.text session = requests.Session() resp = session.head(url, allow_redirects=True)", "= update.text session = requests.Session() resp = session.head(url, allow_redirects=True) if", "requests, os, shlex, asyncio, uuid, shutil from typing import Tuple", "stderr.decode(\"utf-8\", \"replace\").strip(), process.returncode, process.pid, ) # Start @xbot.on_message(filters.command('start') & filters.private)", "import Client, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery #", "'wm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update =", "allow_redirects=True) if '?' in resp.url: tt = resp.url.split('?', 1)[0] else:", "r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) cmd = f'ffmpeg -i", "from typing import Tuple from pyrogram import Client, filters from", "-vn -ar 44100 -ac 2 -ab 192 -f mp3 \"{ttid}.mp3\"'", "allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) cmd = f'ffmpeg -i \"{ttid}.mp4\" -vn -ar", "= Client('TikTokDL', api_id=APP_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) # Helpers # Thanks to", "rs = json.loads(result) link = rs['result']['nowm'] resp = session.head(link, allow_redirects=True)", "BOT_TOKEN = os.environ['BOT_TOKEN'] downloads = './downloads/{}/' #Button START_BUTTONS=[ [ InlineKeyboardButton('Source',", "allow_redirects=True) if not 'tiktok.com' in resp.url: return await update.reply('Select the", "from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery # Configs API_HASH =", "FridayUB async def run_cmd(cmd: str) -> Tuple[str, str, int, int]:", "_tiktok(bot, update): url = update.text session = requests.Session() resp =", "-f mp3 \"{ttid}.mp3\"' await run_cmd(cmd) await bot.send_audio(update.chat.id, f'{ttid}.mp3',) shutil.rmtree(dirs) xbot.run()", "# Configs API_HASH = os.environ['API_HASH'] APP_ID = int(os.environ['APP_ID']) BOT_TOKEN =", "to FridayUB async def run_cmd(cmd: str) -> Tuple[str, str, int,", "ttid = dirs+tt.split('/')[-1] r = requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result = r.text rs", "f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'audio': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs)", "await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await", "update.reply('Select the options below', True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) # Callbacks @xbot.on_callback_query() async", "= f'ffmpeg -i \"{ttid}.mp4\" -vn -ar 44100 -ac 2 -ab", "] DL_BUTTONS=[ [ InlineKeyboardButton('No Watermark', callback_data='nowm'), InlineKeyboardButton('Watermark', callback_data='wm'), ], [InlineKeyboardButton('Audio',", "], [InlineKeyboardButton('Audio', callback_data='audio')], ] # Running bot xbot = Client('TikTokDL',", "await process.communicate() return ( stdout.decode(\"utf-8\", \"replace\").strip(), stderr.decode(\"utf-8\", \"replace\").strip(), process.returncode, process.pid,", "'nowm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update =", "'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'wm': dirs", "<filename>bot.py import json, requests, os, shlex, asyncio, uuid, shutil from", "filters.private) async def _start(bot, update): await update.reply_text(f\"I'm TikTokDL!\\nYou can download", "def _start(bot, update): await update.reply_text(f\"I'm TikTokDL!\\nYou can download tiktok video/audio", "InlineKeyboardButton('Source', url='https://github.com/X-Gorn/TikTokDL'), InlineKeyboardButton('Project Channel', url='https://t.me/xTeamBots'), ], [InlineKeyboardButton('Author', url='https://t.me/xgorn')], ] DL_BUTTONS=[", "asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate()", "session = requests.Session() resp = session.head(url, allow_redirects=True) if '?' in", "-ab 192 -f mp3 \"{ttid}.mp3\"' await run_cmd(cmd) await bot.send_audio(update.chat.id, f'{ttid}.mp3',)", "process = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr", "import Tuple from pyrogram import Client, filters from pyrogram.types import", "= requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result = r.text rs = json.loads(result) link =", "stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() return (", "process.pid, ) # Start @xbot.on_message(filters.command('start') & filters.private) async def _start(bot,", "def _tiktok(bot, update): url = update.text session = requests.Session() resp", "update): url = update.text session = requests.Session() resp = session.head(url,", "'tiktok.com' in resp.url: return await update.reply('Select the options below', True,", "CallbackQuery): if cb.data == 'nowm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb", "== 'nowm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb update", "-i \"{ttid}.mp4\" -vn -ar 44100 -ac 2 -ab 192 -f", "if '?' in resp.url: tt = resp.url.split('?', 1)[0] else: tt", "*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() return", "not 'tiktok.com' in resp.url: return await update.reply('Select the options below',", "pyrogram import Client, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery", "def run_cmd(cmd: str) -> Tuple[str, str, int, int]: args =", "process.returncode, process.pid, ) # Start @xbot.on_message(filters.command('start') & filters.private) async def", "= os.environ['API_HASH'] APP_ID = int(os.environ['APP_ID']) BOT_TOKEN = os.environ['BOT_TOKEN'] downloads =", "async def _tiktok(bot, update): url = update.text session = requests.Session()", "= shlex.split(cmd) process = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE )", "@xbot.on_callback_query() async def _callbacks(bot, cb: CallbackQuery): if cb.data == 'nowm':", "the options below', True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) # Callbacks @xbot.on_callback_query() async def", "url='https://t.me/xTeamBots'), ], [InlineKeyboardButton('Author', url='https://t.me/xgorn')], ] DL_BUTTONS=[ [ InlineKeyboardButton('No Watermark', callback_data='nowm'),", "cb.data == 'nowm': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb = cb", "cbb.message.reply_to_message await cb.message.delete() url = update.text session = requests.Session() resp", "open(f'{ttid}.mp4', 'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs) elif cb.data == 'wm':", "link = rs['result']['wm'] resp = session.head(link, allow_redirects=True) r = requests.get(resp.url,", "api_id=APP_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) # Helpers # Thanks to FridayUB async", "dirs+tt.split('/')[-1] r = requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result = r.text rs = json.loads(result)", "= rs['result']['nowm'] resp = session.head(link, allow_redirects=True) r = requests.get(resp.url, allow_redirects=True)", "] # Running bot xbot = Client('TikTokDL', api_id=APP_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)", "def _callbacks(bot, cb: CallbackQuery): if cb.data == 'nowm': dirs =", "callback_data='audio')], ] # Running bot xbot = Client('TikTokDL', api_id=APP_ID, api_hash=API_HASH,", "shutil.rmtree(dirs) elif cb.data == 'audio': dirs = downloads.format(uuid.uuid4().hex) os.makedirs(dirs) cbb", "resp.url: return await update.reply('Select the options below', True, reply_markup=InlineKeyboardMarkup(DL_BUTTONS)) #", "r = requests.get('https://api.reiyuura.me/api/dl/tiktok?url='+tt) result = r.text rs = json.loads(result) link", "r = requests.get(resp.url, allow_redirects=True) open(f'{ttid}.mp4', 'wb').write(r.content) await bot.send_video(update.chat.id, f'{ttid}.mp4',) shutil.rmtree(dirs)" ]
[ "label self._add_result_label(main_vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"room_select\"] =", "self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if question_index == 1: # requester send request to", "self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q2_panel(self):", "{\"room\": info[\"room\"], \"start\": info[\"start\"], \"end\": info[\"end\"], # 'start': '2020-04-05 21:00:00',", "= tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"] = dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"] = tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"] =", "try: occu = str(response['count']) occupancy_info = response['occupancy_info'] except: occu =", "= occu_label self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q2_panel(self): print(\"q2\")", "= util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"] = util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0) def join(self, timeout=None):", "proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"utilization_label\"] = occu_label", "= wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox1.Add(start_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox1.Add(dpc1, proportion=3,", "self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl # add result widget # add count", "self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"] = util.combine_datetime(date, time) info[\"room\"] = room # requester", "self._stopevent = threading.Event() self.parent_panel = parent_panel self.parent_thread = parent_thread def", "1: ## get ## url = self.server + \"/people_building/\" body", "# add name list roomlb = wx.ListBox(self) vbox.Add(roomlb, proportion=0, flag=wx.ALL,", "border=5) hbox2.Add(tpc2, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox2, proportion=0, flag=wx.ALL, border=5) #", "self._add_result_label(vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl", "self._stopevent.set() print(\"thread stop\") threading.Thread.join(self, timeout) class RightPanel(wx.Panel): def __init__(self, parent,", "flag=wx.RIGHT|wx.TOP, border=4) date_hbox.Add(dpc, proportion=3, flag=wx.RIGHT, border=5) date_hbox.Add(tpc, proportion=3, flag=wx.RIGHT, border=5)", "# add canvas panel # canvas_panel = CanvasPanel(self) # vbox1.Add(canvas_panel,", "5: ## get ## url = self.server + \"/utilization/\" body", "= parent_thread def run(self): while (not self._stopevent.is_set()) and self.parent_thread.is_alive(): print(\"hello\")", "elif question_index == 3: ## get ## url = self.server", "wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc2 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox2.Add(end_label, proportion=2,", "vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3", "= roomlb self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q4_panel(self): print(\"q4\")", "a specific room?\" ] drop_down_menu = wx.ComboBox(self, choices=question_list) hbox1.Add(drop_down_menu, proportion=8,", "border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name list roomlb", "start_label = wx.StaticText(self, label=\"START TIME\") start_label.SetFont(self.font) dpc1 = wx.adv.DatePickerCtrl(self, -1,", "wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox1.Add(start_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox1.Add(dpc1, proportion=3, flag=wx.RIGHT,", "rlb.Append(name) elif question_index == 5: ## get ## url =", "self.Fit() self.GetParent().SendSizeEvent() def _q3_panel(self): print(\"q3\") vbox = self.add_date_time_picker_layout() hbox1 =", "self.SetBackgroundColour(\"#000000\") # r = lambda: random.randint(0,255) # color = '#%02X%02X%02X'", "time = self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"] = util.combine_datetime(date, time)", "time import datetime import threading import requests import json from", "except: occu = str(0) occupancy_info = [] ## received ##", "date_hbox.Add(dpc, proportion=3, flag=wx.RIGHT, border=5) date_hbox.Add(tpc, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(date_hbox, proportion=0,", "self.GetParent().SendSizeEvent() def _q5_panel(self): print(\"q5\") vbox = wx.BoxSizer(wx.VERTICAL) # datetime date_hbox", "= self._request_handle(url=url, body=body, METHOD=\"post\") # self.request_handle(url, body, METHOD=\"post\") try: response", "tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"] = dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"] = tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"] = cb", "combo drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection, combo_box=drop_down_menu, panel=result_panel)) def on_selection(self, event, combo_box, panel):", "Real time box real_label = wx.StaticText(self, label=\"REAL TIME\") real_label.SetFont(self.font) cb", "= {\"name\": info[\"name\"], \"start\": info[\"start\"], \"end\": info[\"end\"], # 'start': '2020-04-05", "count = str(0) room_list = [] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count)", "self.OnClick(event, question_index), comfirm_btn) def _add_result_label(self, sizer): result_label = wx.StaticText(self, label=\"RESULT\")", "hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL) # Start start_label =", "send request to server pass elif question_index == 2: #", "confirm button self._add_confirm_button(vbox, 3) # add result label self._add_result_label(vbox) #", "the worker is working if self.worker: self.worker.join() self.worker = None", "# add result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self,", "end_label = wx.StaticText(self, label=\"END TIME\") end_label.SetFont(self.font) dpc2 = wx.adv.DatePickerCtrl(self, -1,", "start = end - datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"] = util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"] =", "wx.BoxSizer(wx.HORIZONTAL) # Start start_label = wx.StaticText(self, label=\"START TIME\") start_label.SetFont(self.font) dpc1", "## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for name in room_list:", "# confirm button self._add_confirm_button(vbox, 3) # add result label self._add_result_label(vbox)", "received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif question_index == 2: ## get ## url", "button self._add_confirm_button(main_vbox, 1) # add result label self._add_result_label(main_vbox) # add", "} response = self._request_handle(url=url, body=body, METHOD=\"post\") try: room_list = response['room']", "border=10) # add drop down menu question_list = [ \"1.", "'end': '2020-04-05 21:10:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\") try:", "time end = datetime.datetime.now() start = end - datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"]", "params={}, METHOD=\"post\"): # https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\", url) print(\"body\", body) print(\"params\", params)", "(r(),r(),r()) return vbox def _add_confirm_button(self, sizer, question_index): \"\"\" question_index =>", "How many people are in a specific room?\", \"3. Where", "None self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear() decorate_panel = self._q_dict[q_idx] decorate_panel() def add_date_time_picker_layout(self): vbox", "main_vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self, label=\"Name\")", "confirm button self._add_confirm_button(main_vbox, 2) # add result label self._add_result_label(main_vbox) #", "self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self, label=\"Name\") name_label.SetFont(self.font) hbox1.Add(name_label,", "OnClick(self, event, question_index): info = {} # handle date and", "for name in room_list: rlb.Append(name) elif question_index == 5: ##", "to server room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room) info[\"room\"] = room elif", "ResultPanel(self) # result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) vbox.Add(hbox1, proportion=1, flag=wx.EXPAND|wx.ALL,", "building?\", \"2. How many people are in a specific room?\",", "self.info_widget_dict[\"consumer\"][\"name_list\"] = namelb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q3_panel(self):", "name_text_ctrl # add result widget # add count hbox =", "= wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0,", "wx.Panel.__init__(self, parent=parent) self.drop_down_menu_ID = None self.result_visual_ID = None self.info =", "# add result label self._add_result_label(main_vbox) # add widget infomation to", "self.Fit() self.GetParent().SendSizeEvent() def _q4_panel(self): print(\"q4\") main_vbox = self.add_date_time_picker_layout() hbox1 =", "if if_real_time: if not self.worker: self.worker = ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(), parent_panel=self)", "= wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL) # Start start_label = wx.StaticText(self,", "print(\"q4\") main_vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self,", "= {\"name\": info[\"name\"], # \"start_time\": info[\"start\"], # \"end_time\": info[\"end\"], \"time\":", "button self._add_confirm_button(main_vbox, 2) # add result label self._add_result_label(main_vbox) # add", "util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0) def join(self, timeout=None): self._stopevent.set() print(\"thread stop\") threading.Thread.join(self,", "= response['occupancy_info'] except: occu = str(0) occupancy_info = [] ##", "= wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) font.MakeBold() result_label.SetFont(font) sizer.Add(result_label, proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL, border=20) def", "room_list = response['room'] count = str(len(room_list)) except: count = str(0)", "are in a specific room?\", \"3. Where is someone?\", #", "the building?\", \"2. How many people are in a specific", "comfirm_btn = wx.Button(self, id=-1, label=\"Confirm\") sizer.Add(comfirm_btn, proportion=0, flag=wx.TOP|wx.LEFT, border=5) #", "flag=wx.TOP, border=5) vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox,", "-1, wx.DefaultDateTime) tpc2 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox2.Add(end_label, proportion=2, flag=wx.RIGHT|wx.TOP,", "== 200: resp = r.json() print(resp) print(type(resp)) return resp def", "many people are in the building?\", \"2. How many people", "print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0]) # st2 = wx.StaticText(self, label=combo_box.GetValue()) # st2.SetFont(font) #", "else: r = requests.get(url, params=params) print(r.status_code) if r.status_code == 200:", "room_list: rlb.Append(name) elif question_index == 5: ## get ## url", "info[\"end\"], \"time\": info[\"start\"], } response = self._request_handle(url=url, body=body, METHOD=\"post\") count", "requester send request to server pass elif question_index == 2:", "hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL) #", "print(r.status_code) if r.status_code == 200: resp = r.json() print(resp) print(type(resp))", "response = json.loads(response) utilization = \"{:.2f}\".format(response[\"utilization\"]*100) + \"%\" except: utilization", "proportion=2, flag=wx.RIGHT, border=10) # add drop down menu question_list =", "import config import time import datetime import threading import requests", "\"Room_1_1_150\", \"Room_1_1_184\"] room_combobox = wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5)", "= wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0,", "name in occupancy_info: nlb.Append(name) elif question_index == 3: ## get", "proportion=0, flag=wx.ALL, border=5) # add name list namelb = wx.ListBox(self)", "self._init_UI() def _init_UI(self): self.SetBackgroundColour(\"#BAB86C\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) vbox =", "params) resp = {} if METHOD == \"post\": r =", "import time import datetime import threading import requests import json", "# canvas_panel = CanvasPanel(self) # vbox1.Add(canvas_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) result_panel", "listen combo drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection, combo_box=drop_down_menu, panel=result_panel)) def on_selection(self, event, combo_box,", "real_label = wx.StaticText(self, label=\"REAL TIME\") real_label.SetFont(self.font) cb = wx.CheckBox(self) hbox3.Add(real_label,", "name, parent_thread, parent_panel): threading.Thread.__init__(self, name=name) self._stopevent = threading.Event() self.parent_panel =", "self.worker = ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(), parent_panel=self) self.worker.start() print(\"start worker\") else: #", "# https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\", url) print(\"body\", body) print(\"params\", params) resp =", "room_label.SetFont(self.font) room_hbox.Add(room_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) room_list = [ \"\", \"Room_1_1_140\",", "print(\"start time = {}\".format(info[\"start\"])) # print(\"end time = {}\".format(info[\"end\"])) if_real_time", "main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small", "wx.StaticText(self, label=\"Name\") name_label.SetFont(self.font) hbox1.Add(name_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) name_text_ctrl = wx.TextCtrl(self)", "dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"] = tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"] = dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"] = tpc2", "= [] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear()", "wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(hbox1,", "False date = self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time = self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue()", "border=5) # End end_label = wx.StaticText(self, label=\"END TIME\") end_label.SetFont(self.font) dpc2", "resp = r.json() print(resp) print(type(resp)) return resp def _send_request(self, info):", "wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL) # Start start_label = wx.StaticText(self, label=\"START", "= wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT,", "add_date_time_picker_layout(self): vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL)", "people are in a specific room?\", \"3. Where is someone?\",", "border=5) # confirm button self._add_confirm_button(vbox, 5) # add result label", "enter unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL,", "# \"start_time\": info[\"start\"], # \"end_time\": info[\"end\"], \"time\": info[\"start\"], } response", "flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name list", "https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\", url) print(\"body\", body) print(\"params\", params) resp = {}", "_request_handle(self, url, body={}, params={}, METHOD=\"post\"): # https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\", url) print(\"body\",", "self.Fit() self.GetParent().SendSizeEvent() def _q2_panel(self): print(\"q2\") main_vbox = self.add_date_time_picker_layout() # Room", "= wx.ComboBox(self, choices=question_list) hbox1.Add(drop_down_menu, proportion=8, flag=wx.TOP, border=5) vbox1 = wx.BoxSizer(wx.VERTICAL)", "add drop down menu question_list = [ \"1. How many", "\"4\": self._q5_panel,} self.info_widget_dict = {\"feeder\": {}, \"consumer\": {}} self.worker =", "border=5) vbox.Add(hbox3, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"feeder\"][\"start_date\"] = dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"] =", "label = wx.StaticText(self, label=\"Room Count\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5)", "wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12) self.font.MakeBold() def init_question_UI(self, q_idx): # clean the panel", "st2 = wx.StaticText(self, label=combo_box.GetValue()) # st2.SetFont(font) # sizer1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER,", "## received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif question_index == 2: ## get ##", "__init__(self, parent, info={}): wx.Panel.__init__(self, parent=parent) self.drop_down_menu_ID = None self.result_visual_ID =", "border=5) # add name list roomlb = wx.ListBox(self) main_vbox.Add(roomlb, proportion=0,", "proportion=0, flag=wx.ALL, border=5) # add name list roomlb = wx.ListBox(self)", "result widget # add count hbox = wx.BoxSizer(wx.HORIZONTAL) label =", "= {}\".format(info[\"end\"])) if_real_time = self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if question_index == 1: #", "ResultPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # self._init_UI() self._q_dict =", "question_index => {1, 2, 3, 4} \"\"\" comfirm_btn = wx.Button(self,", "combo_box, panel): # print(self.drop_down_menu.GetValue()) print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0]) # st2 = wx.StaticText(self,", "self.info = info if if_real_time: if not self.worker: self.worker =", "body=body, METHOD=\"post\") # self.request_handle(url, body, METHOD=\"post\") try: response = json.loads(response)", "vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) # add question label", "= {} if METHOD == \"post\": r = requests.post(url, data=body)", "= str(response['count']) except: occu = str(0) ## received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif", "parent) # self._init_UI() self._q_dict = {\"1\": self._q1_panel, \"2\": self._q2_panel, \"3\":", "font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) font.MakeBold() result_label.SetFont(font) sizer.Add(result_label, proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL, border=20)", "wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5)", "start_time = self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date = self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time = self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"]", "wx.Button(self, id=-1, label=\"Confirm\") sizer.Add(comfirm_btn, proportion=0, flag=wx.TOP|wx.LEFT, border=5) # self.Bind(wx.EVT_BUTTON, self.OnClick,", "add result label self._add_result_label(main_vbox) # add widget infomation to dict", "{} # handle date and time if question_index in [1,", "= cb # self.SetBackgroundColour(\"#000000\") # r = lambda: random.randint(0,255) #", "= self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date = self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time = self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"] =", "print(\"start worker\") else: # first check if the worker is", "comfirm_btn) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, question_index), comfirm_btn) def _add_result_label(self, sizer):", "parent_panel): threading.Thread.__init__(self, name=name) self._stopevent = threading.Event() self.parent_panel = parent_panel self.parent_thread", "def _add_result_label(self, sizer): result_label = wx.StaticText(self, label=\"RESULT\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)", "= room # requester send request to server info[\"question_index\"] =", "has been stop\") self.worker.join() self.worker = None self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear() decorate_panel", "self.server + \"/person_room/\" body = {\"name\": info[\"name\"], \"start\": info[\"start\"], \"end\":", "# clean the panel for child in self.GetChildren(): child.Destroy() #", "random.randint(0,255) # color = '#%02X%02X%02X' % (r(),r(),r()) return vbox def", "= self.add_date_time_picker_layout() # Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label =", "occupancy_info = [] ## received ## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb = self.info_widget_dict[\"consumer\"][\"name_list\"]", "+ \"/utilization/\" body = {\"room\": info[\"room\"], \"date\": info[\"date\"], # 'date':", "border=10) self.SetSizer(vbox) # listen combo drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection, combo_box=drop_down_menu, panel=result_panel)) def", "hbox3.Add(real_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox3.Add(cb, proportion=3, flag=wx.RIGHT|wx.TOP, border=5) vbox.Add(hbox3, proportion=0,", "self.add_date_time_picker_layout() # confirm button self._add_confirm_button(main_vbox, 1) # add result label", "info[\"room\"], \"date\": info[\"date\"], # 'date': '2020-04-05 20:00:00' } response =", "self.GetChildren(): child.Destroy() # stop the worker if self.worker: # print(\"the", "people are in the building?\", \"2. How many people are", "= room_combobox # add result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label", "+ \"question/4\" body = {\"name\": info[\"name\"], # \"start_time\": info[\"start\"], #", "# result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) vbox.Add(hbox1, proportion=1, flag=wx.EXPAND|wx.ALL, border=10)", "is the utilization of a specific room?\" ] drop_down_menu =", "specific room?\", \"3. Where is someone?\", # \"4. Which room", "self.info_widget_dict[\"feeder\"][\"start_date\"] = dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"] = tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"] = dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"]", "self.worker: self.worker = ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(), parent_panel=self) self.worker.start() print(\"start worker\") else:", "threading import requests import json from functools import partial class", "= ResultPanel(self) # result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) vbox.Add(hbox1, proportion=1,", "print(\"thread stop\") threading.Thread.join(self, timeout) class RightPanel(wx.Panel): def __init__(self, parent, info={}):", "choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) # room_info = wx.TextCtrl(self) #", "\"/utilization/\" body = {\"room\": info[\"room\"], \"date\": info[\"date\"], # 'date': '2020-04-05", "received ## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb = self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear() for name in", "room_label = wx.StaticText(self, label=\"Room\") room_label.SetFont(self.font) room_hbox.Add(room_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) room_list", "partial class ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self, name, parent_thread, parent_panel):", "info[\"date\"], # 'date': '2020-04-05 20:00:00' } response = self._request_handle(url=url, body=body,", "add count hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Room Count\")", "label self._add_result_label(main_vbox) # add result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label", "panel.init_question_UI(combo_box.GetValue()[0]) # st2 = wx.StaticText(self, label=combo_box.GetValue()) # st2.SetFont(font) # sizer1.Add(st2,", "self.Bind(wx.EVT_BUTTON, self.OnClick, comfirm_btn) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, question_index), comfirm_btn) def", "= None self.info = info self._init_UI() def _init_UI(self): self.SetBackgroundColour(\"#BAB86C\") font", "flag=wx.RIGHT|wx.TOP, border=4) hbox1.Add(dpc1, proportion=3, flag=wx.RIGHT, border=5) hbox1.Add(tpc1, proportion=3, flag=wx.RIGHT, border=5)", "border=5) # confirm button self._add_confirm_button(main_vbox, 2) # add result label", "% (r(),r(),r()) return vbox def _add_confirm_button(self, sizer, question_index): \"\"\" question_index", "sizer1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) class ResultPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self,", "and time if question_index in [1, 2, 3, 4]: start_date", "import threading import requests import json from functools import partial", "wx.BoxSizer(wx.VERTICAL) # datetime date_hbox = wx.BoxSizer(wx.HORIZONTAL) date_label = wx.StaticText(self, label=\"Datetime\")", "widget infomation to dict self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result", "== 2: # requester send request to server room =", "flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(vbox) #", "self.info_widget_dict[\"feeder\"][\"real_time\"] = cb # self.SetBackgroundColour(\"#000000\") # r = lambda: random.randint(0,255)", "2, 3, 4} \"\"\" comfirm_btn = wx.Button(self, id=-1, label=\"Confirm\") sizer.Add(comfirm_btn,", "flag=wx.EXPAND|wx.ALL, border=10) vbox.Add(vbox1, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) self.SetSizer(vbox) # listen combo", "worker if self.worker: # print(\"the worker has been stop\") self.worker.join()", "self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q5_panel(self): print(\"q5\") vbox =", "# self.SetBackgroundColour(\"#000000\") # r = lambda: random.randint(0,255) # color =", "wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) # add question label st1 =", "confirm button self._add_confirm_button(vbox, 5) # add result label self._add_result_label(vbox) #", "datetime.datetime.now() start = end - datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"] = util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"]", "flag=wx.ALL, border=5) # add name list roomlb = wx.ListBox(self) main_vbox.Add(roomlb,", "label=\"Name\") name_label.SetFont(self.font) hbox1.Add(name_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) name_text_ctrl = wx.TextCtrl(self) name_text_ctrl.AppendText('Please", "_q4_panel(self): print(\"q4\") main_vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label =", "\"question/4\" body = {\"name\": info[\"name\"], # \"start_time\": info[\"start\"], # \"end_time\":", "self.info_widget_dict[\"feeder\"][\"date_picker\"] = dpc self.info_widget_dict[\"feeder\"][\"time_picker\"] = tpc self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox #", "str(random.randint(0, 20)) room_list = [\"Room_1_1_140\", \"Room_1_1_141\"] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count)", "flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox, 4) # add result", "question_index == 2: # requester send request to server room", "room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"] = util.combine_datetime(date, time) info[\"room\"] = room", "# body = {'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00'} response", "wx.StaticText(self, label=\"RESULT\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) font.MakeBold() result_label.SetFont(font) sizer.Add(result_label, proportion=0,", "{}\".format(info[\"start\"])) # print(\"end time = {}\".format(info[\"end\"])) if_real_time = self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if", "proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL, border=20) def OnClick(self, event, question_index): info = {}", "== 3: # requester send request to server name =", "= wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc1 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox1.Add(start_label,", "self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result widget # add count", "util.combine_datetime(end_date, end_time) # print(\"start time = {}\".format(info[\"start\"])) # print(\"end time", "question_list = [ \"1. How many people are in the", "result label self._add_result_label(vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"date_picker\"]", "count hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label,", "self.SetBackgroundColour(\"#BAB86C\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 =", "# https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self, name, parent_thread, parent_panel): threading.Thread.__init__(self, name=name) self._stopevent", "\"Room_1_1_140\", \"Room_1_1_141\", \"Room_1_1_142\", \"Room_1_1_143\", \"Room_1_1_144\", \"Room_1_1_150\", \"Room_1_1_184\"] room_combobox = wx.ComboBox(self,", "None self.info = info self._init_UI() def _init_UI(self): self.SetBackgroundColour(\"#BAB86C\") font =", "vbox1.Add(result_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) vbox.Add(hbox1, proportion=1, flag=wx.EXPAND|wx.ALL, border=10) vbox.Add(vbox1, proportion=9,", "info[\"question_index\"] = question_index self.info = info if if_real_time: if not", "flag=wx.TOP, border=5) main_vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox,", "canvas panel # canvas_panel = CanvasPanel(self) # vbox1.Add(canvas_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM,", "result_label.SetFont(font) sizer.Add(result_label, proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL, border=20) def OnClick(self, event, question_index): info", "parent_thread=threading.currentThread(), parent_panel=self) self.worker.start() print(\"start worker\") else: # first check if", "stop the worker if self.worker: # print(\"the worker has been", "self._add_confirm_button(vbox, 3) # add result label self._add_result_label(vbox) # add widget", "= room_combobox # add result widget # add count hbox", "body={}, params={}, METHOD=\"post\"): # https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\", url) print(\"body\", body) print(\"params\",", "question_index = 4 name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name", "are in the building?\", \"2. How many people are in", "add widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl # add", "proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"name_list\"] = namelb self.SetSizer(main_vbox)", "if question_index in [1, 2, 3, 4]: start_date = self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue()", "# print(self.drop_down_menu.GetValue()) print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0]) # st2 = wx.StaticText(self, label=combo_box.GetValue()) #", "else: # question_index == 5 if_real_time = False date =", "proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) self.SetSizer(vbox) # listen combo drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection, combo_box=drop_down_menu,", "count hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Room Count\") label.SetFont(self.font)", "\"end\": info[\"end\"]} # body = {'start': '2020-04-05 21:00:00', 'end': '2020-04-05", "name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else: # question_index", "question_index == 3: # requester send request to server name", "hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self, label=\"Name\") name_label.SetFont(self.font) hbox1.Add(name_label, proportion=2,", "rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for name in room_list: rlb.Append(name) elif", "add canvas panel # canvas_panel = CanvasPanel(self) # vbox1.Add(canvas_panel, proportion=9,", "self.parent_thread = parent_thread def run(self): while (not self._stopevent.is_set()) and self.parent_thread.is_alive():", "self._request_handle(url=url, body=body, METHOD=\"post\") # self.request_handle(url, body, METHOD=\"post\") try: response =", "occupancy_info: nlb.Append(name) elif question_index == 3: ## get ## url", "## get ## url = self.server + \"/people_building/\" body =", "4]: start_date = self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time = self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date = self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue()", "add name list roomlb = wx.ListBox(self) vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5)", "room_combobox = wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) vbox.Add(room_hbox, proportion=0,", "room elif question_index == 3: # requester send request to", "widget hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Utilization\") label.SetFont(self.font) hbox.Add(label,", "wx.StaticText(self, label=\"Datetime\") date_label.SetFont(self.font) dpc = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc =", "= str(0) room_list = [] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb", "dpc self.info_widget_dict[\"feeder\"][\"time_picker\"] = tpc self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result", "def _request_handle(self, url, body={}, params={}, METHOD=\"post\"): # https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\", url)", "hbox3.Add(cb, proportion=3, flag=wx.RIGHT|wx.TOP, border=5) vbox.Add(hbox3, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"feeder\"][\"start_date\"] =", "vbox = wx.BoxSizer(wx.VERTICAL) # datetime date_hbox = wx.BoxSizer(wx.HORIZONTAL) date_label =", "wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL,", "st1.SetFont(font) hbox1.Add(st1, proportion=2, flag=wx.RIGHT, border=10) # add drop down menu", "self.GetParent().SendSizeEvent() def _q3_panel(self): print(\"q3\") vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL)", "End end_label = wx.StaticText(self, label=\"END TIME\") end_label.SetFont(self.font) dpc2 = wx.adv.DatePickerCtrl(self,", "body=body, METHOD=\"post\") try: room_list = response['room'] count = str(len(room_list)) except:", "start_time) info[\"end\"] = util.combine_datetime(end_date, end_time) # print(\"start time = {}\".format(info[\"start\"]))", "request to server room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room) info[\"room\"] = room", "\"Room_1_1_144\", \"Room_1_1_150\", \"Room_1_1_184\"] room_combobox = wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP,", "flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) result_panel = ResultPanel(self) # result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM,", "self.server + \"/utilization/\" body = {\"room\": info[\"room\"], \"date\": info[\"date\"], #", "dict self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result widget # add", "proportion=2, flag=wx.TOP|wx.RIGHT, border=5) name_text_ctrl = wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter unique name')", "roomlb self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q4_panel(self): print(\"q4\") main_vbox", "flag=wx.ALL, border=5) # add name list namelb = wx.ListBox(self) main_vbox.Add(namelb,", "\"start\": info[\"start\"], \"end\": info[\"end\"], # 'start': '2020-04-05 21:00:00', 'end': '2020-04-05", "parent_thread, parent_panel): threading.Thread.__init__(self, name=name) self._stopevent = threading.Event() self.parent_panel = parent_panel", "str(response['count']) except: occu = str(0) ## received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif question_index", "requests import json from functools import partial class ReqeusterThread(threading.Thread): #", "occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"utilization_label\"]", "# print(self.parent_panel.info_widget_dict) # print(self.parent_panel.info) # chnage to real time end", "event, question_index): info = {} # handle date and time", "\"\"\" question_index => {1, 2, 3, 4} \"\"\" comfirm_btn =", "https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q5_panel(self): print(\"q5\") vbox = wx.BoxSizer(wx.VERTICAL) #", "# add widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl #", "= wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Room Count\") label.SetFont(self.font) hbox.Add(label, proportion=2,", "flag=wx.RIGHT, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # End end_label =", "get ## url = self.server + \"/people_room/\" body = {\"room\":", "21:10:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\") try: occu =", "print(self.drop_down_menu.GetValue()) print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0]) # st2 = wx.StaticText(self, label=combo_box.GetValue()) # st2.SetFont(font)", "import partial class ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self, name, parent_thread,", "name_text_ctrl.AppendText('Please enter unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) vbox.Add(hbox1, proportion=0,", "self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time = self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"] = util.combine_datetime(start_date, start_time) info[\"end\"] =", "occu = str(0) occupancy_info = [] ## received ## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu)", "flag=wx.TOP, border=5) # room_info = wx.TextCtrl(self) # room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP,", "occu_label = wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox,", "tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"] = cb # self.SetBackgroundColour(\"#000000\") # r = lambda:", "border=20) def OnClick(self, event, question_index): info = {} # handle", "def OnClick(self, event, question_index): info = {} # handle date", "# vbox1.Add(canvas_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) result_panel = ResultPanel(self) # result_panel.SetBackgroundColour(\"#000000\")", "sizer.Add(comfirm_btn, proportion=0, flag=wx.TOP|wx.LEFT, border=5) # self.Bind(wx.EVT_BUTTON, self.OnClick, comfirm_btn) self.Bind(wx.EVT_BUTTON, lambda", "ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(), parent_panel=self) self.worker.start() print(\"start worker\") else: # first check", "METHOD=\"post\") try: room_list = response['room'] count = str(len(room_list)) except: count", "{\"name\": info[\"name\"], # \"start_time\": info[\"start\"], # \"end_time\": info[\"end\"], \"time\": info[\"start\"],", "= {'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00'} response = self._request_handle(url=url,", "hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label, proportion=2,", "= lambda: random.randint(0,255) # color = '#%02X%02X%02X' % (r(),r(),r()) return", "= wx.StaticText(self, label=\"Name\") name_label.SetFont(self.font) hbox1.Add(name_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) name_text_ctrl =", "= wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) date_hbox.Add(date_label,", "flag=wx.TOP|wx.RIGHT, border=5) room_list = [ \"\", \"Room_1_1_140\", \"Room_1_1_141\", \"Room_1_1_142\", \"Room_1_1_143\",", "wx.StaticText(self, label=combo_box.GetValue()) # st2.SetFont(font) # sizer1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) class", "add result label # st2 = wx.StaticText(self, label='Result') # st2.SetFont(font)", "wx.StaticText(self, label=\"Room Count\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label =", "} response = self._request_handle(url=url, body=body, METHOD=\"post\") try: occu = str(response['count'])", "timeout) class RightPanel(wx.Panel): def __init__(self, parent, info={}): wx.Panel.__init__(self, parent=parent) self.drop_down_menu_ID", "self.server + \"/people_building/\" body = {\"start\": info[\"start\"], \"end\": info[\"end\"]} #", "self.OnClick, comfirm_btn) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, question_index), comfirm_btn) def _add_result_label(self,", "3, 4} \"\"\" comfirm_btn = wx.Button(self, id=-1, label=\"Confirm\") sizer.Add(comfirm_btn, proportion=0,", "{1, 2, 3, 4} \"\"\" comfirm_btn = wx.Button(self, id=-1, label=\"Confirm\")", "if r.status_code == 200: resp = r.json() print(resp) print(type(resp)) return", "200: resp = r.json() print(resp) print(type(resp)) return resp def _send_request(self,", "print(\"q2\") main_vbox = self.add_date_time_picker_layout() # Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL)", "= {} # handle date and time if question_index in", "question_index self.info = info if if_real_time: if not self.worker: self.worker", "url = self.server + \"/people_room/\" body = {\"room\": info[\"room\"], \"start\":", "import requests import json from functools import partial class ReqeusterThread(threading.Thread):", "info[\"date\"] = util.combine_datetime(date, time) info[\"room\"] = room # requester send", "border=5) # add name list namelb = wx.ListBox(self) main_vbox.Add(namelb, proportion=0,", "= \"{:.2f}\".format(response[\"utilization\"]*100) + \"%\" except: utilization = \"0%\" ## received##", "= wx.BoxSizer(wx.VERTICAL) # add result label # st2 = wx.StaticText(self,", "room_list: rlb.Append(name) elif question_index == 4: ## get ## url", "chnage to real time end = datetime.datetime.now() start = end", "room_info = wx.TextCtrl(self) # room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(room_hbox, proportion=0,", "self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result widget hbox = wx.BoxSizer(wx.HORIZONTAL)", "self.server = config.SERVER self._set_font() def _set_font(self): self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12)", "= wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox2.Add(end_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox2.Add(dpc2, proportion=3,", "wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc1 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox1.Add(start_label, proportion=2,", "partial(self.on_selection, combo_box=drop_down_menu, panel=result_panel)) def on_selection(self, event, combo_box, panel): # print(self.drop_down_menu.GetValue())", "border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def", "def join(self, timeout=None): self._stopevent.set() print(\"thread stop\") threading.Thread.join(self, timeout) class RightPanel(wx.Panel):", "occu = str(response['count']) occupancy_info = response['occupancy_info'] except: occu = str(0)", "= wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) # room_info =", "dpc2 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc2 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime)", "print(\"q1\") main_vbox = self.add_date_time_picker_layout() # confirm button self._add_confirm_button(main_vbox, 1) #", "print(self.parent_panel.info_widget_dict) # print(self.parent_panel.info) # chnage to real time end =", "proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox, 3) # add", "wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self, label=\"Name\") name_label.SetFont(self.font) hbox1.Add(name_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5)", "proportion=2, flag=wx.TOP|wx.RIGHT, border=5) room_list = [ \"\", \"Room_1_1_140\", \"Room_1_1_141\", \"Room_1_1_142\",", "font.SetPointSize(20) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) # add question", "url = self.server + \"question/4\" body = {\"name\": info[\"name\"], #", "# st2 = wx.StaticText(self, label='Result') # st2.SetFont(font) # vbox1.Add(st2, proportion=1,", "# add result label self._add_result_label(main_vbox) # add result widget hbox", "# https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q2_panel(self): print(\"q2\") main_vbox = self.add_date_time_picker_layout()", "room_combobox # add result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label =", "_add_result_label(self, sizer): result_label = wx.StaticText(self, label=\"RESULT\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20)", "wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) date_hbox.Add(date_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) date_hbox.Add(dpc, proportion=3, flag=wx.RIGHT,", "3) # add result label self._add_result_label(vbox) # add widget infomation", "body = {\"room\": info[\"room\"], \"start\": info[\"start\"], \"end\": info[\"end\"], # 'start':", "## get ## url = self.server + \"/utilization/\" body =", "import util import config import time import datetime import threading", "response['room'] count = str(len(room_list)) except: count = str(0) room_list =", "try: occu = str(response['count']) except: occu = str(0) ## received##", "button self._add_confirm_button(main_vbox, 4) # add result label self._add_result_label(main_vbox) # add", "wx.DefaultDateTime) tpc2 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox2.Add(end_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4)", "= wx.ListBox(self) main_vbox.Add(namelb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"name_list\"]", "add question label st1 = wx.StaticText(self, label='Question') st1.SetFont(font) hbox1.Add(st1, proportion=2,", "send request to server info[\"question_index\"] = question_index self.info = info", "label=\"Room Count\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self,", "= wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) # add question label st1", "hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Utilization\") label.SetFont(self.font) hbox.Add(label, proportion=2,", "= self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else: # question_index =", "import datetime import threading import requests import json from functools", "json.loads(response) utilization = \"{:.2f}\".format(response[\"utilization\"]*100) + \"%\" except: utilization = \"0%\"", "border=5) # room_info = wx.TextCtrl(self) # room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5)", "result label # st2 = wx.StaticText(self, label='Result') # st2.SetFont(font) #", "someone visited?\", \"4. What is the utilization of a specific", "self.server + \"/people_room/\" body = {\"room\": info[\"room\"], \"start\": info[\"start\"], \"end\":", "label=\"Confirm\") sizer.Add(comfirm_btn, proportion=0, flag=wx.TOP|wx.LEFT, border=5) # self.Bind(wx.EVT_BUTTON, self.OnClick, comfirm_btn) self.Bind(wx.EVT_BUTTON,", "utilization of a specific room?\" ] drop_down_menu = wx.ComboBox(self, choices=question_list)", "flag=wx.RIGHT, border=10) # add drop down menu question_list = [", "proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label", "confirm button self._add_confirm_button(main_vbox, 1) # add result label self._add_result_label(main_vbox) #", "vbox def _add_confirm_button(self, sizer, question_index): \"\"\" question_index => {1, 2,", "What is the utilization of a specific room?\" ] drop_down_menu", "roomlb = wx.ListBox(self) main_vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label", "label=\"Datetime\") date_label.SetFont(self.font) dpc = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc = wx.adv.TimePickerCtrl(self,", "border=5) vbox.Add(hbox2, proportion=0, flag=wx.ALL, border=5) # Real time box real_label", "hbox1.Add(dpc1, proportion=3, flag=wx.RIGHT, border=5) hbox1.Add(tpc1, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox1, proportion=0,", "self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear() decorate_panel = self._q_dict[q_idx] decorate_panel() def add_date_time_picker_layout(self): vbox =", "dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"] = tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"] = cb # self.SetBackgroundColour(\"#000000\") #", "pass elif question_index == 2: # requester send request to", "self._request_handle(url=url, body=body, METHOD=\"post\") try: occu = str(response['count']) occupancy_info = response['occupancy_info']", "been stop\") self.worker.join() self.worker = None self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear() decorate_panel =", "= json.loads(response) utilization = \"{:.2f}\".format(response[\"utilization\"]*100) + \"%\" except: utilization =", "def _q2_panel(self): print(\"q2\") main_vbox = self.add_date_time_picker_layout() # Room Info room_hbox", "proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(main_vbox)", "wx.BoxSizer(wx.VERTICAL) # add result label # st2 = wx.StaticText(self, label='Result')", "self._add_confirm_button(main_vbox, 2) # add result label self._add_result_label(main_vbox) # add widget", "widget infomation to dict self.info_widget_dict[\"feeder\"][\"date_picker\"] = dpc self.info_widget_dict[\"feeder\"][\"time_picker\"] = tpc", "flag=wx.ALL, border=5) # End end_label = wx.StaticText(self, label=\"END TIME\") end_label.SetFont(self.font)", "Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label = wx.StaticText(self, label=\"Room\") room_label.SetFont(self.font) room_hbox.Add(room_label,", "init_question_UI(self, q_idx): # clean the panel for child in self.GetChildren():", "tpc2 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox2.Add(end_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox2.Add(dpc2,", "## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb = self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear() for name in occupancy_info:", "font.MakeBold() result_label.SetFont(font) sizer.Add(result_label, proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL, border=20) def OnClick(self, event, question_index):", "proportion=8, flag=wx.TOP, border=5) vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm button", "Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label = wx.StaticText(self, label=\"Room\") room_label.SetFont(self.font)", "if the worker is working if self.worker: self.worker.join() self.worker =", "flag=wx.RIGHT, border=5) hbox1.Add(tpc1, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5)", "panel): # print(self.drop_down_menu.GetValue()) print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0]) # st2 = wx.StaticText(self, label=combo_box.GetValue())", "proportion=8, flag=wx.TOP, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm button", "import wx import wx.adv import random import util import config", "hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm", "functools import partial class ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self, name,", "result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) vbox.Add(hbox1, proportion=1, flag=wx.EXPAND|wx.ALL, border=10) vbox.Add(vbox1,", "elif question_index == 4: ## get ## url = self.server", "self.request_handle(url, body, METHOD=\"post\") try: response = json.loads(response) utilization = \"{:.2f}\".format(response[\"utilization\"]*100)", "= wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc2 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox2.Add(end_label,", "url = self.server + \"/people_building/\" body = {\"start\": info[\"start\"], \"end\":", "border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox, 3)", "info[\"name\"] = name else: # question_index = 4 name =", "\"3\": self._q3_panel, # \"4\": self._q4_panel, \"4\": self._q5_panel,} self.info_widget_dict = {\"feeder\":", "widget # add count hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self,", "wx.BoxSizer(wx.HORIZONTAL) date_label = wx.StaticText(self, label=\"Datetime\") date_label.SetFont(self.font) dpc = wx.adv.DatePickerCtrl(self, -1,", "-1, wx.DefaultDateTime) hbox1.Add(start_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox1.Add(dpc1, proportion=3, flag=wx.RIGHT, border=5)", "self.parent_thread.is_alive(): print(\"hello\") # print(self.parent_panel.info_widget_dict) # print(self.parent_panel.info) # chnage to real", "= self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room) info[\"room\"] = room elif question_index == 3:", "parent=parent) self.drop_down_menu_ID = None self.result_visual_ID = None self.info = info", "proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox2, proportion=0, flag=wx.ALL, border=5) # Real time", "= wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5)", "## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for name", "print(room) info[\"room\"] = room elif question_index == 3: # requester", "wx.DefaultDateTime) date_hbox.Add(date_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) date_hbox.Add(dpc, proportion=3, flag=wx.RIGHT, border=5) date_hbox.Add(tpc,", "self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for name in room_list: rlb.Append(name) elif question_index ==", "= wx.StaticText(self, label='Question') st1.SetFont(font) hbox1.Add(st1, proportion=2, flag=wx.RIGHT, border=10) # add", "room_list = [\"Room_1_1_140\", \"Room_1_1_141\"] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb =", "to dict self.info_widget_dict[\"feeder\"][\"date_picker\"] = dpc self.info_widget_dict[\"feeder\"][\"time_picker\"] = tpc self.info_widget_dict[\"feeder\"][\"room_select\"] =", "'end': '2020-04-05 21:10:00'} response = self._request_handle(url=url, body=body, METHOD=\"post\") try: occu", "## received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def _q1_panel(self): print(\"q1\") main_vbox = self.add_date_time_picker_layout() #", "first check if the worker is working if self.worker: self.worker.join()", "return resp def _send_request(self, info): question_index = int(info[\"question_index\"]) if question_index", "self._add_result_label(vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"date_picker\"] = dpc", "border=5) room_list = [ \"\", \"Room_1_1_140\", \"Room_1_1_141\", \"Room_1_1_142\", \"Room_1_1_143\", \"Room_1_1_144\",", "hbox3 = wx.BoxSizer(wx.HORIZONTAL) # Start start_label = wx.StaticText(self, label=\"START TIME\")", "\"Room_1_1_184\"] room_combobox = wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) #", "to server pass elif question_index == 2: # requester send", "url, body={}, params={}, METHOD=\"post\"): # https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\", url) print(\"body\", body)", "server room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room) info[\"room\"] = room elif question_index", "info={}): wx.Panel.__init__(self, parent=parent) self.drop_down_menu_ID = None self.result_visual_ID = None self.info", "= self.server + \"/utilization/\" body = {\"room\": info[\"room\"], \"date\": info[\"date\"],", "= tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"] = cb # self.SetBackgroundColour(\"#000000\") # r =", "= {\"feeder\": {}, \"consumer\": {}} self.worker = None self.server =", "flag=wx.TOP, border=5) main_vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox,", "wx.StaticText(self, label=\"START TIME\") start_label.SetFont(self.font) dpc1 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc1", "= self.server + \"/person_room/\" body = {\"name\": info[\"name\"], \"start\": info[\"start\"],", "vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # End end_label = wx.StaticText(self, label=\"END", "border=5) # Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label = wx.StaticText(self,", "proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2,", "to server name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else:", "= int(info[\"question_index\"]) if question_index == 1: ## get ## url", "= str(random.randint(0, 20)) room_list = [\"Room_1_1_140\", \"Room_1_1_141\"] ## received ##", "wx.TextCtrl(self) # room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5)", "5 if_real_time = False date = self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time = self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue()", "flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.SetSizer(main_vbox)", "question_index == 2: ## get ## url = self.server +", "4: ## get ## url = self.server + \"question/4\" body", "# listen combo drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection, combo_box=drop_down_menu, panel=result_panel)) def on_selection(self, event,", "vbox.Add(date_hbox, proportion=0, flag=wx.ALL, border=5) # Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL)", "\"4. Which room has someone visited?\", \"4. What is the", "label='Result') # st2.SetFont(font) # vbox1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) # add", "label self._add_result_label(vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"] =", "widget hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label,", "request to server pass elif question_index == 2: # requester", "METHOD=\"post\") count = str(random.randint(0, 20)) room_list = [\"Room_1_1_140\", \"Room_1_1_141\"] ##", "self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear() for name in occupancy_info: nlb.Append(name) elif question_index ==", "https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q2_panel(self): print(\"q2\") main_vbox = self.add_date_time_picker_layout() #", "https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q3_panel(self): print(\"q3\") vbox = self.add_date_time_picker_layout() hbox1", "down menu question_list = [ \"1. How many people are", "METHOD=\"post\") try: response = json.loads(response) utilization = \"{:.2f}\".format(response[\"utilization\"]*100) + \"%\"", "# add count hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Room", "st1 = wx.StaticText(self, label='Question') st1.SetFont(font) hbox1.Add(st1, proportion=2, flag=wx.RIGHT, border=10) #", "on_selection(self, event, combo_box, panel): # print(self.drop_down_menu.GetValue()) print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0]) # st2", "= wx.BoxSizer(wx.HORIZONTAL) # Start start_label = wx.StaticText(self, label=\"START TIME\") start_label.SetFont(self.font)", "[] ## received ## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb = self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear() for", "result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font)", "1) # add result label self._add_result_label(main_vbox) # add result widget", "room_hbox.Add(room_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) room_list = [ \"\", \"Room_1_1_140\", \"Room_1_1_141\",", "from functools import partial class ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self,", "self.font.SetPointSize(12) self.font.MakeBold() def init_question_UI(self, q_idx): # clean the panel for", "{\"feeder\": {}, \"consumer\": {}} self.worker = None self.server = config.SERVER", "border=5) # confirm button self._add_confirm_button(main_vbox, 4) # add result label", "3: ## get ## url = self.server + \"/person_room/\" body", "received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for name in", "requests.post(url, data=body) else: r = requests.get(url, params=params) print(r.status_code) if r.status_code", "= self._q_dict[q_idx] decorate_panel() def add_date_time_picker_layout(self): vbox = wx.BoxSizer(wx.VERTICAL) hbox1 =", "hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"utilization_label\"] =", "label=\"REAL TIME\") real_label.SetFont(self.font) cb = wx.CheckBox(self) hbox3.Add(real_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4)", "= requests.post(url, data=body) else: r = requests.get(url, params=params) print(r.status_code) if", "response = self._request_handle(url=url, body=body, METHOD=\"post\") try: occu = str(response['count']) except:", "= self._request_handle(url=url, body=body, METHOD=\"post\") try: occu = str(response['count']) except: occu", "# confirm button self._add_confirm_button(vbox, 5) # add result label self._add_result_label(vbox)", "{\"room\": info[\"room\"], \"date\": info[\"date\"], # 'date': '2020-04-05 20:00:00' } response", "flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox, 2) # add result", "flag=wx.RIGHT|wx.TOP, border=4) hbox3.Add(cb, proportion=3, flag=wx.RIGHT|wx.TOP, border=5) vbox.Add(hbox3, proportion=0, flag=wx.ALL, border=5)", "self.worker = None self.server = config.SERVER self._set_font() def _set_font(self): self.font", "flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"name_list\"] = namelb self.SetSizer(main_vbox) #", "name_label.SetFont(self.font) hbox1.Add(name_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) name_text_ctrl = wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter", "self._q_dict = {\"1\": self._q1_panel, \"2\": self._q2_panel, \"3\": self._q3_panel, # \"4\":", "print(\"hello\") # print(self.parent_panel.info_widget_dict) # print(self.parent_panel.info) # chnage to real time", "datetime import threading import requests import json from functools import", "body=body, METHOD=\"post\") count = str(random.randint(0, 20)) room_list = [\"Room_1_1_140\", \"Room_1_1_141\"]", "add name list namelb = wx.ListBox(self) main_vbox.Add(namelb, proportion=0, flag=wx.ALL, border=5)", "= name else: # question_index = 4 name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue()", "3, 4]: start_date = self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time = self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date =", "label self._add_result_label(vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"date_picker\"] =", "run(self): while (not self._stopevent.is_set()) and self.parent_thread.is_alive(): print(\"hello\") # print(self.parent_panel.info_widget_dict) #", "label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self, label=\"__\")", "start_label.SetFont(self.font) dpc1 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc1 = wx.adv.TimePickerCtrl(self, -1,", "sizer, question_index): \"\"\" question_index => {1, 2, 3, 4} \"\"\"", "server info[\"question_index\"] = question_index self.info = info if if_real_time: if", "if METHOD == \"post\": r = requests.post(url, data=body) else: r", "room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) # room_info = wx.TextCtrl(self) # room_hbox.Add(room_combobox,", "= wx.StaticText(self, label=\"REAL TIME\") real_label.SetFont(self.font) cb = wx.CheckBox(self) hbox3.Add(real_label, proportion=2,", "_q2_panel(self): print(\"q2\") main_vbox = self.add_date_time_picker_layout() # Room Info room_hbox =", "border=5) name_text_ctrl = wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter unique name') hbox1.Add(name_text_ctrl, proportion=8,", "worker\") else: # first check if the worker is working", "main_vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox, 4) #", "self.info_widget_dict = {\"feeder\": {}, \"consumer\": {}} self.worker = None self.server", "info[\"end\"]} # body = {'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00'}", "flag=wx.RIGHT, border=5) hbox2.Add(tpc2, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox2, proportion=0, flag=wx.ALL, border=5)", "## url = self.server + \"/utilization/\" body = {\"room\": info[\"room\"],", "utilization = \"0%\" ## received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def _q1_panel(self): print(\"q1\") main_vbox", "[ \"1. How many people are in the building?\", \"2.", "class ResultPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # self._init_UI() self._q_dict", "info[\"name\"], \"start\": info[\"start\"], \"end\": info[\"end\"], # 'start': '2020-04-05 21:00:00', 'end':", "result label self._add_result_label(main_vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"room_select\"]", "name_text_ctrl.AppendText('Please enter unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(hbox1, proportion=0,", "print(\"body\", body) print(\"params\", params) resp = {} if METHOD ==", "2: ## get ## url = self.server + \"/people_room/\" body", "label st1 = wx.StaticText(self, label='Question') st1.SetFont(font) hbox1.Add(st1, proportion=2, flag=wx.RIGHT, border=10)", "= info if if_real_time: if not self.worker: self.worker = ReqeusterThread(name=\"question_{}_requester\".format(question_index),", "\"Room_1_1_142\", \"Room_1_1_143\", \"Room_1_1_144\", \"Room_1_1_150\", \"Room_1_1_184\"] room_combobox = wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox,", "= {}\".format(info[\"start\"])) # print(\"end time = {}\".format(info[\"end\"])) if_real_time = self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue()", "room has someone visited?\", \"4. What is the utilization of", "self._add_result_label(main_vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl", "= util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0) def join(self, timeout=None): self._stopevent.set() print(\"thread stop\")", "def run(self): while (not self._stopevent.is_set()) and self.parent_thread.is_alive(): print(\"hello\") # print(self.parent_panel.info_widget_dict)", "How many people are in the building?\", \"2. How many", "stop\") threading.Thread.join(self, timeout) class RightPanel(wx.Panel): def __init__(self, parent, info={}): wx.Panel.__init__(self,", "# self.request_handle(url, body, METHOD=\"post\") try: response = json.loads(response) utilization =", "cb # self.SetBackgroundColour(\"#000000\") # r = lambda: random.randint(0,255) # color", "border=1) class ResultPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # self._init_UI()", "Which room has someone visited?\", \"4. What is the utilization", "# add count hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\")", "= [ \"1. How many people are in the building?\",", "wx.BoxSizer(wx.HORIZONTAL) # add question label st1 = wx.StaticText(self, label='Question') st1.SetFont(font)", "st2.SetFont(font) # sizer1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) class ResultPanel(wx.Panel): def __init__(self,", "received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def _q1_panel(self): print(\"q1\") main_vbox = self.add_date_time_picker_layout() # confirm", "someone?\", # \"4. Which room has someone visited?\", \"4. What", "= namelb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q3_panel(self): print(\"q3\")", "main_vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb", "# \"4\": self._q4_panel, \"4\": self._q5_panel,} self.info_widget_dict = {\"feeder\": {}, \"consumer\":", "requester send request to server room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room) info[\"room\"]", "# add name list namelb = wx.ListBox(self) main_vbox.Add(namelb, proportion=0, flag=wx.ALL,", "'#%02X%02X%02X' % (r(),r(),r()) return vbox def _add_confirm_button(self, sizer, question_index): \"\"\"", "[1, 2, 3, 4]: start_date = self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time = self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue()", "info[\"start\"], } response = self._request_handle(url=url, body=body, METHOD=\"post\") count = str(random.randint(0,", "\"/people_building/\" body = {\"start\": info[\"start\"], \"end\": info[\"end\"]} # body =", "print(\"params\", params) resp = {} if METHOD == \"post\": r", "= occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent()", "self._add_confirm_button(vbox, 5) # add result label self._add_result_label(vbox) # add widget", "wx.StaticText(self, label='Question') st1.SetFont(font) hbox1.Add(st1, proportion=2, flag=wx.RIGHT, border=10) # add drop", "datetime date_hbox = wx.BoxSizer(wx.HORIZONTAL) date_label = wx.StaticText(self, label=\"Datetime\") date_label.SetFont(self.font) dpc", "self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, question_index), comfirm_btn) def _add_result_label(self, sizer): result_label", "= {\"1\": self._q1_panel, \"2\": self._q2_panel, \"3\": self._q3_panel, # \"4\": self._q4_panel,", "## received ## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb = self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear() for name", "proportion=2, flag=wx.RIGHT|wx.TOP, border=4) date_hbox.Add(dpc, proportion=3, flag=wx.RIGHT, border=5) date_hbox.Add(tpc, proportion=3, flag=wx.RIGHT,", "end - datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"] = util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"] = util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info)", "'2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00' } response = self._request_handle(url=url, body=body,", "tpc = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) date_hbox.Add(date_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) date_hbox.Add(dpc,", "body = {'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00'} response =", "parent): wx.Panel.__init__(self, parent) # self._init_UI() self._q_dict = {\"1\": self._q1_panel, \"2\":", "timeout=None): self._stopevent.set() print(\"thread stop\") threading.Thread.join(self, timeout) class RightPanel(wx.Panel): def __init__(self,", "question_index == 1: # requester send request to server pass", "parent_thread def run(self): while (not self._stopevent.is_set()) and self.parent_thread.is_alive(): print(\"hello\") #", "'2020-04-05 21:10:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\") try: occu", "in room_list: rlb.Append(name) elif question_index == 5: ## get ##", "\"0%\" ## received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def _q1_panel(self): print(\"q1\") main_vbox = self.add_date_time_picker_layout()", "= info self._init_UI() def _init_UI(self): self.SetBackgroundColour(\"#BAB86C\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20)", "namelb = wx.ListBox(self) main_vbox.Add(namelb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label", "main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name list roomlb =", "many people are in a specific room?\", \"3. Where is", "proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox2.Add(dpc2, proportion=3, flag=wx.RIGHT, border=5) hbox2.Add(tpc2, proportion=3, flag=wx.RIGHT,", "to server info[\"question_index\"] = question_index self.info = info if if_real_time:", "occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) #", "for child in self.GetChildren(): child.Destroy() # stop the worker if", "info[\"name\"] = name else: # question_index == 5 if_real_time =", "flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox, 3) # add result", "wx.ComboBox(self, choices=question_list) hbox1.Add(drop_down_menu, proportion=8, flag=wx.TOP, border=5) vbox1 = wx.BoxSizer(wx.VERTICAL) #", "event, combo_box, panel): # print(self.drop_down_menu.GetValue()) print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0]) # st2 =", "threading.Event() self.parent_panel = parent_panel self.parent_thread = parent_thread def run(self): while", "label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font)", "def _q3_panel(self): print(\"q3\") vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label", "wx.ListBox(self) vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] =", "rlb.Append(name) elif question_index == 4: ## get ## url =", "_send_request(self, info): question_index = int(info[\"question_index\"]) if question_index == 1: ##", "self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else: # question_index = 4", "+ \"/people_building/\" body = {\"start\": info[\"start\"], \"end\": info[\"end\"]} # body", "None self.server = config.SERVER self._set_font() def _set_font(self): self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)", "self._stopevent.wait(5.0) def join(self, timeout=None): self._stopevent.set() print(\"thread stop\") threading.Thread.join(self, timeout) class", "border=5) vbox1 = wx.BoxSizer(wx.VERTICAL) # add result label # st2", "get ## url = self.server + \"/people_building/\" body = {\"start\":", "menu question_list = [ \"1. How many people are in", "ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self, name, parent_thread, parent_panel): threading.Thread.__init__(self, name=name)", "room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm", "= None self.result_visual_ID = None self.info = info self._init_UI() def", "in a specific room?\", \"3. Where is someone?\", # \"4.", "except: utilization = \"0%\" ## received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def _q1_panel(self): print(\"q1\")", "name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) #", "METHOD=\"post\") # self.request_handle(url, body, METHOD=\"post\") try: response = json.loads(response) utilization", "= self.server + \"question/4\" body = {\"name\": info[\"name\"], # \"start_time\":", "name in room_list: rlb.Append(name) elif question_index == 5: ## get", "body = {\"start\": info[\"start\"], \"end\": info[\"end\"]} # body = {'start':", "hbox2.Add(end_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox2.Add(dpc2, proportion=3, flag=wx.RIGHT, border=5) hbox2.Add(tpc2, proportion=3,", "= ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(), parent_panel=self) self.worker.start() print(\"start worker\") else: # first", "None self.result_visual_ID = None self.info = info self._init_UI() def _init_UI(self):", "flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"utilization_label\"] = occu_label self.SetSizer(vbox)", "if self.worker: # print(\"the worker has been stop\") self.worker.join() self.worker", "name in room_list: rlb.Append(name) elif question_index == 4: ## get", "= room elif question_index == 3: # requester send request", "proportion=3, flag=wx.RIGHT, border=5) vbox.Add(date_hbox, proportion=0, flag=wx.ALL, border=5) # Room Info", "self._add_result_label(main_vbox) # add result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label =", "'2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00'} response = self._request_handle(url=url, body=body, METHOD=\"post\")", "border=5) hbox1.Add(tpc1, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) #", "label=\"END TIME\") end_label.SetFont(self.font) dpc2 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc2 =", "= name else: # question_index == 5 if_real_time = False", "= self._request_handle(url=url, body=body, METHOD=\"post\") try: occu = str(response['count']) occupancy_info =", "list namelb = wx.ListBox(self) main_vbox.Add(namelb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] =", "response['occupancy_info'] except: occu = str(0) occupancy_info = [] ## received", "font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL)", "add result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Utilization\")", "= self._request_handle(url=url, body=body, METHOD=\"post\") count = str(random.randint(0, 20)) room_list =", "hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Room Count\") label.SetFont(self.font) hbox.Add(label,", "proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox, 4) # add", "response = self._request_handle(url=url, body=body, METHOD=\"post\") # self.request_handle(url, body, METHOD=\"post\") try:", "self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def _q1_panel(self): print(\"q1\") main_vbox = self.add_date_time_picker_layout() # confirm button", "add widget infomation to dict self.info_widget_dict[\"feeder\"][\"date_picker\"] = dpc self.info_widget_dict[\"feeder\"][\"time_picker\"] =", "import json from functools import partial class ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html", "= None self._send_request(info) def _request_handle(self, url, body={}, params={}, METHOD=\"post\"): #", "proportion=3, flag=wx.RIGHT|wx.TOP, border=5) vbox.Add(hbox3, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"feeder\"][\"start_date\"] = dpc1", "config import time import datetime import threading import requests import", "event: self.OnClick(event, question_index), comfirm_btn) def _add_result_label(self, sizer): result_label = wx.StaticText(self,", "__init__(self, name, parent_thread, parent_panel): threading.Thread.__init__(self, name=name) self._stopevent = threading.Event() self.parent_panel", "\"Room_1_1_141\"] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for", "print(\"q3\") vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self,", "_set_font(self): self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12) self.font.MakeBold() def init_question_UI(self, q_idx): #", "response = self._request_handle(url=url, body=body, METHOD=\"post\") count = str(random.randint(0, 20)) room_list", "json from functools import partial class ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def", "is someone?\", # \"4. Which room has someone visited?\", \"4.", "\"consumer\": {}} self.worker = None self.server = config.SERVER self._set_font() def", "str(len(room_list)) except: count = str(0) room_list = [] ## received", "question_index): \"\"\" question_index => {1, 2, 3, 4} \"\"\" comfirm_btn", "import wx.adv import random import util import config import time", "info[\"room\"] = room elif question_index == 3: # requester send", "except: occu = str(0) ## received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif question_index ==", "in self.GetChildren(): child.Destroy() # stop the worker if self.worker: #", "params=params) print(r.status_code) if r.status_code == 200: resp = r.json() print(resp)", "end_time) # print(\"start time = {}\".format(info[\"start\"])) # print(\"end time =", "tpc self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result widget hbox =", "# r = lambda: random.randint(0,255) # color = '#%02X%02X%02X' %", "nlb.Clear() for name in occupancy_info: nlb.Append(name) elif question_index == 3:", "st2.SetFont(font) # vbox1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) # add canvas panel", "decorate_panel = self._q_dict[q_idx] decorate_panel() def add_date_time_picker_layout(self): vbox = wx.BoxSizer(wx.VERTICAL) hbox1", "not self.worker: self.worker = ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(), parent_panel=self) self.worker.start() print(\"start worker\")", "self._request_handle(url=url, body=body, METHOD=\"post\") count = str(random.randint(0, 20)) room_list = [\"Room_1_1_140\",", "label=\"START TIME\") start_label.SetFont(self.font) dpc1 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc1 =", "self.info_widget_dict[\"feeder\"][\"time_picker\"] = tpc self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result widget", "border=5) # Real time box real_label = wx.StaticText(self, label=\"REAL TIME\")", "room?\" ] drop_down_menu = wx.ComboBox(self, choices=question_list) hbox1.Add(drop_down_menu, proportion=8, flag=wx.TOP, border=5)", "r = lambda: random.randint(0,255) # color = '#%02X%02X%02X' % (r(),r(),r())", "= occu_label self.info_widget_dict[\"consumer\"][\"name_list\"] = namelb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent()", "1: # requester send request to server pass elif question_index", "= wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label =", "self.font.MakeBold() def init_question_UI(self, q_idx): # clean the panel for child", "def add_date_time_picker_layout(self): vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 =", "# \"4. Which room has someone visited?\", \"4. What is", "add result label self._add_result_label(vbox) # add widget infomation to dict", "occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def", "real_label.SetFont(self.font) cb = wx.CheckBox(self) hbox3.Add(real_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox3.Add(cb, proportion=3,", "20)) room_list = [\"Room_1_1_140\", \"Room_1_1_141\"] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb", "handle date and time if question_index in [1, 2, 3,", "confirm button self._add_confirm_button(main_vbox, 4) # add result label self._add_result_label(main_vbox) #", "hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add", "time = {}\".format(info[\"end\"])) if_real_time = self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if question_index == 1:", "= self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time = self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"] = util.combine_datetime(start_date, start_time) info[\"end\"]", "== 5 if_real_time = False date = self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time =", "info): question_index = int(info[\"question_index\"]) if question_index == 1: ## get", "flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT,", "wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL,", "flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"utilization_label\"] = occu_label self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent()", "button self._add_confirm_button(vbox, 5) # add result label self._add_result_label(vbox) # add", "self.parent_panel.info[\"end\"] = util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0) def join(self, timeout=None): self._stopevent.set() print(\"thread", "self.parent_panel = parent_panel self.parent_thread = parent_thread def run(self): while (not", "= r.json() print(resp) print(type(resp)) return resp def _send_request(self, info): question_index", "= wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL) # Start", "comfirm_btn) def _add_result_label(self, sizer): result_label = wx.StaticText(self, label=\"RESULT\") font =", "end_label.SetFont(self.font) dpc2 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc2 = wx.adv.TimePickerCtrl(self, -1,", "{} if METHOD == \"post\": r = requests.post(url, data=body) else:", "# add drop down menu question_list = [ \"1. How", "self._q2_panel, \"3\": self._q3_panel, # \"4\": self._q4_panel, \"4\": self._q5_panel,} self.info_widget_dict =", "= False date = self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time = self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room =", "check if the worker is working if self.worker: self.worker.join() self.worker", "add result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\")", "occu_label self.info_widget_dict[\"consumer\"][\"name_list\"] = namelb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def", "info[\"start\"], \"end\": info[\"end\"]} # body = {'start': '2020-04-05 21:00:00', 'end':", "resp def _send_request(self, info): question_index = int(info[\"question_index\"]) if question_index ==", "print(self.parent_panel.info) # chnage to real time end = datetime.datetime.now() start", "hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add", "send request to server room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room) info[\"room\"] =", "self._q_dict[q_idx] decorate_panel() def add_date_time_picker_layout(self): vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL)", "= self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time = self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date = self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time =", "= {\"start\": info[\"start\"], \"end\": info[\"end\"]} # body = {'start': '2020-04-05", "proportion=0, flag=wx.TOP|wx.LEFT, border=5) # self.Bind(wx.EVT_BUTTON, self.OnClick, comfirm_btn) self.Bind(wx.EVT_BUTTON, lambda event:", "self.Fit() self.GetParent().SendSizeEvent() def _q5_panel(self): print(\"q5\") vbox = wx.BoxSizer(wx.VERTICAL) # datetime", "proportion=1, flag=wx.ALIGN_CENTER, border=1) # add canvas panel # canvas_panel =", "self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q4_panel(self):", "elif question_index == 5: ## get ## url = self.server", "self.worker = None self._send_request(info) def _request_handle(self, url, body={}, params={}, METHOD=\"post\"):", "border=5) self.info_widget_dict[\"feeder\"][\"start_date\"] = dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"] = tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"] = dpc2", "the utilization of a specific room?\" ] drop_down_menu = wx.ComboBox(self,", "get ## url = self.server + \"question/4\" body = {\"name\":", "def __init__(self, parent): wx.Panel.__init__(self, parent) # self._init_UI() self._q_dict = {\"1\":", "try: response = json.loads(response) utilization = \"{:.2f}\".format(response[\"utilization\"]*100) + \"%\" except:", "result widget hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Utilization\") label.SetFont(self.font)", "roomlb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q5_panel(self): print(\"q5\") vbox", "# End end_label = wx.StaticText(self, label=\"END TIME\") end_label.SetFont(self.font) dpc2 =", "the panel for child in self.GetChildren(): child.Destroy() # stop the", "border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # End end_label = wx.StaticText(self,", "hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] =", "flag=wx.TOP, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox,", "room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label = wx.StaticText(self, label=\"Room\") room_label.SetFont(self.font) room_hbox.Add(room_label, proportion=2,", "time box real_label = wx.StaticText(self, label=\"REAL TIME\") real_label.SetFont(self.font) cb =", "server pass elif question_index == 2: # requester send request", "== 5: ## get ## url = self.server + \"/utilization/\"", "real time end = datetime.datetime.now() start = end - datetime.timedelta(minutes=1)", "vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"utilization_label\"] = occu_label self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small", "proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"utilization_label\"] = occu_label self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit()", "self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"] = util.combine_datetime(start_date, start_time) info[\"end\"] = util.combine_datetime(end_date, end_time) #", "name list roomlb = wx.ListBox(self) vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"]", "threading.Thread.__init__(self, name=name) self._stopevent = threading.Event() self.parent_panel = parent_panel self.parent_thread =", "border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small", "proportion=3, flag=wx.RIGHT, border=5) hbox2.Add(tpc2, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox2, proportion=0, flag=wx.ALL,", "label # st2 = wx.StaticText(self, label='Result') # st2.SetFont(font) # vbox1.Add(st2,", "border=10) vbox.Add(vbox1, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) self.SetSizer(vbox) # listen combo drop_down_menu.Bind(wx.EVT_COMBOBOX,", "wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) font.MakeBold() result_label.SetFont(font) sizer.Add(result_label, proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL, border=20) def OnClick(self,", "= self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"] = util.combine_datetime(start_date, start_time) info[\"end\"] = util.combine_datetime(end_date, end_time)", "room_combobox # add result widget # add count hbox =", "question_index == 5 if_real_time = False date = self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time", "border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name list namelb", "border=4) hbox2.Add(dpc2, proportion=3, flag=wx.RIGHT, border=5) hbox2.Add(tpc2, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox2,", "self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"] = util.combine_datetime(date, time) info[\"room\"] =", "print(\"q5\") vbox = wx.BoxSizer(wx.VERTICAL) # datetime date_hbox = wx.BoxSizer(wx.HORIZONTAL) date_label", "RightPanel(wx.Panel): def __init__(self, parent, info={}): wx.Panel.__init__(self, parent=parent) self.drop_down_menu_ID = None", "vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name list roomlb =", "self.parent_panel.info[\"start\"] = util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"] = util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0) def join(self,", "flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox, 5) # add result", "start_date = self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time = self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date = self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time", "def _set_font(self): self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12) self.font.MakeBold() def init_question_UI(self, q_idx):", "request to server info[\"question_index\"] = question_index self.info = info if", "2, 3, 4]: start_date = self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time = self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date", "label = wx.StaticText(self, label=\"Utilization\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label", "proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox, 2) # add", "elif question_index == 2: # requester send request to server", "4) # add result label self._add_result_label(main_vbox) # add widget infomation", "is working if self.worker: self.worker.join() self.worker = None self._send_request(info) def", "vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox, 5) #", "wx.StaticText(self, label='Result') # st2.SetFont(font) # vbox1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) #", "lambda event: self.OnClick(event, question_index), comfirm_btn) def _add_result_label(self, sizer): result_label =", "# print(\"start time = {}\".format(info[\"start\"])) # print(\"end time = {}\".format(info[\"end\"]))", "# confirm button self._add_confirm_button(main_vbox, 4) # add result label self._add_result_label(main_vbox)", "= wx.BoxSizer(wx.HORIZONTAL) room_label = wx.StaticText(self, label=\"Room\") room_label.SetFont(self.font) room_hbox.Add(room_label, proportion=2, flag=wx.TOP|wx.RIGHT,", "+ \"%\" except: utilization = \"0%\" ## received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def", "requester send request to server info[\"question_index\"] = question_index self.info =", "drop_down_menu = wx.ComboBox(self, choices=question_list) hbox1.Add(drop_down_menu, proportion=8, flag=wx.TOP, border=5) vbox1 =", "info self._init_UI() def _init_UI(self): self.SetBackgroundColour(\"#BAB86C\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) vbox", "== 1: # requester send request to server pass elif", "{}} self.worker = None self.server = config.SERVER self._set_font() def _set_font(self):", "self.GetParent().SendSizeEvent() def _q2_panel(self): print(\"q2\") main_vbox = self.add_date_time_picker_layout() # Room Info", "{\"start\": info[\"start\"], \"end\": info[\"end\"]} # body = {'start': '2020-04-05 21:00:00',", "main_vbox = self.add_date_time_picker_layout() # Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label", "flag=wx.RIGHT|wx.TOP, border=5) vbox.Add(hbox3, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"feeder\"][\"start_date\"] = dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"]", "room_combobox = wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) # room_info", "-1, wx.DefaultDateTime) tpc1 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox1.Add(start_label, proportion=2, flag=wx.RIGHT|wx.TOP,", "wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) # room_info = wx.TextCtrl(self)", "body = {\"name\": info[\"name\"], # \"start_time\": info[\"start\"], # \"end_time\": info[\"end\"],", "proportion=1, flag=wx.ALIGN_CENTER, border=1) class ResultPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent)", "occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def", "question label st1 = wx.StaticText(self, label='Question') st1.SetFont(font) hbox1.Add(st1, proportion=2, flag=wx.RIGHT,", "# 'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00' } response =", "= wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3 =", "self.info_widget_dict[\"feeder\"][\"start_time\"] = tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"] = dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"] = tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"]", "self.info_widget_dict[\"feeder\"][\"end_date\"] = dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"] = tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"] = cb #", "# add question label st1 = wx.StaticText(self, label='Question') st1.SetFont(font) hbox1.Add(st1,", "def __init__(self, parent, info={}): wx.Panel.__init__(self, parent=parent) self.drop_down_menu_ID = None self.result_visual_ID", "color = '#%02X%02X%02X' % (r(),r(),r()) return vbox def _add_confirm_button(self, sizer,", "# add result label # st2 = wx.StaticText(self, label='Result') #", "label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5)", "self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time = self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"] = util.combine_datetime(date,", "def init_question_UI(self, q_idx): # clean the panel for child in", "vbox1 = wx.BoxSizer(wx.VERTICAL) # add result label # st2 =", "namelb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q3_panel(self): print(\"q3\") vbox", "hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label,", "self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q4_panel(self): print(\"q4\") main_vbox =", "str(response['count']) occupancy_info = response['occupancy_info'] except: occu = str(0) occupancy_info =", "= wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12) self.font.MakeBold() def init_question_UI(self, q_idx): # clean the", "def _q1_panel(self): print(\"q1\") main_vbox = self.add_date_time_picker_layout() # confirm button self._add_confirm_button(main_vbox,", "r = requests.post(url, data=body) else: r = requests.get(url, params=params) print(r.status_code)", "info[\"start\"] = util.combine_datetime(start_date, start_time) info[\"end\"] = util.combine_datetime(end_date, end_time) # print(\"start", "question_index == 3: ## get ## url = self.server +", "# Start start_label = wx.StaticText(self, label=\"START TIME\") start_label.SetFont(self.font) dpc1 =", "# color = '#%02X%02X%02X' % (r(),r(),r()) return vbox def _add_confirm_button(self,", "if_real_time = False date = self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time = self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room", "canvas_panel = CanvasPanel(self) # vbox1.Add(canvas_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) result_panel =", "proportion=3, flag=wx.RIGHT, border=5) hbox1.Add(tpc1, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL,", "room_list = [] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"]", "occupancy_info = response['occupancy_info'] except: occu = str(0) occupancy_info = []", "self.drop_down_menu_ID = None self.result_visual_ID = None self.info = info self._init_UI()", "self._init_UI() self._q_dict = {\"1\": self._q1_panel, \"2\": self._q2_panel, \"3\": self._q3_panel, #", "= wx.StaticText(self, label=combo_box.GetValue()) # st2.SetFont(font) # sizer1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1)", "# print(\"end time = {}\".format(info[\"end\"])) if_real_time = self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if question_index", "proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox3.Add(cb, proportion=3, flag=wx.RIGHT|wx.TOP, border=5) vbox.Add(hbox3, proportion=0, flag=wx.ALL,", "info[\"end\"], # 'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00' } response", "self._stopevent.is_set()) and self.parent_thread.is_alive(): print(\"hello\") # print(self.parent_panel.info_widget_dict) # print(self.parent_panel.info) # chnage", "server name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else: #", "border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small", "label self._add_result_label(main_vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"] =", "name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) #", "date_hbox.Add(date_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) date_hbox.Add(dpc, proportion=3, flag=wx.RIGHT, border=5) date_hbox.Add(tpc, proportion=3,", "if self.worker: self.worker.join() self.worker = None self._send_request(info) def _request_handle(self, url,", "url) print(\"body\", body) print(\"params\", params) resp = {} if METHOD", "decorate_panel() def add_date_time_picker_layout(self): vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2", "proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name", "border=5) vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox, 5)", "METHOD == \"post\": r = requests.post(url, data=body) else: r =", "infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl # add result widget", "response = self._request_handle(url=url, body=body, METHOD=\"post\") try: room_list = response['room'] count", "for name in room_list: rlb.Append(name) elif question_index == 4: ##", "flag=wx.ALL, border=5) # Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label =", "add result label self._add_result_label(main_vbox) # add result widget hbox =", "flag=wx.ALL, border=5) # Real time box real_label = wx.StaticText(self, label=\"REAL", "self._set_font() def _set_font(self): self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12) self.font.MakeBold() def init_question_UI(self,", "5) # add result label self._add_result_label(vbox) # add widget infomation", "self._add_confirm_button(main_vbox, 1) # add result label self._add_result_label(main_vbox) # add result", "+ \"/person_room/\" body = {\"name\": info[\"name\"], \"start\": info[\"start\"], \"end\": info[\"end\"],", "border=1) # add canvas panel # canvas_panel = CanvasPanel(self) #", "time = {}\".format(info[\"start\"])) # print(\"end time = {}\".format(info[\"end\"])) if_real_time =", "self.worker.join() self.worker = None self._send_request(info) def _request_handle(self, url, body={}, params={},", "# room_info = wx.TextCtrl(self) # room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(room_hbox,", "time) info[\"room\"] = room # requester send request to server", "flag=wx.TOP, border=5) vbox1 = wx.BoxSizer(wx.VERTICAL) # add result label #", "def _q5_panel(self): print(\"q5\") vbox = wx.BoxSizer(wx.VERTICAL) # datetime date_hbox =", "= wx.CheckBox(self) hbox3.Add(real_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox3.Add(cb, proportion=3, flag=wx.RIGHT|wx.TOP, border=5)", "# https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q3_panel(self): print(\"q3\") vbox = self.add_date_time_picker_layout()", "\"{:.2f}\".format(response[\"utilization\"]*100) + \"%\" except: utilization = \"0%\" ## received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization)", "METHOD=\"post\"): # https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\", url) print(\"body\", body) print(\"params\", params) resp", "proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(vbox)", "\"/people_room/\" body = {\"room\": info[\"room\"], \"start\": info[\"start\"], \"end\": info[\"end\"], #", "## get ## url = self.server + \"/people_room/\" body =", "return vbox def _add_confirm_button(self, sizer, question_index): \"\"\" question_index => {1,", "count = str(random.randint(0, 20)) room_list = [\"Room_1_1_140\", \"Room_1_1_141\"] ## received", "wx.CheckBox(self) hbox3.Add(real_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox3.Add(cb, proportion=3, flag=wx.RIGHT|wx.TOP, border=5) vbox.Add(hbox3,", "# datetime date_hbox = wx.BoxSizer(wx.HORIZONTAL) date_label = wx.StaticText(self, label=\"Datetime\") date_label.SetFont(self.font)", "flag=wx.RIGHT|wx.TOP, border=4) hbox2.Add(dpc2, proportion=3, flag=wx.RIGHT, border=5) hbox2.Add(tpc2, proportion=3, flag=wx.RIGHT, border=5)", "add widget infomation to dict self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add", "border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name list roomlb", "print(\"end time = {}\".format(info[\"end\"])) if_real_time = self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if question_index ==", "send request to server name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] =", "= roomlb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q5_panel(self): print(\"q5\")", "label=combo_box.GetValue()) # st2.SetFont(font) # sizer1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) class ResultPanel(wx.Panel):", "info = {} # handle date and time if question_index", "name else: # question_index = 4 name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name)", "datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"] = util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"] = util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0) def", "a specific room?\", \"3. Where is someone?\", # \"4. Which", "question_index): info = {} # handle date and time if", "== 2: ## get ## url = self.server + \"/people_room/\"", "hbox2.Add(dpc2, proportion=3, flag=wx.RIGHT, border=5) hbox2.Add(tpc2, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox2, proportion=0,", "question_index == 1: ## get ## url = self.server +", "\"post\": r = requests.post(url, data=body) else: r = requests.get(url, params=params)", "'2020-04-05 21:10:00'} response = self._request_handle(url=url, body=body, METHOD=\"post\") try: occu =", "get ## url = self.server + \"/person_room/\" body = {\"name\":", "= '#%02X%02X%02X' % (r(),r(),r()) return vbox def _add_confirm_button(self, sizer, question_index):", "border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.SetSizer(main_vbox) #", "= self._request_handle(url=url, body=body, METHOD=\"post\") try: room_list = response['room'] count =", "= wx.StaticText(self, label=\"Utilization\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label =", "r.status_code == 200: resp = r.json() print(resp) print(type(resp)) return resp", "flag=wx.ALIGN_CENTER_HORIZONTAL, border=20) def OnClick(self, event, question_index): info = {} #", "# st2.SetFont(font) # vbox1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) # add canvas", "self.worker: # print(\"the worker has been stop\") self.worker.join() self.worker =", "room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm", "\"4. What is the utilization of a specific room?\" ]", "util import config import time import datetime import threading import", "clean the panel for child in self.GetChildren(): child.Destroy() # stop", "result label self._add_result_label(main_vbox) # add result widget hbox = wx.BoxSizer(wx.HORIZONTAL)", "= name_text_ctrl # add result widget # add count hbox", "= wx.BoxSizer(wx.HORIZONTAL) # add question label st1 = wx.StaticText(self, label='Question')", "wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) # add", "Count\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self, label=\"__\")", "wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) vbox.Add(hbox1,", "info if if_real_time: if not self.worker: self.worker = ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(),", "r = requests.get(url, params=params) print(r.status_code) if r.status_code == 200: resp", "= occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent()", "add result widget # add count hbox = wx.BoxSizer(wx.HORIZONTAL) label", "\"1. How many people are in the building?\", \"2. How", "dpc1 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc1 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime)", "body=body, METHOD=\"post\") try: occu = str(response['count']) occupancy_info = response['occupancy_info'] except:", "for name in occupancy_info: nlb.Append(name) elif question_index == 3: ##", "# self.Bind(wx.EVT_BUTTON, self.OnClick, comfirm_btn) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, question_index), comfirm_btn)", "-1, wx.DefaultDateTime) date_hbox.Add(date_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) date_hbox.Add(dpc, proportion=3, flag=wx.RIGHT, border=5)", "the worker if self.worker: # print(\"the worker has been stop\")", "q_idx): # clean the panel for child in self.GetChildren(): child.Destroy()", "METHOD=\"post\") try: occu = str(response['count']) except: occu = str(0) ##", "question_index), comfirm_btn) def _add_result_label(self, sizer): result_label = wx.StaticText(self, label=\"RESULT\") font", "except: count = str(0) room_list = [] ## received ##", "date and time if question_index in [1, 2, 3, 4]:", "visited?\", \"4. What is the utilization of a specific room?\"", "self.server + \"question/4\" body = {\"name\": info[\"name\"], # \"start_time\": info[\"start\"],", "vbox1.Add(canvas_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) result_panel = ResultPanel(self) # result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel,", "proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) vbox.Add(hbox1, proportion=1, flag=wx.EXPAND|wx.ALL, border=10) vbox.Add(vbox1, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM,", "sizer.Add(result_label, proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL, border=20) def OnClick(self, event, question_index): info =", "# Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label = wx.StaticText(self, label=\"Room\")", "proportion=8, flag=wx.TOP, border=5) main_vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm button", "panel for child in self.GetChildren(): child.Destroy() # stop the worker", "self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit()", "# requester send request to server name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name)", "self.add_date_time_picker_layout() # Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label = wx.StaticText(self,", "_q1_panel(self): print(\"q1\") main_vbox = self.add_date_time_picker_layout() # confirm button self._add_confirm_button(main_vbox, 1)", "self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for name in room_list: rlb.Append(name)", "self.result_visual_ID = None self.info = info self._init_UI() def _init_UI(self): self.SetBackgroundColour(\"#BAB86C\")", "self._request_handle(url=url, body=body, METHOD=\"post\") try: occu = str(response['count']) except: occu =", "print(resp) print(type(resp)) return resp def _send_request(self, info): question_index = int(info[\"question_index\"])", "border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"utilization_label\"] = occu_label self.SetSizer(vbox) #", "room # requester send request to server info[\"question_index\"] = question_index", "print(name) info[\"name\"] = name else: # question_index == 5 if_real_time", "date = self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time = self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"]", "_q5_panel(self): print(\"q5\") vbox = wx.BoxSizer(wx.VERTICAL) # datetime date_hbox = wx.BoxSizer(wx.HORIZONTAL)", "= self.add_date_time_picker_layout() # confirm button self._add_confirm_button(main_vbox, 1) # add result", "= {\"room\": info[\"room\"], \"start\": info[\"start\"], \"end\": info[\"end\"], # 'start': '2020-04-05", "list roomlb = wx.ListBox(self) main_vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] =", "= dpc self.info_widget_dict[\"feeder\"][\"time_picker\"] = tpc self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add", "elif question_index == 3: # requester send request to server", "# requester send request to server room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room)", "== \"post\": r = requests.post(url, data=body) else: r = requests.get(url,", "wx.adv import random import util import config import time import", "= wx.StaticText(self, label=\"Room\") room_label.SetFont(self.font) room_hbox.Add(room_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) room_list =", "= self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self, label=\"Name\") name_label.SetFont(self.font)", "= datetime.datetime.now() start = end - datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"] = util.convert_to_GMT_zone(start)", "has someone visited?\", \"4. What is the utilization of a", "\"4\": self._q4_panel, \"4\": self._q5_panel,} self.info_widget_dict = {\"feeder\": {}, \"consumer\": {}}", "wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Room Count\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT,", "hbox1.Add(drop_down_menu, proportion=8, flag=wx.TOP, border=5) vbox1 = wx.BoxSizer(wx.VERTICAL) # add result", "self._q5_panel,} self.info_widget_dict = {\"feeder\": {}, \"consumer\": {}} self.worker = None", "in the building?\", \"2. How many people are in a", "vbox.Add(hbox3, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"feeder\"][\"start_date\"] = dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"] = tpc1", "vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self, label=\"Name\")", "threading.Thread.join(self, timeout) class RightPanel(wx.Panel): def __init__(self, parent, info={}): wx.Panel.__init__(self, parent=parent)", "self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else: # question_index == 5", "end_date = self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time = self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"] = util.combine_datetime(start_date, start_time)", "wx.StaticText(self, label=\"Utilization\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self,", "\"%\" except: utilization = \"0%\" ## received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def _q1_panel(self):", "util.combine_datetime(start_date, start_time) info[\"end\"] = util.combine_datetime(end_date, end_time) # print(\"start time =", "self.info = info self._init_UI() def _init_UI(self): self.SetBackgroundColour(\"#BAB86C\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)", "# st2 = wx.StaticText(self, label=combo_box.GetValue()) # st2.SetFont(font) # sizer1.Add(st2, proportion=1,", "+ \"/people_room/\" body = {\"room\": info[\"room\"], \"start\": info[\"start\"], \"end\": info[\"end\"],", "in room_list: rlb.Append(name) elif question_index == 4: ## get ##", "https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q4_panel(self): print(\"q4\") main_vbox = self.add_date_time_picker_layout() hbox1", "self._q1_panel, \"2\": self._q2_panel, \"3\": self._q3_panel, # \"4\": self._q4_panel, \"4\": self._q5_panel,}", "date_label.SetFont(self.font) dpc = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc = wx.adv.TimePickerCtrl(self, -1,", "combo_box=drop_down_menu, panel=result_panel)) def on_selection(self, event, combo_box, panel): # print(self.drop_down_menu.GetValue()) print(combo_box.GetValue())", "result_panel = ResultPanel(self) # result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) vbox.Add(hbox1,", "url = self.server + \"/person_room/\" body = {\"name\": info[\"name\"], \"start\":", "def _init_UI(self): self.SetBackgroundColour(\"#BAB86C\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) vbox = wx.BoxSizer(wx.VERTICAL)", "choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) #", "main_vbox.Add(namelb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"name_list\"] = namelb", "to dict self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result widget #", "proportion=0, flag=wx.ALL, border=5) # End end_label = wx.StaticText(self, label=\"END TIME\")", "enter unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(hbox1, proportion=0, flag=wx.ALL,", "border=5) # add name list roomlb = wx.ListBox(self) vbox.Add(roomlb, proportion=0,", "drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection, combo_box=drop_down_menu, panel=result_panel)) def on_selection(self, event, combo_box, panel): #", "= response['room'] count = str(len(room_list)) except: count = str(0) room_list", "Where is someone?\", # \"4. Which room has someone visited?\",", "## url = self.server + \"/people_building/\" body = {\"start\": info[\"start\"],", "else: # first check if the worker is working if", "self.GetParent().SendSizeEvent() def _q4_panel(self): print(\"q4\") main_vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL)", "wx.StaticText(self, label=\"END TIME\") end_label.SetFont(self.font) dpc2 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc2", "# print(self.parent_panel.info) # chnage to real time end = datetime.datetime.now()", "self.worker: self.worker.join() self.worker = None self._send_request(info) def _request_handle(self, url, body={},", "body = {\"name\": info[\"name\"], \"start\": info[\"start\"], \"end\": info[\"end\"], # 'start':", "= util.combine_datetime(start_date, start_time) info[\"end\"] = util.combine_datetime(end_date, end_time) # print(\"start time", "self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room) info[\"room\"] = room elif question_index == 3: #", "## get ## url = self.server + \"/person_room/\" body =", "proportion=8, flag=wx.TOP, border=5) main_vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm button", "flag=wx.ALIGN_CENTER, border=1) # add canvas panel # canvas_panel = CanvasPanel(self)", "proportion=3, flag=wx.RIGHT, border=5) date_hbox.Add(tpc, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(date_hbox, proportion=0, flag=wx.ALL,", "\"end\": info[\"end\"], # 'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00' }", "config.SERVER self._set_font() def _set_font(self): self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12) self.font.MakeBold() def", "self._send_request(info) def _request_handle(self, url, body={}, params={}, METHOD=\"post\"): # https://stackoverflow.com/questions/15900338/python-request-post-with-param-data print(\"url\",", "vbox1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) # add canvas panel # canvas_panel", "= end - datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"] = util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"] = util.convert_to_GMT_zone(end)", "proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"feeder\"][\"start_date\"] = dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"] = tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"]", "\"end_time\": info[\"end\"], \"time\": info[\"start\"], } response = self._request_handle(url=url, body=body, METHOD=\"post\")", "self._q3_panel, # \"4\": self._q4_panel, \"4\": self._q5_panel,} self.info_widget_dict = {\"feeder\": {},", "vbox.Add(hbox1, proportion=1, flag=wx.EXPAND|wx.ALL, border=10) vbox.Add(vbox1, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) self.SetSizer(vbox) #", "in [1, 2, 3, 4]: start_date = self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time =", "= wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) vbox.Add(room_hbox, proportion=0, flag=wx.ALL,", "# stop the worker if self.worker: # print(\"the worker has", "unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5)", "flag=wx.ALIGN_CENTER, border=1) class ResultPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) #", "= tpc self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result widget hbox", "body) print(\"params\", params) resp = {} if METHOD == \"post\":", "occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"]", "= [] ## received ## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb = self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear()", "self.worker = None self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear() decorate_panel = self._q_dict[q_idx] decorate_panel() def", "self._add_result_label(main_vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox", "body = {\"room\": info[\"room\"], \"date\": info[\"date\"], # 'date': '2020-04-05 20:00:00'", "# https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q5_panel(self): print(\"q5\") vbox = wx.BoxSizer(wx.VERTICAL)", "= threading.Event() self.parent_panel = parent_panel self.parent_thread = parent_thread def run(self):", "else: # question_index = 4 name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"]", "wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5)", "data=body) else: r = requests.get(url, params=params) print(r.status_code) if r.status_code ==", "# requester send request to server pass elif question_index ==", "label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5)", "cb = wx.CheckBox(self) hbox3.Add(real_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox3.Add(cb, proportion=3, flag=wx.RIGHT|wx.TOP,", "= \"0%\" ## received## self.info_widget_dict[\"consumer\"][\"utilization_label\"].SetLabel(utilization) def _q1_panel(self): print(\"q1\") main_vbox =", "= wx.StaticText(self, label=\"Room Count\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label", "# confirm button self._add_confirm_button(main_vbox, 1) # add result label self._add_result_label(main_vbox)", "self.info_widget_dict[\"feeder\"][\"end_time\"] = tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"] = cb # self.SetBackgroundColour(\"#000000\") # r", "info[\"start\"], # \"end_time\": info[\"end\"], \"time\": info[\"start\"], } response = self._request_handle(url=url,", "lambda: random.randint(0,255) # color = '#%02X%02X%02X' % (r(),r(),r()) return vbox", "border=5) # self.Bind(wx.EVT_BUTTON, self.OnClick, comfirm_btn) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, question_index),", "border=5) vbox.Add(date_hbox, proportion=0, flag=wx.ALL, border=5) # Room Info room_hbox =", "(not self._stopevent.is_set()) and self.parent_thread.is_alive(): print(\"hello\") # print(self.parent_panel.info_widget_dict) # print(self.parent_panel.info) #", "wx.ListBox(self) main_vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] =", "def __init__(self, name, parent_thread, parent_panel): threading.Thread.__init__(self, name=name) self._stopevent = threading.Event()", "[\"Room_1_1_140\", \"Room_1_1_141\"] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear()", "label = wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label", "flag=wx.TOP|wx.RIGHT, border=5) name_text_ctrl = wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter unique name') hbox1.Add(name_text_ctrl,", "question_index in [1, 2, 3, 4]: start_date = self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time", "wx.ListBox(self) main_vbox.Add(namelb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"name_list\"] =", "def on_selection(self, event, combo_box, panel): # print(self.drop_down_menu.GetValue()) print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0]) #", "= wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) date_hbox.Add(date_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) date_hbox.Add(dpc, proportion=3,", "# Real time box real_label = wx.StaticText(self, label=\"REAL TIME\") real_label.SetFont(self.font)", "requests.get(url, params=params) print(r.status_code) if r.status_code == 200: resp = r.json()", "_add_confirm_button(self, sizer, question_index): \"\"\" question_index => {1, 2, 3, 4}", "info[\"start\"], \"end\": info[\"end\"], # 'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00'", "dpc = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime)", "worker is working if self.worker: self.worker.join() self.worker = None self._send_request(info)", "= self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"] = util.combine_datetime(date, time) info[\"room\"] = room #", "info[\"room\"], \"start\": info[\"start\"], \"end\": info[\"end\"], # 'start': '2020-04-05 21:00:00', 'end':", "body, METHOD=\"post\") try: response = json.loads(response) utilization = \"{:.2f}\".format(response[\"utilization\"]*100) +", "self.worker.join() self.worker = None self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear() decorate_panel = self._q_dict[q_idx] decorate_panel()", "wx.DefaultDateTime) hbox1.Add(start_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox1.Add(dpc1, proportion=3, flag=wx.RIGHT, border=5) hbox1.Add(tpc1,", "url = self.server + \"/utilization/\" body = {\"room\": info[\"room\"], \"date\":", "list roomlb = wx.ListBox(self) vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] =", "\"Room_1_1_184\"] room_combobox = wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) vbox.Add(room_hbox,", "in occupancy_info: nlb.Append(name) elif question_index == 3: ## get ##", "\"3. Where is someone?\", # \"4. Which room has someone", "date_hbox.Add(tpc, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(date_hbox, proportion=0, flag=wx.ALL, border=5) # Room", "_init_UI(self): self.SetBackgroundColour(\"#BAB86C\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) vbox = wx.BoxSizer(wx.VERTICAL) hbox1", "wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self,", "= dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"] = tpc2 self.info_widget_dict[\"feeder\"][\"real_time\"] = cb # self.SetBackgroundColour(\"#000000\")", "while (not self._stopevent.is_set()) and self.parent_thread.is_alive(): print(\"hello\") # print(self.parent_panel.info_widget_dict) # print(self.parent_panel.info)", "choices=question_list) hbox1.Add(drop_down_menu, proportion=8, flag=wx.TOP, border=5) vbox1 = wx.BoxSizer(wx.VERTICAL) # add", "= CanvasPanel(self) # vbox1.Add(canvas_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) result_panel = ResultPanel(self)", "print(\"the worker has been stop\") self.worker.join() self.worker = None self.info_widget_dict[\"feeder\"].clear()", "= parent_panel self.parent_thread = parent_thread def run(self): while (not self._stopevent.is_set())", "21:10:00'} response = self._request_handle(url=url, body=body, METHOD=\"post\") try: occu = str(response['count'])", "rlb.Clear() for name in room_list: rlb.Append(name) elif question_index == 4:", "\"start_time\": info[\"start\"], # \"end_time\": info[\"end\"], \"time\": info[\"start\"], } response =", "self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"name_list\"] = namelb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit()", "= wx.StaticText(self, label=\"START TIME\") start_label.SetFont(self.font) dpc1 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime)", "resp = {} if METHOD == \"post\": r = requests.post(url,", "try: room_list = response['room'] count = str(len(room_list)) except: count =", "= wx.StaticText(self, label='Result') # st2.SetFont(font) # vbox1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1)", "self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date = self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time = self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"] = util.combine_datetime(start_date,", "\"/person_room/\" body = {\"name\": info[\"name\"], \"start\": info[\"start\"], \"end\": info[\"end\"], #", "\"2\": self._q2_panel, \"3\": self._q3_panel, # \"4\": self._q4_panel, \"4\": self._q5_panel,} self.info_widget_dict", "rlb.Clear() for name in room_list: rlb.Append(name) elif question_index == 5:", "21:00:00', 'end': '2020-04-05 21:10:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\")", "body=body, METHOD=\"post\") try: occu = str(response['count']) except: occu = str(0)", "occu_label self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q2_panel(self): print(\"q2\") main_vbox", "hbox1 = wx.BoxSizer(wx.HORIZONTAL) # add question label st1 = wx.StaticText(self,", "vbox.Add(hbox2, proportion=0, flag=wx.ALL, border=5) # Real time box real_label =", "self._request_handle(url=url, body=body, METHOD=\"post\") try: room_list = response['room'] count = str(len(room_list))", "proportion=2, flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name", "self.info_widget_dict[\"feeder\"][\"start_date\"].GetValue() start_time = self.info_widget_dict[\"feeder\"][\"start_time\"].GetValue() end_date = self.info_widget_dict[\"feeder\"][\"end_date\"].GetValue() end_time = self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue()", "\"date\": info[\"date\"], # 'date': '2020-04-05 20:00:00' } response = self._request_handle(url=url,", "main_vbox = self.add_date_time_picker_layout() # confirm button self._add_confirm_button(main_vbox, 1) # add", "-1, wx.DefaultDateTime) hbox2.Add(end_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox2.Add(dpc2, proportion=3, flag=wx.RIGHT, border=5)", "= wx.TextCtrl(self) # room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(room_hbox, proportion=0, flag=wx.ALL,", "date_hbox = wx.BoxSizer(wx.HORIZONTAL) date_label = wx.StaticText(self, label=\"Datetime\") date_label.SetFont(self.font) dpc =", "flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) vbox.Add(hbox1, proportion=1, flag=wx.EXPAND|wx.ALL, border=10) vbox.Add(vbox1, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10)", "infomation to dict self.info_widget_dict[\"feeder\"][\"date_picker\"] = dpc self.info_widget_dict[\"feeder\"][\"time_picker\"] = tpc self.info_widget_dict[\"feeder\"][\"room_select\"]", "if not self.worker: self.worker = ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(), parent_panel=self) self.worker.start() print(\"start", "print(name) info[\"name\"] = name else: # question_index = 4 name", "print(\"url\", url) print(\"body\", body) print(\"params\", params) resp = {} if", "child in self.GetChildren(): child.Destroy() # stop the worker if self.worker:", "vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb", "drop down menu question_list = [ \"1. How many people", "result label self._add_result_label(main_vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"]", "if question_index == 1: ## get ## url = self.server", "## url = self.server + \"/person_room/\" body = {\"name\": info[\"name\"],", "wx.DefaultDateTime) hbox2.Add(end_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox2.Add(dpc2, proportion=3, flag=wx.RIGHT, border=5) hbox2.Add(tpc2,", "util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"] = util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0) def join(self, timeout=None): self._stopevent.set()", "# sizer1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) class ResultPanel(wx.Panel): def __init__(self, parent):", "util.combine_datetime(date, time) info[\"room\"] = room # requester send request to", "tpc1 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox1.Add(start_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox1.Add(dpc1,", "widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl # add result", "CanvasPanel(self) # vbox1.Add(canvas_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) result_panel = ResultPanel(self) #", "child.Destroy() # stop the worker if self.worker: # print(\"the worker", "__init__(self, parent): wx.Panel.__init__(self, parent) # self._init_UI() self._q_dict = {\"1\": self._q1_panel,", "dict self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl # add result widget # add", "## url = self.server + \"/people_room/\" body = {\"room\": info[\"room\"],", "{'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00'} response = self._request_handle(url=url, body=body,", "flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) self.SetSizer(vbox) # listen combo drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection, combo_box=drop_down_menu, panel=result_panel))", "vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox, 3) #", "print(type(resp)) return resp def _send_request(self, info): question_index = int(info[\"question_index\"]) if", "utilization = \"{:.2f}\".format(response[\"utilization\"]*100) + \"%\" except: utilization = \"0%\" ##", "= self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear() for name in occupancy_info: nlb.Append(name) elif question_index", "join(self, timeout=None): self._stopevent.set() print(\"thread stop\") threading.Thread.join(self, timeout) class RightPanel(wx.Panel): def", "# requester send request to server info[\"question_index\"] = question_index self.info", "label=\"RESULT\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) font.MakeBold() result_label.SetFont(font) sizer.Add(result_label, proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL,", "result label self._add_result_label(vbox) # add widget infomation to dict self.info_widget_dict[\"feeder\"][\"name_select\"]", "# question_index == 5 if_real_time = False date = self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue()", "[] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for", "flag=wx.ALL, border=5) self.info_widget_dict[\"feeder\"][\"start_date\"] = dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"] = tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"] =", "4 name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else: #", "worker has been stop\") self.worker.join() self.worker = None self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear()", "proportion=8, flag=wx.TOP, border=5) # room_info = wx.TextCtrl(self) # room_hbox.Add(room_combobox, proportion=8,", "== 1: ## get ## url = self.server + \"/people_building/\"", "self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q5_panel(self):", "hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm", "info[\"room\"] = room # requester send request to server info[\"question_index\"]", "label=\"Room\") room_label.SetFont(self.font) room_hbox.Add(room_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) room_list = [ \"\",", "border=4) hbox1.Add(dpc1, proportion=3, flag=wx.RIGHT, border=5) hbox1.Add(tpc1, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox1,", "panel=result_panel)) def on_selection(self, event, combo_box, panel): # print(self.drop_down_menu.GetValue()) print(combo_box.GetValue()) panel.init_question_UI(combo_box.GetValue()[0])", "result_label = wx.StaticText(self, label=\"RESULT\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) font.MakeBold() result_label.SetFont(font)", "{}\".format(info[\"end\"])) if_real_time = self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if question_index == 1: # requester", "r.json() print(resp) print(type(resp)) return resp def _send_request(self, info): question_index =", "border=10) vbox.Add(hbox1, proportion=1, flag=wx.EXPAND|wx.ALL, border=10) vbox.Add(vbox1, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) self.SetSizer(vbox)", "parent_panel self.parent_thread = parent_thread def run(self): while (not self._stopevent.is_set()) and", "proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox1.Add(dpc1, proportion=3, flag=wx.RIGHT, border=5) hbox1.Add(tpc1, proportion=3, flag=wx.RIGHT,", "self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q2_panel(self): print(\"q2\") main_vbox =", "Start start_label = wx.StaticText(self, label=\"START TIME\") start_label.SetFont(self.font) dpc1 = wx.adv.DatePickerCtrl(self,", "hbox1.Add(name_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) name_text_ctrl = wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter unique", "TIME\") real_label.SetFont(self.font) cb = wx.CheckBox(self) hbox3.Add(real_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox3.Add(cb,", "= wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) #", "# room_hbox.Add(room_combobox, proportion=8, flag=wx.TOP, border=5) main_vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) #", "font.SetPointSize(20) font.MakeBold() result_label.SetFont(font) sizer.Add(result_label, proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL, border=20) def OnClick(self, event,", "sizer): result_label = wx.StaticText(self, label=\"RESULT\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) font.MakeBold()", "wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Utilization\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5)", "# 'date': '2020-04-05 20:00:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\")", "name else: # question_index == 5 if_real_time = False date", "= self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else: # question_index ==", "= 4 name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name else:", "= wx.StaticText(self, label=\"END TIME\") end_label.SetFont(self.font) dpc2 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime)", "occu_label = wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox,", "flag=wx.RIGHT, border=5) date_hbox.Add(tpc, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(date_hbox, proportion=0, flag=wx.ALL, border=5)", "room_list = [ \"\", \"Room_1_1_140\", \"Room_1_1_141\", \"Room_1_1_142\", \"Room_1_1_143\", \"Room_1_1_144\", \"Room_1_1_150\",", "] drop_down_menu = wx.ComboBox(self, choices=question_list) hbox1.Add(drop_down_menu, proportion=8, flag=wx.TOP, border=5) vbox1", "\"Room_1_1_141\", \"Room_1_1_142\", \"Room_1_1_143\", \"Room_1_1_144\", \"Room_1_1_150\", \"Room_1_1_184\"] room_combobox = wx.ComboBox(self, choices=room_list)", "flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(main_vbox) #", "requester send request to server name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"]", "info[\"name\"], # \"start_time\": info[\"start\"], # \"end_time\": info[\"end\"], \"time\": info[\"start\"], }", "get ## url = self.server + \"/utilization/\" body = {\"room\":", "main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name list namelb =", "# self._init_UI() self._q_dict = {\"1\": self._q1_panel, \"2\": self._q2_panel, \"3\": self._q3_panel,", "border=5) main_vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox, 2)", "- datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"] = util.convert_to_GMT_zone(start) self.parent_panel.info[\"end\"] = util.convert_to_GMT_zone(end) self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0)", "border=5) occu_label = wx.StaticText(self, label=\"__\") occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5)", "working if self.worker: self.worker.join() self.worker = None self._send_request(info) def _request_handle(self,", "occu = str(response['count']) except: occu = str(0) ## received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu)", "wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox2.Add(end_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox2.Add(dpc2, proportion=3, flag=wx.RIGHT,", "= wx.BoxSizer(wx.VERTICAL) # datetime date_hbox = wx.BoxSizer(wx.HORIZONTAL) date_label = wx.StaticText(self,", "to real time end = datetime.datetime.now() start = end -", "border=10) result_panel = ResultPanel(self) # result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10)", "int(info[\"question_index\"]) if question_index == 1: ## get ## url =", "= {\"room\": info[\"room\"], \"date\": info[\"date\"], # 'date': '2020-04-05 20:00:00' }", "= wx.StaticText(self, label=\"Datetime\") date_label.SetFont(self.font) dpc = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc", "def _send_request(self, info): question_index = int(info[\"question_index\"]) if question_index == 1:", "# add result label self._add_result_label(vbox) # add widget infomation to", "class RightPanel(wx.Panel): def __init__(self, parent, info={}): wx.Panel.__init__(self, parent=parent) self.drop_down_menu_ID =", "end = datetime.datetime.now() start = end - datetime.timedelta(minutes=1) self.parent_panel.info[\"start\"] =", "to dict self.info_widget_dict[\"feeder\"][\"name_select\"] = name_text_ctrl # add result widget #", "METHOD=\"post\") try: occu = str(response['count']) occupancy_info = response['occupancy_info'] except: occu", "=> {1, 2, 3, 4} \"\"\" comfirm_btn = wx.Button(self, id=-1,", "name list roomlb = wx.ListBox(self) main_vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"]", "wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) date_hbox.Add(date_label, proportion=2,", "\"\", \"Room_1_1_140\", \"Room_1_1_141\", \"Room_1_1_142\", \"Room_1_1_143\", \"Room_1_1_144\", \"Room_1_1_150\", \"Room_1_1_184\"] room_combobox =", "= str(0) occupancy_info = [] ## received ## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb", "border=5) main_vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox, 4)", "border=4) date_hbox.Add(dpc, proportion=3, flag=wx.RIGHT, border=5) date_hbox.Add(tpc, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(date_hbox,", "{}, \"consumer\": {}} self.worker = None self.server = config.SERVER self._set_font()", "question_index == 5: ## get ## url = self.server +", "# print(\"the worker has been stop\") self.worker.join() self.worker = None", "elif question_index == 2: ## get ## url = self.server", "name_text_ctrl = wx.TextCtrl(self) name_text_ctrl.AppendText('Please enter unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP,", "panel # canvas_panel = CanvasPanel(self) # vbox1.Add(canvas_panel, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10)", "= str(len(room_list)) except: count = str(0) room_list = [] ##", "== 4: ## get ## url = self.server + \"question/4\"", "request to server name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] = name", "self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb = self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear() for name in occupancy_info: nlb.Append(name)", "= [\"Room_1_1_140\", \"Room_1_1_141\"] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb = self.info_widget_dict[\"consumer\"][\"room_list\"]", "specific room?\" ] drop_down_menu = wx.ComboBox(self, choices=question_list) hbox1.Add(drop_down_menu, proportion=8, flag=wx.TOP,", "proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(vbox, 5) # add", "proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit()", "flag=wx.TOP|wx.RIGHT, border=5) vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) # add name list", "if question_index == 1: # requester send request to server", "# handle date and time if question_index in [1, 2,", "self.info_widget_dict[\"consumer\"].clear() decorate_panel = self._q_dict[q_idx] decorate_panel() def add_date_time_picker_layout(self): vbox = wx.BoxSizer(wx.VERTICAL)", "\"2. How many people are in a specific room?\", \"3.", "if_real_time = self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if question_index == 1: # requester send", "flag=wx.TOP|wx.LEFT, border=5) # self.Bind(wx.EVT_BUTTON, self.OnClick, comfirm_btn) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event,", "https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self, name, parent_thread, parent_panel): threading.Thread.__init__(self, name=name) self._stopevent =", "\"\"\" comfirm_btn = wx.Button(self, id=-1, label=\"Confirm\") sizer.Add(comfirm_btn, proportion=0, flag=wx.TOP|wx.LEFT, border=5)", "= self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"] = util.combine_datetime(date, time) info[\"room\"]", "hbox1.Add(st1, proportion=2, flag=wx.RIGHT, border=10) # add drop down menu question_list", "count = str(len(room_list)) except: count = str(0) room_list = []", "= [ \"\", \"Room_1_1_140\", \"Room_1_1_141\", \"Room_1_1_142\", \"Room_1_1_143\", \"Room_1_1_144\", \"Room_1_1_150\", \"Room_1_1_184\"]", "add count hbox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Occupancy\") label.SetFont(self.font)", "= self.server + \"/people_building/\" body = {\"start\": info[\"start\"], \"end\": info[\"end\"]}", "button self._add_confirm_button(vbox, 3) # add result label self._add_result_label(vbox) # add", "# add widget infomation to dict self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox #", "# st2.SetFont(font) # sizer1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) class ResultPanel(wx.Panel): def", "self._add_confirm_button(main_vbox, 4) # add result label self._add_result_label(main_vbox) # add widget", "# add widget infomation to dict self.info_widget_dict[\"feeder\"][\"date_picker\"] = dpc self.info_widget_dict[\"feeder\"][\"time_picker\"]", "self.parent_panel._send_request(self.parent_panel.info) self._stopevent.wait(5.0) def join(self, timeout=None): self._stopevent.set() print(\"thread stop\") threading.Thread.join(self, timeout)", "'date': '2020-04-05 20:00:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\") #", "# add name list roomlb = wx.ListBox(self) main_vbox.Add(roomlb, proportion=0, flag=wx.ALL,", "def _add_confirm_button(self, sizer, question_index): \"\"\" question_index => {1, 2, 3,", "= self.info_widget_dict[\"consumer\"][\"room_list\"] rlb.Clear() for name in room_list: rlb.Append(name) elif question_index", "= config.SERVER self._set_font() def _set_font(self): self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12) self.font.MakeBold()", "= requests.get(url, params=params) print(r.status_code) if r.status_code == 200: resp =", "# confirm button self._add_confirm_button(main_vbox, 2) # add result label self._add_result_label(main_vbox)", "3: # requester send request to server name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue()", "border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"name_list\"] = namelb self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small", "21:00:00', 'end': '2020-04-05 21:10:00'} response = self._request_handle(url=url, body=body, METHOD=\"post\") try:", "self._q4_panel, \"4\": self._q5_panel,} self.info_widget_dict = {\"feeder\": {}, \"consumer\": {}} self.worker", "wx.DefaultDateTime) tpc1 = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) hbox1.Add(start_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4)", "self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q3_panel(self): print(\"q3\") vbox =", "self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(12) self.font.MakeBold() def init_question_UI(self, q_idx): # clean", "[ \"\", \"Room_1_1_140\", \"Room_1_1_141\", \"Room_1_1_142\", \"Room_1_1_143\", \"Room_1_1_144\", \"Room_1_1_150\", \"Room_1_1_184\"] room_combobox", "flag=wx.ALL, border=5) # add name list roomlb = wx.ListBox(self) vbox.Add(roomlb,", "hbox1.Add(start_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4) hbox1.Add(dpc1, proportion=3, flag=wx.RIGHT, border=5) hbox1.Add(tpc1, proportion=3,", "} response = self._request_handle(url=url, body=body, METHOD=\"post\") count = str(random.randint(0, 20))", "hbox1.Add(tpc1, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # End", "## url = self.server + \"question/4\" body = {\"name\": info[\"name\"],", "wx.StaticText(self, label=\"REAL TIME\") real_label.SetFont(self.font) cb = wx.CheckBox(self) hbox3.Add(real_label, proportion=2, flag=wx.RIGHT|wx.TOP,", "if_real_time: if not self.worker: self.worker = ReqeusterThread(name=\"question_{}_requester\".format(question_index), parent_thread=threading.currentThread(), parent_panel=self) self.worker.start()", "main_vbox.Add(room_hbox, proportion=0, flag=wx.ALL, border=5) # confirm button self._add_confirm_button(main_vbox, 2) #", "= str(0) ## received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif question_index == 2: ##", "occu_label.SetFont(self.font) hbox.Add(occu_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) main_vbox.Add(hbox, proportion=0, flag=wx.ALL, border=5) #", "proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5) # End end_label", "wx import wx.adv import random import util import config import", "= dpc1 self.info_widget_dict[\"feeder\"][\"start_time\"] = tpc1 self.info_widget_dict[\"feeder\"][\"end_date\"] = dpc2 self.info_widget_dict[\"feeder\"][\"end_time\"] =", "flag=wx.RIGHT, border=5) vbox.Add(date_hbox, proportion=0, flag=wx.ALL, border=5) # Room Info room_hbox", "name=name) self._stopevent = threading.Event() self.parent_panel = parent_panel self.parent_thread = parent_thread", "4} \"\"\" comfirm_btn = wx.Button(self, id=-1, label=\"Confirm\") sizer.Add(comfirm_btn, proportion=0, flag=wx.TOP|wx.LEFT,", "'start': '2020-04-05 21:00:00', 'end': '2020-04-05 21:10:00' } response = self._request_handle(url=url,", "# question_index = 4 name = self.info_widget_dict[\"feeder\"][\"name_select\"].GetValue() print(name) info[\"name\"] =", "proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) result_panel = ResultPanel(self) # result_panel.SetBackgroundColour(\"#000000\") vbox1.Add(result_panel, proportion=9,", "# chnage to real time end = datetime.datetime.now() start =", "border=5) # confirm button self._add_confirm_button(vbox, 3) # add result label", "TIME\") end_label.SetFont(self.font) dpc2 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc2 = wx.adv.TimePickerCtrl(self,", "== 3: ## get ## url = self.server + \"/person_room/\"", "roomlb = wx.ListBox(self) vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label", "nlb = self.info_widget_dict[\"consumer\"][\"name_list\"] nlb.Clear() for name in occupancy_info: nlb.Append(name) elif", "= self.info_widget_dict[\"feeder\"][\"date_picker\"].GetValue() time = self.info_widget_dict[\"feeder\"][\"time_picker\"].GetValue() room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() info[\"date\"] =", "= wx.BoxSizer(wx.HORIZONTAL) name_label = wx.StaticText(self, label=\"Name\") name_label.SetFont(self.font) hbox1.Add(name_label, proportion=2, flag=wx.TOP|wx.RIGHT,", "{\"name\": info[\"name\"], \"start\": info[\"start\"], \"end\": info[\"end\"], # 'start': '2020-04-05 21:00:00',", "add name list roomlb = wx.ListBox(self) main_vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5)", "= None self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear() decorate_panel = self._q_dict[q_idx] decorate_panel() def add_date_time_picker_layout(self):", "room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue() print(room) info[\"room\"] = room elif question_index ==", "2) # add result label self._add_result_label(main_vbox) # add widget infomation", "_q3_panel(self): print(\"q3\") vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label =", "class ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self, name, parent_thread, parent_panel): threading.Thread.__init__(self,", "# \"end_time\": info[\"end\"], \"time\": info[\"start\"], } response = self._request_handle(url=url, body=body,", "# vbox1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER, border=1) # add canvas panel #", "time if question_index in [1, 2, 3, 4]: start_date =", "room?\", \"3. Where is someone?\", # \"4. Which room has", "random import util import config import time import datetime import", "flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"] = occu_label self.SetSizer(main_vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent()", "infomation to dict self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox # add result widget", "= wx.Button(self, id=-1, label=\"Confirm\") sizer.Add(comfirm_btn, proportion=0, flag=wx.TOP|wx.LEFT, border=5) # self.Bind(wx.EVT_BUTTON,", "= self.info_widget_dict[\"feeder\"][\"real_time\"].GetValue() if question_index == 1: # requester send request", "self.worker.start() print(\"start worker\") else: # first check if the worker", "\"time\": info[\"start\"], } response = self._request_handle(url=url, body=body, METHOD=\"post\") count =", "unique name') hbox1.Add(name_text_ctrl, proportion=8, flag=wx.TOP, border=5) vbox.Add(hbox1, proportion=0, flag=wx.ALL, border=5)", "21:10:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\") try: room_list =", "= str(response['count']) occupancy_info = response['occupancy_info'] except: occu = str(0) occupancy_info", "question_index = int(info[\"question_index\"]) if question_index == 1: ## get ##", "dict self.info_widget_dict[\"feeder\"][\"date_picker\"] = dpc self.info_widget_dict[\"feeder\"][\"time_picker\"] = tpc self.info_widget_dict[\"feeder\"][\"room_select\"] = room_combobox", "proportion=0, flag=wx.ALL, border=5) # Room Info room_hbox = wx.BoxSizer(wx.HORIZONTAL) room_label", "proportion=8, flag=wx.TOP, border=5) vbox1 = wx.BoxSizer(wx.VERTICAL) # add result label", "response = self._request_handle(url=url, body=body, METHOD=\"post\") try: occu = str(response['count']) occupancy_info", "date_label = wx.StaticText(self, label=\"Datetime\") date_label.SetFont(self.font) dpc = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime)", "# https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit() self.GetParent().SendSizeEvent() def _q4_panel(self): print(\"q4\") main_vbox = self.add_date_time_picker_layout()", "proportion=0, flag=wx.ALL, border=5) # Real time box real_label = wx.StaticText(self,", "} response = self._request_handle(url=url, body=body, METHOD=\"post\") # self.request_handle(url, body, METHOD=\"post\")", "flag=wx.RIGHT, border=5) vbox.Add(hbox2, proportion=0, flag=wx.ALL, border=5) # Real time box", "2: # requester send request to server room = self.info_widget_dict[\"feeder\"][\"room_select\"].GetValue()", "of a specific room?\" ] drop_down_menu = wx.ComboBox(self, choices=question_list) hbox1.Add(drop_down_menu,", "str(0) ## received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif question_index == 2: ## get", "wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL)", "'2020-04-05 21:10:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\") try: room_list", "wx.StaticText(self, label=\"Room\") room_label.SetFont(self.font) room_hbox.Add(room_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) room_list = [", "name_label = wx.StaticText(self, label=\"Name\") name_label.SetFont(self.font) hbox1.Add(name_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) name_text_ctrl", "= None self.server = config.SERVER self._set_font() def _set_font(self): self.font =", "name list namelb = wx.ListBox(self) main_vbox.Add(namelb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"occu_label\"]", "self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif question_index == 2: ## get ## url =", "self.SetSizer(vbox) # listen combo drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection, combo_box=drop_down_menu, panel=result_panel)) def on_selection(self,", "info[\"end\"] = util.combine_datetime(end_date, end_time) # print(\"start time = {}\".format(info[\"start\"])) #", "str(0) room_list = [] ## received ## self.info_widget_dict[\"consumer\"][\"count_label\"].SetLabel(count) rlb =", "\"Room_1_1_143\", \"Room_1_1_144\", \"Room_1_1_150\", \"Room_1_1_184\"] room_combobox = wx.ComboBox(self, choices=room_list) room_hbox.Add(room_combobox, proportion=8,", "border=5) date_hbox.Add(tpc, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(date_hbox, proportion=0, flag=wx.ALL, border=5) #", "wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL) # Start start_label", "-1, wx.DefaultDateTime) tpc = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) date_hbox.Add(date_label, proportion=2, flag=wx.RIGHT|wx.TOP,", "question_index == 4: ## get ## url = self.server +", "hbox2.Add(tpc2, proportion=3, flag=wx.RIGHT, border=5) vbox.Add(hbox2, proportion=0, flag=wx.ALL, border=5) # Real", "parent, info={}): wx.Panel.__init__(self, parent=parent) self.drop_down_menu_ID = None self.result_visual_ID = None", "occu = str(0) ## received## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) elif question_index == 2:", "st2 = wx.StaticText(self, label='Result') # st2.SetFont(font) # vbox1.Add(st2, proportion=1, flag=wx.ALIGN_CENTER,", "end_time = self.info_widget_dict[\"feeder\"][\"end_time\"].GetValue() info[\"start\"] = util.combine_datetime(start_date, start_time) info[\"end\"] = util.combine_datetime(end_date,", "20:00:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\") # self.request_handle(url, body,", "= wx.ListBox(self) vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"]", "= wx.BoxSizer(wx.HORIZONTAL) date_label = wx.StaticText(self, label=\"Datetime\") date_label.SetFont(self.font) dpc = wx.adv.DatePickerCtrl(self,", "wx.Panel.__init__(self, parent) # self._init_UI() self._q_dict = {\"1\": self._q1_panel, \"2\": self._q2_panel,", "vbox.Add(vbox1, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) self.SetSizer(vbox) # listen combo drop_down_menu.Bind(wx.EVT_COMBOBOX, partial(self.on_selection,", "self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"] = roomlb self.SetSizer(vbox) # https://stackoverflow.com/questions/42365239/wxpython-after-changing-panel-and-redo-layout-panel-is-very-small self.Fit()", "label='Question') st1.SetFont(font) hbox1.Add(st1, proportion=2, flag=wx.RIGHT, border=10) # add drop down", "None self._send_request(info) def _request_handle(self, url, body={}, params={}, METHOD=\"post\"): # https://stackoverflow.com/questions/15900338/python-request-post-with-param-data", "wx.DefaultDateTime) tpc = wx.adv.TimePickerCtrl(self, -1, wx.DefaultDateTime) date_hbox.Add(date_label, proportion=2, flag=wx.RIGHT|wx.TOP, border=4)", "TIME\") start_label.SetFont(self.font) dpc1 = wx.adv.DatePickerCtrl(self, -1, wx.DefaultDateTime) tpc1 = wx.adv.TimePickerCtrl(self,", "'2020-04-05 20:00:00' } response = self._request_handle(url=url, body=body, METHOD=\"post\") # self.request_handle(url,", "import random import util import config import time import datetime", "= util.combine_datetime(end_date, end_time) # print(\"start time = {}\".format(info[\"start\"])) # print(\"end", "= wx.StaticText(self, label=\"RESULT\") font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(20) font.MakeBold() result_label.SetFont(font) sizer.Add(result_label,", "proportion=1, flag=wx.EXPAND|wx.ALL, border=10) vbox.Add(vbox1, proportion=9, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10) self.SetSizer(vbox) # listen", "id=-1, label=\"Confirm\") sizer.Add(comfirm_btn, proportion=0, flag=wx.TOP|wx.LEFT, border=5) # self.Bind(wx.EVT_BUTTON, self.OnClick, comfirm_btn)", "## get ## url = self.server + \"question/4\" body =", "# add result widget # add count hbox = wx.BoxSizer(wx.HORIZONTAL)", "box real_label = wx.StaticText(self, label=\"REAL TIME\") real_label.SetFont(self.font) cb = wx.CheckBox(self)", "border=4) hbox3.Add(cb, proportion=3, flag=wx.RIGHT|wx.TOP, border=5) vbox.Add(hbox3, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"feeder\"][\"start_date\"]", "= wx.ListBox(self) main_vbox.Add(roomlb, proportion=0, flag=wx.ALL, border=5) self.info_widget_dict[\"consumer\"][\"count_label\"] = occu_label self.info_widget_dict[\"consumer\"][\"room_list\"]", "= self.server + \"/people_room/\" body = {\"room\": info[\"room\"], \"start\": info[\"start\"],", "label=\"Utilization\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5) occu_label = wx.StaticText(self, label=\"__\")", "= util.combine_datetime(date, time) info[\"room\"] = room # requester send request", "wx.BoxSizer(wx.HORIZONTAL) room_label = wx.StaticText(self, label=\"Room\") room_label.SetFont(self.font) room_hbox.Add(room_label, proportion=2, flag=wx.TOP|wx.RIGHT, border=5)", "= question_index self.info = info if if_real_time: if not self.worker:", "parent_panel=self) self.worker.start() print(\"start worker\") else: # first check if the", "{\"1\": self._q1_panel, \"2\": self._q2_panel, \"3\": self._q3_panel, # \"4\": self._q4_panel, \"4\":", "nlb.Append(name) elif question_index == 3: ## get ## url =", "and self.parent_thread.is_alive(): print(\"hello\") # print(self.parent_panel.info_widget_dict) # print(self.parent_panel.info) # chnage to", "def _q4_panel(self): print(\"q4\") main_vbox = self.add_date_time_picker_layout() hbox1 = wx.BoxSizer(wx.HORIZONTAL) name_label", "str(0) occupancy_info = [] ## received ## self.info_widget_dict[\"consumer\"][\"occu_label\"].SetLabel(occu) nlb =", "= wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=\"Utilization\") label.SetFont(self.font) hbox.Add(label, proportion=2, flag=wx.TOP|wx.RIGHT,", "# first check if the worker is working if self.worker:", "stop\") self.worker.join() self.worker = None self.info_widget_dict[\"feeder\"].clear() self.info_widget_dict[\"consumer\"].clear() decorate_panel = self._q_dict[q_idx]" ]
[ "entities: query_cards(query_string, limit=20) -> search.SearchResults The results items will have", "ndb QUERY_LIMIT = 20 CARD_INDEX_NAME = 'cards' # Increase this", "privacy clause). parts = [] if terms: parts.append(' OR '.join(terms))", "Increase this value when _card2doc changes its format so that", "entities in the search facility.\"\"\" # TODO(chris): should we allow", "index.delete(card_doc_ids) def query_cards(query_str, limit=QUERY_LIMIT, web_safe_cursor=None, ids_only=False, user_key=None): \"\"\"Return the search.SearchResults", "a query. ids_only is useful because the returned document IDs", "value when _card2doc changes its format so that # queries", "a user would enter it, and passes through a custom", "re.sub(r'[^a-zA-Z0-9._-]+', '', token) if sane_token: if sane_token in ('AND', 'OK'):", "continue # ignore special search keywords elif token.startswith('@'): names.append(sane_token) elif", "= tag_field self.private_field = private_field self.user_key_field = user_key_field self.query_options =", "= _QueryProcessor( query_str, name_field='user_nickname', tag_field='tag', private_field='private', user_key_field='user_key', query_options=search.QueryOptions(limit=limit, cursor=cursor, ids_only=ids_only),", "# TODO(chris): is user_nickname always a direct-match # shortname, e.g.,", "name_field self.tag_field = tag_field self.private_field = private_field self.user_key_field = user_key_field", "tags.append(sane_token) else: terms.append(sane_token) return terms, names, tags class _QueryProcessor(object): \"\"\"Simple", "query. ids_only is useful because the returned document IDs are", "' AND '.join(parts) def query(self): query = search.Query( query_string=self._build_query_string(), options=self.query_options)", "rendering a search results item to avoid entity lookup? tag_fields", "= '%s: 0' % self.private_field if self.user_key: # ... but", "= [] if terms: parts.append(' OR '.join(terms)) if names: parts.append('%s:", "private... privacy = '%s: 0' % self.private_field if self.user_key: #", "= index.search(query_processor.query()) # TODO(chris): should this return partially-instantiated # models.Card", "self.private_field if self.user_key: # ... but always show the user", "search.SearchResults The results items will have the following fields: user_key,", "200 cards per call? assert len(cards) <= 200, len(cards) card_docs", "get # metadata from an entity and generate a document.", "tokens should apply to. \"\"\" def __init__(self, query_str, name_field, tag_field,", "is the name of the field #tag tokens should apply", "_card2doc(card): # TODO(chris): should we include all fields that would", "allow more than 200 cards per call? assert len(cards) <=", "so that # queries can determine the data available on", "to. \"\"\" def __init__(self, query_str, name_field, tag_field, private_field, user_key_field, query_options=None,", "elif token.startswith('#'): tags.append(sane_token) else: terms.append(sane_token) return terms, names, tags class", "map(_card2docid, cards) index.delete(card_doc_ids) def query_cards(query_str, limit=QUERY_LIMIT, web_safe_cursor=None, ids_only=False, user_key=None): \"\"\"Return", "web_safe_cursor: cursor = search.Cursor(web_safe_string=web_safe_cursor) else: cursor = None index =", "tag_field, private_field, user_key_field, query_options=None, user_key=None): self.query_str = query_str self.name_field =", "remove Card entities in the search facility: insert_cards([models.Card]) delete_cards([models.Card]) Query", "def _build_query_string(self): terms, names, tags = self._sanitize_user_input() # Our simply", "'.join(terms)) if names: parts.append('%s: (%s)' % (self.name_field, ' OR '.join(names)))", "self._sanitize_user_input() # Our simply query logic is to OR together", "query_options=None, user_key=None): self.query_str = query_str self.name_field = name_field self.tag_field =", "index.put(card_docs) def delete_cards(cards): \"\"\"Delete models.Card entities from the search facility.\"\"\"", "def _sanitize_user_input(query_str): # The search API puts special meaning on", "TODO(chris): should we include all fields that would be needed", "application-specific search semantics on top of App Engine's search API.", "doc def _card2docid(card): # We set the search.Document's ID to", "'.join(parts) def query(self): query = search.Query( query_string=self._build_query_string(), options=self.query_options) return query", "top of App Engine's search API. There are two chief", "will have the following fields: user_key, user_nickname, front, back, info,", "= map(_card2docid, cards) index.delete(card_doc_ids) def query_cards(query_str, limit=QUERY_LIMIT, web_safe_cursor=None, ids_only=False, user_key=None):", "% self.private_field if self.user_key: # ... but always show the", "search.AtomField(name='user_key', value=card.user_key.urlsafe()), # TODO(chris): is user_nickname always a direct-match #", "QUERY_LIMIT = 20 CARD_INDEX_NAME = 'cards' # Increase this value", "managing entities in the search facility. Add and remove Card", "it, and passes through a custom query processor before the", "it would be better if this module didn't know about", "Card entities: query_cards(query_string, limit=20) -> search.SearchResults The results items will", "e.g., @chris? search.AtomField(name='user_nickname', value=card.user_nickname), # TODO(chris): support HtmlField for richer", "possibly with @name and #tag tokens. name_field is the field", "facility: insert_cards([models.Card]) delete_cards([models.Card]) Query for Card entities: query_cards(query_string, limit=20) ->", "_sanitize_user_input(query_str) def _build_query_string(self): terms, names, tags = self._sanitize_user_input() # Our", "def _card2docid(card): # We set the search.Document's ID to the", "OR %s: (%s)' % (self.user_key_field, self.user_key) parts.append('(' + privacy +", "else: cursor = None index = search.Index(name=CARD_INDEX_NAME) query_processor = _QueryProcessor(", "should we include all fields that would be needed #", "query is submitted to App Engine. Notably, pass @username to", "query_cards(query_str, limit=QUERY_LIMIT, web_safe_cursor=None, ids_only=False, user_key=None): \"\"\"Return the search.SearchResults for a", "parts.append('%s: (%s)' % (self.name_field, ' OR '.join(names))) if tags: parts.append('%s:", "results. privacy += ' OR %s: (%s)' % (self.user_key_field, self.user_key)", "name_field is the field @name tokens should apply to. tag_field", "internal query language to users so # we strictly restrict", "API. There are two chief operations: querying for entities, and", "[] for token in query_str.split(): # TODO(chris): allow international characters.", "TODO(chris): support HtmlField for richer cards? search.TextField(name='front', value=card.front), search.TextField(name='back', value=card.back),", "restrict the query to entities authored by username, and #tag", "query_str.split(): # TODO(chris): allow international characters. sane_token = re.sub(r'[^a-zA-Z0-9._-]+', '',", "user_key_field, query_options=None, user_key=None): self.query_str = query_str self.name_field = name_field self.tag_field", "# we strictly restrict inputs. The rules are: # #", "tag filters (plus a privacy clause). parts = [] if", "index = search.Index(name=CARD_INDEX_NAME) card_doc_ids = map(_card2docid, cards) index.delete(card_doc_ids) def query_cards(query_str,", "OR '.join(tags))) # Don't return cards that other users have", "it mirrors. return card.key.urlsafe() def _sanitize_user_input(query_str): # The search API", "user their own cards in results. privacy += ' OR", "should this return partially-instantiated # models.Card instances instead of leaking", "didn't know about # specific entity types, but instead defined", "names.append(sane_token) elif token.startswith('#'): tags.append(sane_token) else: terms.append(sane_token) return terms, names, tags", "can determine the data available on returned documents. CARD_DOCUMENT_VERSION =", "instead of leaking implementation details # like we do now?", "sane_token: if sane_token in ('AND', 'OK'): continue # ignore special", "cards that other users have marked private... privacy = '%s:", "want to expose the internal query language to users so", "from the # user, then AND in the name or", "[a-zA-Z0-9._-]. # @name is removed and 'name' values returned as", "in results. privacy += ' OR %s: (%s)' % (self.user_key_field,", "google.appengine.api import search from google.appengine.ext import ndb QUERY_LIMIT = 20", "200 # TODO(chris): it would be better if this module", "results items will have the following fields: user_key, user_nickname, front,", "cursor = search.Cursor(web_safe_string=web_safe_cursor) else: cursor = None index = search.Index(name=CARD_INDEX_NAME)", "+ tag_fields) return doc def _card2docid(card): # We set the", "the search.SearchResults for a query. ids_only is useful because the", "(self.name_field, ' OR '.join(names))) if tags: parts.append('%s: (%s)' % (self.tag_field,", "special search keywords elif token.startswith('@'): names.append(sane_token) elif token.startswith('#'): tags.append(sane_token) else:", "querying for entities, and managing entities in the search facility.", "privacy = '%s: 0' % self.private_field if self.user_key: # ...", "= 'cards' # Increase this value when _card2doc changes its", "_build_query_string(self): terms, names, tags = self._sanitize_user_input() # Our simply query", "= [], [], [] for token in query_str.split(): # TODO(chris):", "own cards in results. privacy += ' OR %s: (%s)'", "a direct-match # shortname, e.g., @chris? search.AtomField(name='user_nickname', value=card.user_nickname), # TODO(chris):", "for richer cards? search.TextField(name='front', value=card.front), search.TextField(name='back', value=card.back), search.TextField(name='info', value=card.info), search.DateField(name='added',", "an OR query. \"\"\" import re from google.appengine.api import search", "and #tag to restrict the query to only documents matching", "to get # metadata from an entity and generate a", "entities from the search facility.\"\"\" index = search.Index(name=CARD_INDEX_NAME) card_doc_ids =", "support HtmlField for richer cards? search.TextField(name='front', value=card.front), search.TextField(name='back', value=card.back), search.TextField(name='info',", "source_url The query_string is free-form, as a user would enter", "entities authored by username, and #tag to restrict the query", "TODO(chris): should this return partially-instantiated # models.Card instances instead of", "expose the internal query language to users so # we", "when _card2doc changes its format so that # queries can", "enter it, and passes through a custom query processor before", "if tags: parts.append('%s: (%s)' % (self.tag_field, ' OR '.join(tags))) #", "implementation details # like we do now? return search_results def", "entity key it mirrors. return card.key.urlsafe() def _sanitize_user_input(query_str): # The", "cursor=cursor, ids_only=ids_only), user_key=user_key) search_results = index.search(query_processor.query()) # TODO(chris): should this", "' OR '.join(names))) if tags: parts.append('%s: (%s)' % (self.tag_field, '", "user would enter it, and passes through a custom query", "(%s)' % (self.name_field, ' OR '.join(names))) if tags: parts.append('%s: (%s)'", "if names: parts.append('%s: (%s)' % (self.name_field, ' OR '.join(names))) if", "determine the data available on returned documents. CARD_DOCUMENT_VERSION = '1'", "if card.private else \"0\"), ] + tag_fields) return doc def", "] + tag_fields) return doc def _card2docid(card): # We set", "delete_cards(cards): \"\"\"Delete models.Card entities from the search facility.\"\"\" index =", "<= 200, len(cards) card_docs = map(_card2doc, cards) index = search.Index(name=CARD_INDEX_NAME)", "def delete_cards(cards): \"\"\"Delete models.Card entities from the search facility.\"\"\" index", "import ndb QUERY_LIMIT = 20 CARD_INDEX_NAME = 'cards' # Increase", "types, but instead defined a protocol to get # metadata", "search semantics on top of App Engine's search API. There", "semantics on top of App Engine's search API. There are", "characters for values are [a-zA-Z0-9._-]. # @name is removed and", "in query_str.split(): # TODO(chris): allow international characters. sane_token = re.sub(r'[^a-zA-Z0-9._-]+',", "submitted to App Engine. Notably, pass @username to restrict the", "in the search facility: insert_cards([models.Card]) delete_cards([models.Card]) Query for Card entities:", "we do now? return search_results def _card2doc(card): # TODO(chris): should", "query language to users so # we strictly restrict inputs.", "There are two chief operations: querying for entities, and managing", "that # queries can determine the data available on returned", "characters. sane_token = re.sub(r'[^a-zA-Z0-9._-]+', '', token) if sane_token: if sane_token", "the name of the field #tag tokens should apply to.", "are two chief operations: querying for entities, and managing entities", "following fields: user_key, user_nickname, front, back, info, tag (repeated), added,", "from the search facility.\"\"\" index = search.Index(name=CARD_INDEX_NAME) card_doc_ids = map(_card2docid,", "value=card.source_url), search.AtomField(name='private', value=\"1\" if card.private else \"0\"), ] + tag_fields)", "len(cards) card_docs = map(_card2doc, cards) index = search.Index(name=CARD_INDEX_NAME) index.put(card_docs) def", "leaking implementation details # like we do now? return search_results", "'%s: 0' % self.private_field if self.user_key: # ... but always", "or update models.Card entities in the search facility.\"\"\" # TODO(chris):", "App Engine. Notably, pass @username to restrict the query to", "url-safe keys for models.Card entities. \"\"\" if web_safe_cursor: cursor =", "is the field @name tokens should apply to. tag_field is", "in ('AND', 'OK'): continue # ignore special search keywords elif", "be needed # for rendering a search results item to", "as a list. terms, names, tags = [], [], []", "+ ')') return ' AND '.join(parts) def query(self): query =", "else \"0\"), ] + tag_fields) return doc def _card2docid(card): #", "search.Index(name=CARD_INDEX_NAME) query_processor = _QueryProcessor( query_str, name_field='user_nickname', tag_field='tag', private_field='private', user_key_field='user_key', query_options=search.QueryOptions(limit=limit,", "# TODO(chris): support HtmlField for richer cards? search.TextField(name='front', value=card.front), search.TextField(name='back',", "user_key def _sanitize_user_input(self): query_str = self.query_str[:MAX_QUERY_LEN] return _sanitize_user_input(query_str) def _build_query_string(self):", "tags = [], [], [] for token in query_str.split(): #", "is to OR together all terms from the # user,", "= search.Document( doc_id=_card2docid(card), fields=[ search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key', value=card.user_key.urlsafe()), # TODO(chris):", "# We set the search.Document's ID to the entity key", "parts = [] if terms: parts.append(' OR '.join(terms)) if names:", "query. \"\"\" import re from google.appengine.api import search from google.appengine.ext", "OR '.join(terms)) if names: parts.append('%s: (%s)' % (self.name_field, ' OR", "matching the given tag. Multiple @usernames or #tags result in", "def query_cards(query_str, limit=QUERY_LIMIT, web_safe_cursor=None, ids_only=False, user_key=None): \"\"\"Return the search.SearchResults for", "the given tag. Multiple @usernames or #tags result in an", "tag_field='tag', private_field='private', user_key_field='user_key', query_options=search.QueryOptions(limit=limit, cursor=cursor, ids_only=ids_only), user_key=user_key) search_results = index.search(query_processor.query())", "limit=20) -> search.SearchResults The results items will have the following", "know about # specific entity types, but instead defined a", "2000 character limit from # https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN = 200 #", "key it mirrors. return card.key.urlsafe() def _sanitize_user_input(query_str): # The search", "card_docs = map(_card2doc, cards) index = search.Index(name=CARD_INDEX_NAME) index.put(card_docs) def delete_cards(cards):", "return _sanitize_user_input(query_str) def _build_query_string(self): terms, names, tags = self._sanitize_user_input() #", "# user, then AND in the name or tag filters", "models.Card entities from the search facility.\"\"\" index = search.Index(name=CARD_INDEX_NAME) card_doc_ids", "removed and 'name' values returned as a list. # #tag", "apply to. \"\"\" def __init__(self, query_str, name_field, tag_field, private_field, user_key_field,", "then AND in the name or tag filters (plus a", "'.join(names))) if tags: parts.append('%s: (%s)' % (self.tag_field, ' OR '.join(tags)))", "to the entity key it mirrors. return card.key.urlsafe() def _sanitize_user_input(query_str):", "the returned document IDs are url-safe keys for models.Card entities.", "(repeated), added, modified, source_url The query_string is free-form, as a", "all fields that would be needed # for rendering a", "simply query logic is to OR together all terms from", "search facility.\"\"\" index = search.Index(name=CARD_INDEX_NAME) card_doc_ids = map(_card2docid, cards) index.delete(card_doc_ids)", "tag (repeated), added, modified, source_url The query_string is free-form, as", "to only documents matching the given tag. Multiple @usernames or", "\"\"\"Return the search.SearchResults for a query. ids_only is useful because", "now? return search_results def _card2doc(card): # TODO(chris): should we include", "terms: parts.append(' OR '.join(terms)) if names: parts.append('%s: (%s)' % (self.name_field,", "IDs are url-safe keys for models.Card entities. \"\"\" if web_safe_cursor:", "the query to only documents matching the given tag. Multiple", "search facility. Add and remove Card entities in the search", "# Our simply query logic is to OR together all", "search.Cursor(web_safe_string=web_safe_cursor) else: cursor = None index = search.Index(name=CARD_INDEX_NAME) query_processor =", "entities. \"\"\" if web_safe_cursor: cursor = search.Cursor(web_safe_string=web_safe_cursor) else: cursor =", "for tag in card.tags] doc = search.Document( doc_id=_card2docid(card), fields=[ search.AtomField(name='doc_version',", "partially-instantiated # models.Card instances instead of leaking implementation details #", "private_field, user_key_field, query_options=None, user_key=None): self.query_str = query_str self.name_field = name_field", "by username, and #tag to restrict the query to only", "implements application-specific search semantics on top of App Engine's search", "0' % self.private_field if self.user_key: # ... but always show", "user_key=None): self.query_str = query_str self.name_field = name_field self.tag_field = tag_field", "the user their own cards in results. privacy += '", "strictly restrict inputs. The rules are: # # Allowed characters", "changes its format so that # queries can determine the", "a document. def insert_cards(cards): \"\"\"Insert or update models.Card entities in", "inputs and we # don't want to expose the internal", "restrict the query to only documents matching the given tag.", "tag in card.tags] doc = search.Document( doc_id=_card2docid(card), fields=[ search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION),", "removed and 'tag' values returned as a list. terms, names,", "'name' values returned as a list. # #tag is removed", "in the search facility.\"\"\" # TODO(chris): should we allow more", "and 'tag' values returned as a list. terms, names, tags", "two chief operations: querying for entities, and managing entities in", "self.user_key: # ... but always show the user their own", "models.Card entities. \"\"\" if web_safe_cursor: cursor = search.Cursor(web_safe_string=web_safe_cursor) else: cursor", "# don't want to expose the internal query language to", "more than 200 cards per call? assert len(cards) <= 200,", "index = search.Index(name=CARD_INDEX_NAME) index.put(card_docs) def delete_cards(cards): \"\"\"Delete models.Card entities from", "keywords elif token.startswith('@'): names.append(sane_token) elif token.startswith('#'): tags.append(sane_token) else: terms.append(sane_token) return", "queries can determine the data available on returned documents. CARD_DOCUMENT_VERSION", "language to users so # we strictly restrict inputs. The", "= self.query_str[:MAX_QUERY_LEN] return _sanitize_user_input(query_str) def _build_query_string(self): terms, names, tags =", "= re.sub(r'[^a-zA-Z0-9._-]+', '', token) if sane_token: if sane_token in ('AND',", "search.TextField(name='back', value=card.back), search.TextField(name='info', value=card.info), search.DateField(name='added', value=card.added), search.DateField(name='modified', value=card.modified), search.AtomField(name='source_url', value=card.source_url),", "query_options=search.QueryOptions(limit=limit, cursor=cursor, ids_only=ids_only), user_key=user_key) search_results = index.search(query_processor.query()) # TODO(chris): should", "processor before the query is submitted to App Engine. Notably,", "@name and #tag tokens. name_field is the field @name tokens", "a protocol to get # metadata from an entity and", "field @name tokens should apply to. tag_field is the name", "we're under the 2000 character limit from # https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN", "we # don't want to expose the internal query language", "import re from google.appengine.api import search from google.appengine.ext import ndb", "format so that # queries can determine the data available", "user_key=user_key) search_results = index.search(query_processor.query()) # TODO(chris): should this return partially-instantiated", "user_key=None): \"\"\"Return the search.SearchResults for a query. ids_only is useful", "and we # don't want to expose the internal query", "and passes through a custom query processor before the query", "from # https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN = 200 # TODO(chris): it would", "of the field #tag tokens should apply to. \"\"\" def", "search.AtomField(name='private', value=\"1\" if card.private else \"0\"), ] + tag_fields) return", "return card.key.urlsafe() def _sanitize_user_input(query_str): # The search API puts special", "value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key', value=card.user_key.urlsafe()), # TODO(chris): is user_nickname always a direct-match", "would be better if this module didn't know about #", "and 'name' values returned as a list. # #tag is", "the search.Document's ID to the entity key it mirrors. return", "returned as a list. terms, names, tags = [], [],", "#tag tokens should apply to. \"\"\" def __init__(self, query_str, name_field,", "token in query_str.split(): # TODO(chris): allow international characters. sane_token =", "elif token.startswith('@'): names.append(sane_token) elif token.startswith('#'): tags.append(sane_token) else: terms.append(sane_token) return terms,", "direct-match # shortname, e.g., @chris? search.AtomField(name='user_nickname', value=card.user_nickname), # TODO(chris): support", "value=card.modified), search.AtomField(name='source_url', value=card.source_url), search.AtomField(name='private', value=\"1\" if card.private else \"0\"), ]", "@chris? search.AtomField(name='user_nickname', value=card.user_nickname), # TODO(chris): support HtmlField for richer cards?", "query logic is to OR together all terms from the", "if self.user_key: # ... but always show the user their", "together all terms from the # user, then AND in", "users so # we strictly restrict inputs. The rules are:", "sane_token = re.sub(r'[^a-zA-Z0-9._-]+', '', token) if sane_token: if sane_token in", "user_key, user_nickname, front, back, info, tag (repeated), added, modified, source_url", "search facility: insert_cards([models.Card]) delete_cards([models.Card]) Query for Card entities: query_cards(query_string, limit=20)", "# TODO(chris): should this return partially-instantiated # models.Card instances instead", "be better if this module didn't know about # specific", "authored by username, and #tag to restrict the query to", "data available on returned documents. CARD_DOCUMENT_VERSION = '1' # Ensure", "(%s)' % (self.user_key_field, self.user_key) parts.append('(' + privacy + ')') return", "is removed and 'tag' values returned as a list. terms,", "and managing entities in the search facility. Add and remove", "to expose the internal query language to users so #", "custom query processor before the query is submitted to App", "module implements application-specific search semantics on top of App Engine's", "The search API puts special meaning on certain inputs and", "TODO(chris): is user_nickname always a direct-match # shortname, e.g., @chris?", "self.name_field = name_field self.tag_field = tag_field self.private_field = private_field self.user_key_field", "index.search(query_processor.query()) # TODO(chris): should this return partially-instantiated # models.Card instances", "to entities authored by username, and #tag to restrict the", "self.query_str[:MAX_QUERY_LEN] return _sanitize_user_input(query_str) def _build_query_string(self): terms, names, tags = self._sanitize_user_input()", "to users so # we strictly restrict inputs. The rules", "'.join(tags))) # Don't return cards that other users have marked", "AND in the name or tag filters (plus a privacy", "defined a protocol to get # metadata from an entity", "but always show the user their own cards in results.", "user_nickname always a direct-match # shortname, e.g., @chris? search.AtomField(name='user_nickname', value=card.user_nickname),", "if web_safe_cursor: cursor = search.Cursor(web_safe_string=web_safe_cursor) else: cursor = None index", "search_results = index.search(query_processor.query()) # TODO(chris): should this return partially-instantiated #", "card.private else \"0\"), ] + tag_fields) return doc def _card2docid(card):", "fields that would be needed # for rendering a search", "query_str = self.query_str[:MAX_QUERY_LEN] return _sanitize_user_input(query_str) def _build_query_string(self): terms, names, tags", "instead defined a protocol to get # metadata from an", "= search.Index(name=CARD_INDEX_NAME) query_processor = _QueryProcessor( query_str, name_field='user_nickname', tag_field='tag', private_field='private', user_key_field='user_key',", "return cards that other users have marked private... privacy =", "= '1' # Ensure we're under the 2000 character limit", "terms, names, tags = [], [], [] for token in", "terms.append(sane_token) return terms, names, tags class _QueryProcessor(object): \"\"\"Simple queries, possibly", "+= ' OR %s: (%s)' % (self.user_key_field, self.user_key) parts.append('(' +", "ids_only=False, user_key=None): \"\"\"Return the search.SearchResults for a query. ids_only is", "_QueryProcessor( query_str, name_field='user_nickname', tag_field='tag', private_field='private', user_key_field='user_key', query_options=search.QueryOptions(limit=limit, cursor=cursor, ids_only=ids_only), user_key=user_key)", "search.Index(name=CARD_INDEX_NAME) card_doc_ids = map(_card2docid, cards) index.delete(card_doc_ids) def query_cards(query_str, limit=QUERY_LIMIT, web_safe_cursor=None,", "in the search facility. Add and remove Card entities in", "'OK'): continue # ignore special search keywords elif token.startswith('@'): names.append(sane_token)", "limit=QUERY_LIMIT, web_safe_cursor=None, ids_only=False, user_key=None): \"\"\"Return the search.SearchResults for a query.", "certain inputs and we # don't want to expose the", "# Ensure we're under the 2000 character limit from #", "details # like we do now? return search_results def _card2doc(card):", "do now? return search_results def _card2doc(card): # TODO(chris): should we", "if sane_token in ('AND', 'OK'): continue # ignore special search", "Engine. Notably, pass @username to restrict the query to entities", "metadata from an entity and generate a document. def insert_cards(cards):", "ids_only=ids_only), user_key=user_key) search_results = index.search(query_processor.query()) # TODO(chris): should this return", "for rendering a search results item to avoid entity lookup?", "self.user_key_field = user_key_field self.query_options = query_options self.user_key = user_key def", "is useful because the returned document IDs are url-safe keys", "protocol to get # metadata from an entity and generate", "= name_field self.tag_field = tag_field self.private_field = private_field self.user_key_field =", "we allow more than 200 cards per call? assert len(cards)", "ignore special search keywords elif token.startswith('@'): names.append(sane_token) elif token.startswith('#'): tags.append(sane_token)", "Add and remove Card entities in the search facility: insert_cards([models.Card])", "we include all fields that would be needed # for", "search.DateField(name='added', value=card.added), search.DateField(name='modified', value=card.modified), search.AtomField(name='source_url', value=card.source_url), search.AtomField(name='private', value=\"1\" if card.private", "terms from the # user, then AND in the name", "the search facility. Add and remove Card entities in the", "as a list. # #tag is removed and 'tag' values", "def __init__(self, query_str, name_field, tag_field, private_field, user_key_field, query_options=None, user_key=None): self.query_str", "rules are: # # Allowed characters for values are [a-zA-Z0-9._-].", "facility. Add and remove Card entities in the search facility:", "\"\"\"Simple queries, possibly with @name and #tag tokens. name_field is", "token.startswith('@'): names.append(sane_token) elif token.startswith('#'): tags.append(sane_token) else: terms.append(sane_token) return terms, names,", "the data available on returned documents. CARD_DOCUMENT_VERSION = '1' #", "self.tag_field = tag_field self.private_field = private_field self.user_key_field = user_key_field self.query_options", "OR together all terms from the # user, then AND", "entity types, but instead defined a protocol to get #", "terms, names, tags = self._sanitize_user_input() # Our simply query logic", "the search facility.\"\"\" # TODO(chris): should we allow more than", "values are [a-zA-Z0-9._-]. # @name is removed and 'name' values", "= 20 CARD_INDEX_NAME = 'cards' # Increase this value when", "value=card.back), search.TextField(name='info', value=card.info), search.DateField(name='added', value=card.added), search.DateField(name='modified', value=card.modified), search.AtomField(name='source_url', value=card.source_url), search.AtomField(name='private',", "search.Document's ID to the entity key it mirrors. return card.key.urlsafe()", "self.query_options = query_options self.user_key = user_key def _sanitize_user_input(self): query_str =", "field #tag tokens should apply to. \"\"\" def __init__(self, query_str,", "return ' AND '.join(parts) def query(self): query = search.Query( query_string=self._build_query_string(),", "logic is to OR together all terms from the #", "models.Card entities in the search facility.\"\"\" # TODO(chris): should we", "documents. CARD_DOCUMENT_VERSION = '1' # Ensure we're under the 2000", "query_string is free-form, as a user would enter it, and", "facility.\"\"\" # TODO(chris): should we allow more than 200 cards", "their own cards in results. privacy += ' OR %s:", "value=\"1\" if card.private else \"0\"), ] + tag_fields) return doc", "for values are [a-zA-Z0-9._-]. # @name is removed and 'name'", "ids_only is useful because the returned document IDs are url-safe", "entities in the search facility: insert_cards([models.Card]) delete_cards([models.Card]) Query for Card", "given tag. Multiple @usernames or #tags result in an OR", "puts special meaning on certain inputs and we # don't", "lookup? tag_fields = [search.AtomField(name='tag', value=tag) for tag in card.tags] doc", "its format so that # queries can determine the data", "a privacy clause). parts = [] if terms: parts.append(' OR", "-> search.SearchResults The results items will have the following fields:", "front, back, info, tag (repeated), added, modified, source_url The query_string", "search.AtomField(name='user_nickname', value=card.user_nickname), # TODO(chris): support HtmlField for richer cards? search.TextField(name='front',", "[], [] for token in query_str.split(): # TODO(chris): allow international", "search.DateField(name='modified', value=card.modified), search.AtomField(name='source_url', value=card.source_url), search.AtomField(name='private', value=\"1\" if card.private else \"0\"),", "list. terms, names, tags = [], [], [] for token", "index = search.Index(name=CARD_INDEX_NAME) query_processor = _QueryProcessor( query_str, name_field='user_nickname', tag_field='tag', private_field='private',", "and generate a document. def insert_cards(cards): \"\"\"Insert or update models.Card", "if this module didn't know about # specific entity types,", "international characters. sane_token = re.sub(r'[^a-zA-Z0-9._-]+', '', token) if sane_token: if", "user_key_field self.query_options = query_options self.user_key = user_key def _sanitize_user_input(self): query_str", "\"\"\"Insert or update models.Card entities in the search facility.\"\"\" #", "mirrors. return card.key.urlsafe() def _sanitize_user_input(query_str): # The search API puts", "is user_nickname always a direct-match # shortname, e.g., @chris? search.AtomField(name='user_nickname',", "apply to. tag_field is the name of the field #tag", "#tag to restrict the query to only documents matching the", "about # specific entity types, but instead defined a protocol", "import search from google.appengine.ext import ndb QUERY_LIMIT = 20 CARD_INDEX_NAME", "entity lookup? tag_fields = [search.AtomField(name='tag', value=tag) for tag in card.tags]", "The rules are: # # Allowed characters for values are", "only documents matching the given tag. Multiple @usernames or #tags", "set the search.Document's ID to the entity key it mirrors.", "for token in query_str.split(): # TODO(chris): allow international characters. sane_token", "the following fields: user_key, user_nickname, front, back, info, tag (repeated),", "that would be needed # for rendering a search results", "for Card entities: query_cards(query_string, limit=20) -> search.SearchResults The results items", "@name is removed and 'name' values returned as a list.", "insert_cards(cards): \"\"\"Insert or update models.Card entities in the search facility.\"\"\"", "results item to avoid entity lookup? tag_fields = [search.AtomField(name='tag', value=tag)", "the field #tag tokens should apply to. \"\"\" def __init__(self,", "%s: (%s)' % (self.user_key_field, self.user_key) parts.append('(' + privacy + ')')", "before the query is submitted to App Engine. Notably, pass", "names: parts.append('%s: (%s)' % (self.name_field, ' OR '.join(names))) if tags:", "#tags result in an OR query. \"\"\" import re from", "map(_card2doc, cards) index = search.Index(name=CARD_INDEX_NAME) index.put(card_docs) def delete_cards(cards): \"\"\"Delete models.Card", "filters (plus a privacy clause). parts = [] if terms:", "value=card.user_key.urlsafe()), # TODO(chris): is user_nickname always a direct-match # shortname,", "entities in the search facility. Add and remove Card entities", "# @name is removed and 'name' values returned as a", "better if this module didn't know about # specific entity", "query_processor = _QueryProcessor( query_str, name_field='user_nickname', tag_field='tag', private_field='private', user_key_field='user_key', query_options=search.QueryOptions(limit=limit, cursor=cursor,", "we strictly restrict inputs. The rules are: # # Allowed", "values returned as a list. terms, names, tags = [],", "names, tags = [], [], [] for token in query_str.split():", "richer cards? search.TextField(name='front', value=card.front), search.TextField(name='back', value=card.back), search.TextField(name='info', value=card.info), search.DateField(name='added', value=card.added),", "entities, and managing entities in the search facility. Add and", "but instead defined a protocol to get # metadata from", "(self.tag_field, ' OR '.join(tags))) # Don't return cards that other", "name of the field #tag tokens should apply to. \"\"\"", "the search facility.\"\"\" index = search.Index(name=CARD_INDEX_NAME) card_doc_ids = map(_card2docid, cards)", "value=card.added), search.DateField(name='modified', value=card.modified), search.AtomField(name='source_url', value=card.source_url), search.AtomField(name='private', value=\"1\" if card.private else", "of App Engine's search API. There are two chief operations:", "character limit from # https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN = 200 # TODO(chris):", "= map(_card2doc, cards) index = search.Index(name=CARD_INDEX_NAME) index.put(card_docs) def delete_cards(cards): \"\"\"Delete", "allow international characters. sane_token = re.sub(r'[^a-zA-Z0-9._-]+', '', token) if sane_token:", "that other users have marked private... privacy = '%s: 0'", "assert len(cards) <= 200, len(cards) card_docs = map(_card2doc, cards) index", "doc_id=_card2docid(card), fields=[ search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key', value=card.user_key.urlsafe()), # TODO(chris): is user_nickname", "class _QueryProcessor(object): \"\"\"Simple queries, possibly with @name and #tag tokens.", "avoid entity lookup? tag_fields = [search.AtomField(name='tag', value=tag) for tag in", "or #tags result in an OR query. \"\"\" import re", "# TODO(chris): allow international characters. sane_token = re.sub(r'[^a-zA-Z0-9._-]+', '', token)", "search from google.appengine.ext import ndb QUERY_LIMIT = 20 CARD_INDEX_NAME =", "items will have the following fields: user_key, user_nickname, front, back,", "item to avoid entity lookup? tag_fields = [search.AtomField(name='tag', value=tag) for", "tag_field is the name of the field #tag tokens should", "info, tag (repeated), added, modified, source_url The query_string is free-form,", "instances instead of leaking implementation details # like we do", "module didn't know about # specific entity types, but instead", "doc = search.Document( doc_id=_card2docid(card), fields=[ search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key', value=card.user_key.urlsafe()), #", "a list. # #tag is removed and 'tag' values returned", "are: # # Allowed characters for values are [a-zA-Z0-9._-]. #", "shortname, e.g., @chris? search.AtomField(name='user_nickname', value=card.user_nickname), # TODO(chris): support HtmlField for", "queries, possibly with @name and #tag tokens. name_field is the", "generate a document. def insert_cards(cards): \"\"\"Insert or update models.Card entities", "should apply to. \"\"\" def __init__(self, query_str, name_field, tag_field, private_field,", "value=tag) for tag in card.tags] doc = search.Document( doc_id=_card2docid(card), fields=[", "[] if terms: parts.append(' OR '.join(terms)) if names: parts.append('%s: (%s)'", "# TODO(chris): should we include all fields that would be", "if terms: parts.append(' OR '.join(terms)) if names: parts.append('%s: (%s)' %", "delete_cards([models.Card]) Query for Card entities: query_cards(query_string, limit=20) -> search.SearchResults The", "self.query_str = query_str self.name_field = name_field self.tag_field = tag_field self.private_field", "TODO(chris): allow international characters. sane_token = re.sub(r'[^a-zA-Z0-9._-]+', '', token) if", "always show the user their own cards in results. privacy", "tags = self._sanitize_user_input() # Our simply query logic is to", "= query_str self.name_field = name_field self.tag_field = tag_field self.private_field =", "to. tag_field is the name of the field #tag tokens", "Card entities in the search facility: insert_cards([models.Card]) delete_cards([models.Card]) Query for", "operations: querying for entities, and managing entities in the search", "would be needed # for rendering a search results item", "@usernames or #tags result in an OR query. \"\"\" import", "card.tags] doc = search.Document( doc_id=_card2docid(card), fields=[ search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key', value=card.user_key.urlsafe()),", "query_cards(query_string, limit=20) -> search.SearchResults The results items will have the", "search.TextField(name='info', value=card.info), search.DateField(name='added', value=card.added), search.DateField(name='modified', value=card.modified), search.AtomField(name='source_url', value=card.source_url), search.AtomField(name='private', value=\"1\"", "' OR '.join(tags))) # Don't return cards that other users", "\"\"\"Delete models.Card entities from the search facility.\"\"\" index = search.Index(name=CARD_INDEX_NAME)", "(self.user_key_field, self.user_key) parts.append('(' + privacy + ')') return ' AND", "# The search API puts special meaning on certain inputs", "tag. Multiple @usernames or #tags result in an OR query.", "so # we strictly restrict inputs. The rules are: #", "= search.Index(name=CARD_INDEX_NAME) card_doc_ids = map(_card2docid, cards) index.delete(card_doc_ids) def query_cards(query_str, limit=QUERY_LIMIT,", "tokens should apply to. tag_field is the name of the", "names, tags class _QueryProcessor(object): \"\"\"Simple queries, possibly with @name and", "This module implements application-specific search semantics on top of App", "_sanitize_user_input(self): query_str = self.query_str[:MAX_QUERY_LEN] return _sanitize_user_input(query_str) def _build_query_string(self): terms, names,", "facility.\"\"\" index = search.Index(name=CARD_INDEX_NAME) card_doc_ids = map(_card2docid, cards) index.delete(card_doc_ids) def", "this return partially-instantiated # models.Card instances instead of leaking implementation", "returned documents. CARD_DOCUMENT_VERSION = '1' # Ensure we're under the", "returned as a list. # #tag is removed and 'tag'", "and remove Card entities in the search facility: insert_cards([models.Card]) delete_cards([models.Card])", "_card2docid(card): # We set the search.Document's ID to the entity", "return doc def _card2docid(card): # We set the search.Document's ID", "HtmlField for richer cards? search.TextField(name='front', value=card.front), search.TextField(name='back', value=card.back), search.TextField(name='info', value=card.info),", "return terms, names, tags class _QueryProcessor(object): \"\"\"Simple queries, possibly with", "_card2doc changes its format so that # queries can determine", "value=card.front), search.TextField(name='back', value=card.back), search.TextField(name='info', value=card.info), search.DateField(name='added', value=card.added), search.DateField(name='modified', value=card.modified), search.AtomField(name='source_url',", "= user_key_field self.query_options = query_options self.user_key = user_key def _sanitize_user_input(self):", "pass @username to restrict the query to entities authored by", "(plus a privacy clause). parts = [] if terms: parts.append('", "user, then AND in the name or tag filters (plus", "under the 2000 character limit from # https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN =", "ID to the entity key it mirrors. return card.key.urlsafe() def", "this value when _card2doc changes its format so that #", "cards) index = search.Index(name=CARD_INDEX_NAME) index.put(card_docs) def delete_cards(cards): \"\"\"Delete models.Card entities", "insert_cards([models.Card]) delete_cards([models.Card]) Query for Card entities: query_cards(query_string, limit=20) -> search.SearchResults", "# like we do now? return search_results def _card2doc(card): #", "# metadata from an entity and generate a document. def", "\"0\"), ] + tag_fields) return doc def _card2docid(card): # We", "else: terms.append(sane_token) return terms, names, tags class _QueryProcessor(object): \"\"\"Simple queries,", "search facility.\"\"\" # TODO(chris): should we allow more than 200", "#tag tokens. name_field is the field @name tokens should apply", "username, and #tag to restrict the query to only documents", "\"\"\" def __init__(self, query_str, name_field, tag_field, private_field, user_key_field, query_options=None, user_key=None):", "value=card.info), search.DateField(name='added', value=card.added), search.DateField(name='modified', value=card.modified), search.AtomField(name='source_url', value=card.source_url), search.AtomField(name='private', value=\"1\" if", "search.SearchResults for a query. ids_only is useful because the returned", "token.startswith('#'): tags.append(sane_token) else: terms.append(sane_token) return terms, names, tags class _QueryProcessor(object):", "list. # #tag is removed and 'tag' values returned as", "OR query. \"\"\" import re from google.appengine.api import search from", "#tag is removed and 'tag' values returned as a list.", "# https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN = 200 # TODO(chris): it would be", "in card.tags] doc = search.Document( doc_id=_card2docid(card), fields=[ search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key',", "like we do now? return search_results def _card2doc(card): # TODO(chris):", "= 200 # TODO(chris): it would be better if this", "_QueryProcessor(object): \"\"\"Simple queries, possibly with @name and #tag tokens. name_field", "private_field self.user_key_field = user_key_field self.query_options = query_options self.user_key = user_key", "search.Index(name=CARD_INDEX_NAME) index.put(card_docs) def delete_cards(cards): \"\"\"Delete models.Card entities from the search", "search API. This module implements application-specific search semantics on top", "parts.append('(' + privacy + ')') return ' AND '.join(parts) def", "modified, source_url The query_string is free-form, as a user would", "chief operations: querying for entities, and managing entities in the", "include all fields that would be needed # for rendering", "documents matching the given tag. Multiple @usernames or #tags result", "needed # for rendering a search results item to avoid", "in an OR query. \"\"\" import re from google.appengine.api import", "[search.AtomField(name='tag', value=tag) for tag in card.tags] doc = search.Document( doc_id=_card2docid(card),", "parts.append(' OR '.join(terms)) if names: parts.append('%s: (%s)' % (self.name_field, '", "on top of App Engine's search API. There are two", "The results items will have the following fields: user_key, user_nickname,", "don't want to expose the internal query language to users", "is removed and 'name' values returned as a list. #", "query_str self.name_field = name_field self.tag_field = tag_field self.private_field = private_field", "... but always show the user their own cards in", "@name tokens should apply to. tag_field is the name of", "# for rendering a search results item to avoid entity", "Don't return cards that other users have marked private... privacy", "free-form, as a user would enter it, and passes through", "def insert_cards(cards): \"\"\"Insert or update models.Card entities in the search", "search keywords elif token.startswith('@'): names.append(sane_token) elif token.startswith('#'): tags.append(sane_token) else: terms.append(sane_token)", "Engine's search API. There are two chief operations: querying for", "# #tag is removed and 'tag' values returned as a", "def _card2doc(card): # TODO(chris): should we include all fields that", "None index = search.Index(name=CARD_INDEX_NAME) query_processor = _QueryProcessor( query_str, name_field='user_nickname', tag_field='tag',", "Our simply query logic is to OR together all terms", "fields=[ search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key', value=card.user_key.urlsafe()), # TODO(chris): is user_nickname always", "if sane_token: if sane_token in ('AND', 'OK'): continue # ignore", "per call? assert len(cards) <= 200, len(cards) card_docs = map(_card2doc,", "to restrict the query to only documents matching the given", "self.user_key) parts.append('(' + privacy + ')') return ' AND '.join(parts)", "name or tag filters (plus a privacy clause). parts =", "user_key_field='user_key', query_options=search.QueryOptions(limit=limit, cursor=cursor, ids_only=ids_only), user_key=user_key) search_results = index.search(query_processor.query()) # TODO(chris):", "search API puts special meaning on certain inputs and we", "marked private... privacy = '%s: 0' % self.private_field if self.user_key:", "search API. There are two chief operations: querying for entities,", "the search facility: insert_cards([models.Card]) delete_cards([models.Card]) Query for Card entities: query_cards(query_string,", "have the following fields: user_key, user_nickname, front, back, info, tag", "google.appengine.ext import ndb QUERY_LIMIT = 20 CARD_INDEX_NAME = 'cards' #", "'1' # Ensure we're under the 2000 character limit from", "keys for models.Card entities. \"\"\" if web_safe_cursor: cursor = search.Cursor(web_safe_string=web_safe_cursor)", "\"\"\" import re from google.appengine.api import search from google.appengine.ext import", "this module didn't know about # specific entity types, but", "in the name or tag filters (plus a privacy clause).", "and #tag tokens. name_field is the field @name tokens should", "or tag filters (plus a privacy clause). parts = []", "the name or tag filters (plus a privacy clause). parts", "with @name and #tag tokens. name_field is the field @name", "# TODO(chris): should we allow more than 200 cards per", "to OR together all terms from the # user, then", "Multiple @usernames or #tags result in an OR query. \"\"\"", "# specific entity types, but instead defined a protocol to", "return partially-instantiated # models.Card instances instead of leaking implementation details", "other users have marked private... privacy = '%s: 0' %", "# TODO(chris): it would be better if this module didn't", "from an entity and generate a document. def insert_cards(cards): \"\"\"Insert", "def _sanitize_user_input(self): query_str = self.query_str[:MAX_QUERY_LEN] return _sanitize_user_input(query_str) def _build_query_string(self): terms,", "on certain inputs and we # don't want to expose", "for a query. ids_only is useful because the returned document", "should apply to. tag_field is the name of the field", "CARD_DOCUMENT_VERSION = '1' # Ensure we're under the 2000 character", "restrict inputs. The rules are: # # Allowed characters for", "= self._sanitize_user_input() # Our simply query logic is to OR", "to restrict the query to entities authored by username, and", "have marked private... privacy = '%s: 0' % self.private_field if", "document. def insert_cards(cards): \"\"\"Insert or update models.Card entities in the", "# models.Card instances instead of leaking implementation details # like", "than 200 cards per call? assert len(cards) <= 200, len(cards)", "parts.append('%s: (%s)' % (self.tag_field, ' OR '.join(tags))) # Don't return", "self.private_field = private_field self.user_key_field = user_key_field self.query_options = query_options self.user_key", "query to entities authored by username, and #tag to restrict", "'cards' # Increase this value when _card2doc changes its format", "privacy += ' OR %s: (%s)' % (self.user_key_field, self.user_key) parts.append('('", "call? assert len(cards) <= 200, len(cards) card_docs = map(_card2doc, cards)", "values returned as a list. # #tag is removed and", "user_nickname, front, back, info, tag (repeated), added, modified, source_url The", "result in an OR query. \"\"\" import re from google.appengine.api", "= [search.AtomField(name='tag', value=tag) for tag in card.tags] doc = search.Document(", "search.TextField(name='front', value=card.front), search.TextField(name='back', value=card.back), search.TextField(name='info', value=card.info), search.DateField(name='added', value=card.added), search.DateField(name='modified', value=card.modified),", "should we allow more than 200 cards per call? assert", "private_field='private', user_key_field='user_key', query_options=search.QueryOptions(limit=limit, cursor=cursor, ids_only=ids_only), user_key=user_key) search_results = index.search(query_processor.query()) #", "on returned documents. CARD_DOCUMENT_VERSION = '1' # Ensure we're under", "We set the search.Document's ID to the entity key it", "# Allowed characters for values are [a-zA-Z0-9._-]. # @name is", "is submitted to App Engine. Notably, pass @username to restrict", "TODO(chris): it would be better if this module didn't know", "returned document IDs are url-safe keys for models.Card entities. \"\"\"", "Allowed characters for values are [a-zA-Z0-9._-]. # @name is removed", "models.Card instances instead of leaking implementation details # like we", "for entities, and managing entities in the search facility. Add", "tags class _QueryProcessor(object): \"\"\"Simple queries, possibly with @name and #tag", "the entity key it mirrors. return card.key.urlsafe() def _sanitize_user_input(query_str): #", "show the user their own cards in results. privacy +=", "# Increase this value when _card2doc changes its format so", "API puts special meaning on certain inputs and we #", "# Don't return cards that other users have marked private...", "% (self.tag_field, ' OR '.join(tags))) # Don't return cards that", "= None index = search.Index(name=CARD_INDEX_NAME) query_processor = _QueryProcessor( query_str, name_field='user_nickname',", "card.key.urlsafe() def _sanitize_user_input(query_str): # The search API puts special meaning", "because the returned document IDs are url-safe keys for models.Card", "specific entity types, but instead defined a protocol to get", "inputs. The rules are: # # Allowed characters for values", "is free-form, as a user would enter it, and passes", "_sanitize_user_input(query_str): # The search API puts special meaning on certain", "a custom query processor before the query is submitted to", "are url-safe keys for models.Card entities. \"\"\" if web_safe_cursor: cursor", "the query to entities authored by username, and #tag to", "search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key', value=card.user_key.urlsafe()), # TODO(chris): is user_nickname always a", "meaning on certain inputs and we # don't want to", "')') return ' AND '.join(parts) def query(self): query = search.Query(", "the query is submitted to App Engine. Notably, pass @username", "to App Engine. Notably, pass @username to restrict the query", "from google.appengine.api import search from google.appengine.ext import ndb QUERY_LIMIT =", "cards per call? assert len(cards) <= 200, len(cards) card_docs =", "name_field, tag_field, private_field, user_key_field, query_options=None, user_key=None): self.query_str = query_str self.name_field", "re from google.appengine.api import search from google.appengine.ext import ndb QUERY_LIMIT", "' OR %s: (%s)' % (self.user_key_field, self.user_key) parts.append('(' + privacy", "App Engine's search API. There are two chief operations: querying", "return search_results def _card2doc(card): # TODO(chris): should we include all", "self.user_key = user_key def _sanitize_user_input(self): query_str = self.query_str[:MAX_QUERY_LEN] return _sanitize_user_input(query_str)", "entity and generate a document. def insert_cards(cards): \"\"\"Insert or update", "card_doc_ids = map(_card2docid, cards) index.delete(card_doc_ids) def query_cards(query_str, limit=QUERY_LIMIT, web_safe_cursor=None, ids_only=False,", "the 2000 character limit from # https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN = 200", "terms, names, tags class _QueryProcessor(object): \"\"\"Simple queries, possibly with @name", "tag_fields = [search.AtomField(name='tag', value=tag) for tag in card.tags] doc =", "@username to restrict the query to entities authored by username,", "query_str, name_field, tag_field, private_field, user_key_field, query_options=None, user_key=None): self.query_str = query_str", "The query_string is free-form, as a user would enter it,", "= search.Cursor(web_safe_string=web_safe_cursor) else: cursor = None index = search.Index(name=CARD_INDEX_NAME) query_processor", "token) if sane_token: if sane_token in ('AND', 'OK'): continue #", "Notably, pass @username to restrict the query to entities authored", "always a direct-match # shortname, e.g., @chris? search.AtomField(name='user_nickname', value=card.user_nickname), #", "document IDs are url-safe keys for models.Card entities. \"\"\" if", "# # Allowed characters for values are [a-zA-Z0-9._-]. # @name", "query_str, name_field='user_nickname', tag_field='tag', private_field='private', user_key_field='user_key', query_options=search.QueryOptions(limit=limit, cursor=cursor, ids_only=ids_only), user_key=user_key) search_results", "are [a-zA-Z0-9._-]. # @name is removed and 'name' values returned", "200, len(cards) card_docs = map(_card2doc, cards) index = search.Index(name=CARD_INDEX_NAME) index.put(card_docs)", "through a custom query processor before the query is submitted", "all terms from the # user, then AND in the", "= private_field self.user_key_field = user_key_field self.query_options = query_options self.user_key =", "passes through a custom query processor before the query is", "query to only documents matching the given tag. Multiple @usernames", "[], [], [] for token in query_str.split(): # TODO(chris): allow", "a list. terms, names, tags = [], [], [] for", "a search results item to avoid entity lookup? tag_fields =", "the field @name tokens should apply to. tag_field is the", "('AND', 'OK'): continue # ignore special search keywords elif token.startswith('@'):", "sane_token in ('AND', 'OK'): continue # ignore special search keywords", "% (self.user_key_field, self.user_key) parts.append('(' + privacy + ')') return '", "# queries can determine the data available on returned documents.", "20 CARD_INDEX_NAME = 'cards' # Increase this value when _card2doc", "tag_fields) return doc def _card2docid(card): # We set the search.Document's", "names, tags = self._sanitize_user_input() # Our simply query logic is", "len(cards) <= 200, len(cards) card_docs = map(_card2doc, cards) index =", "cards in results. privacy += ' OR %s: (%s)' %", "update models.Card entities in the search facility.\"\"\" # TODO(chris): should", "as a user would enter it, and passes through a", "% (self.name_field, ' OR '.join(names))) if tags: parts.append('%s: (%s)' %", "= query_options self.user_key = user_key def _sanitize_user_input(self): query_str = self.query_str[:MAX_QUERY_LEN]", "TODO(chris): should we allow more than 200 cards per call?", "'tag' values returned as a list. terms, names, tags =", "limit from # https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN = 200 # TODO(chris): it", "MAX_QUERY_LEN = 200 # TODO(chris): it would be better if", "API. This module implements application-specific search semantics on top of", "search.AtomField(name='source_url', value=card.source_url), search.AtomField(name='private', value=\"1\" if card.private else \"0\"), ] +", "name_field='user_nickname', tag_field='tag', private_field='private', user_key_field='user_key', query_options=search.QueryOptions(limit=limit, cursor=cursor, ids_only=ids_only), user_key=user_key) search_results =", "cards? search.TextField(name='front', value=card.front), search.TextField(name='back', value=card.back), search.TextField(name='info', value=card.info), search.DateField(name='added', value=card.added), search.DateField(name='modified',", "OR '.join(names))) if tags: parts.append('%s: (%s)' % (self.tag_field, ' OR", "(%s)' % (self.tag_field, ' OR '.join(tags))) # Don't return cards", "= user_key def _sanitize_user_input(self): query_str = self.query_str[:MAX_QUERY_LEN] return _sanitize_user_input(query_str) def", "search results item to avoid entity lookup? tag_fields = [search.AtomField(name='tag',", "value=card.user_nickname), # TODO(chris): support HtmlField for richer cards? search.TextField(name='front', value=card.front),", "\"\"\" if web_safe_cursor: cursor = search.Cursor(web_safe_string=web_safe_cursor) else: cursor = None", "the internal query language to users so # we strictly", "cursor = None index = search.Index(name=CARD_INDEX_NAME) query_processor = _QueryProcessor( query_str,", "'', token) if sane_token: if sane_token in ('AND', 'OK'): continue", "# ignore special search keywords elif token.startswith('@'): names.append(sane_token) elif token.startswith('#'):", "tokens. name_field is the field @name tokens should apply to.", "# shortname, e.g., @chris? search.AtomField(name='user_nickname', value=card.user_nickname), # TODO(chris): support HtmlField", "available on returned documents. CARD_DOCUMENT_VERSION = '1' # Ensure we're", "users have marked private... privacy = '%s: 0' % self.private_field", "https://developers.google.com/appengine/docs/python/search/query_strings MAX_QUERY_LEN = 200 # TODO(chris): it would be better", "tags: parts.append('%s: (%s)' % (self.tag_field, ' OR '.join(tags))) # Don't", "would enter it, and passes through a custom query processor", "CARD_INDEX_NAME = 'cards' # Increase this value when _card2doc changes", "\"\"\"High-level search API. This module implements application-specific search semantics on", "search_results def _card2doc(card): # TODO(chris): should we include all fields", "AND '.join(parts) def query(self): query = search.Query( query_string=self._build_query_string(), options=self.query_options) return", "clause). parts = [] if terms: parts.append(' OR '.join(terms)) if", "from google.appengine.ext import ndb QUERY_LIMIT = 20 CARD_INDEX_NAME = 'cards'", "query processor before the query is submitted to App Engine.", "web_safe_cursor=None, ids_only=False, user_key=None): \"\"\"Return the search.SearchResults for a query. ids_only", "back, info, tag (repeated), added, modified, source_url The query_string is", "tag_field self.private_field = private_field self.user_key_field = user_key_field self.query_options = query_options", "to avoid entity lookup? tag_fields = [search.AtomField(name='tag', value=tag) for tag", "the # user, then AND in the name or tag", "# ... but always show the user their own cards", "added, modified, source_url The query_string is free-form, as a user", "fields: user_key, user_nickname, front, back, info, tag (repeated), added, modified,", "an entity and generate a document. def insert_cards(cards): \"\"\"Insert or", "<gh_stars>0 \"\"\"High-level search API. This module implements application-specific search semantics", "useful because the returned document IDs are url-safe keys for", "= search.Index(name=CARD_INDEX_NAME) index.put(card_docs) def delete_cards(cards): \"\"\"Delete models.Card entities from the", "special meaning on certain inputs and we # don't want", "__init__(self, query_str, name_field, tag_field, private_field, user_key_field, query_options=None, user_key=None): self.query_str =", "Query for Card entities: query_cards(query_string, limit=20) -> search.SearchResults The results", "query_options self.user_key = user_key def _sanitize_user_input(self): query_str = self.query_str[:MAX_QUERY_LEN] return", "Ensure we're under the 2000 character limit from # https://developers.google.com/appengine/docs/python/search/query_strings", "for models.Card entities. \"\"\" if web_safe_cursor: cursor = search.Cursor(web_safe_string=web_safe_cursor) else:", "cards) index.delete(card_doc_ids) def query_cards(query_str, limit=QUERY_LIMIT, web_safe_cursor=None, ids_only=False, user_key=None): \"\"\"Return the", "of leaking implementation details # like we do now? return", "privacy + ')') return ' AND '.join(parts) def query(self): query", "search.Document( doc_id=_card2docid(card), fields=[ search.AtomField(name='doc_version', value=CARD_DOCUMENT_VERSION), search.AtomField(name='user_key', value=card.user_key.urlsafe()), # TODO(chris): is", "+ privacy + ')') return ' AND '.join(parts) def query(self):" ]
[ "for char in data: item = self.parse_cell_char(players, row, col, char)", "row, col, char) cell.append(item) return cell def parse(self, players, data):", "range(0, height)] def parse_cell_char(self, players, row, col, char): result =", "my_id): result.append(((o_row, o_col), order)) else: pass return result def update_cell(self,", "parse(self, players, data): cells = data.split(',') col = 0 row", "self.height def is_legal(self, row, col, my_id): enemy_id = my_id ^", "output(self): for row in self.cell: sys.stderr.write(\"\\n\") for cell in row:", "S_PLAYER1: players[0].row = row; players[0].col = col; elif char ==", "col, char): result = -1 if char == S_PLAYER1: players[0].row", "= self.parse_cell_char(players, row, col, char) cell.append(item) return cell def parse(self,", "o_col + col if self.is_legal(t_row, t_col): result.append((t_row, t_col)) return result", "0 for cell in cells: if (col >= self.width): col", "PLAYER2, EMPTY, BLOCKED = [0, 1, 2, 3] S_PLAYER1, S_PLAYER2,", "height)] def parse_cell_char(self, players, row, col, char): result = -1", "data): self.cell[row][col] = data def output_cell(self, cell): done = False", "col if self.is_legal(t_row, t_col): result.append((t_row, t_col)) return result def legal_moves(self,", "sys.stderr.write(\"!\") done = True def output(self): for row in self.cell:", "= col; elif char == S_PLAYER2: players[1].row = row; players[1].col", "((1, 0), \"down\"), ((0, 1), \"right\"), ((0, -1), \"left\") ]", "players[0].col = col; elif char == S_PLAYER2: players[1].row = row;", "enemy_id = my_id ^ 1 return (self.in_bounds(row, col)) and (not", "done = True def output(self): for row in self.cell: sys.stderr.write(\"\\n\")", "1 return (self.in_bounds(row, col)) and (not BLOCKED == self.cell[row][col]) and", "sys.stderr.write(\"\\n\") sys.stderr.flush() def tostring(self): res = \"\" for row in", "'.', 'x'] CHARTABLE = [(PLAYER1, S_PLAYER1), (PLAYER2, S_PLAYER2), (EMPTY, S_EMPTY),", "whole grid class Board: def __init__(self, width, height): self.width =", "'1', '.', 'x'] CHARTABLE = [(PLAYER1, S_PLAYER1), (PLAYER2, S_PLAYER2), (EMPTY,", "players, row, col, data): cell = [] for char in", "loc): row, col = loc return self.is_legal(row, col) def get_adjacent(self,", "True break if not done: sys.stderr.write(\"!\") done = True def", "= row; players[1].col = col; for (i, symbol) in CHARTABLE:", "width)] for row in range(0, height)] def parse_cell_char(self, players, row,", "self.cell[row][col] = data def output_cell(self, cell): done = False for", "return cell def parse(self, players, data): cells = data.split(',') col", "o_row t_col = my_player.col + o_col if self.is_legal(t_row, t_col, my_id):", "if char == S_PLAYER1: players[0].row = row; players[0].col = col;", "row >= 0 and col >= 0 and col <", "def update_cell(self, row, col, data): self.cell[row][col] = data def output_cell(self,", "def parse_cell_char(self, players, row, col, char): result = -1 if", ">= 0 and col >= 0 and col < self.width", "[ ((-1, 0), \"up\"), ((1, 0), \"down\"), ((0, 1), \"right\"),", "players[my_id] result = [] for ((o_row, o_col), order) in DIRS:", "row, col, cell) col += 1 def in_bounds (self, row,", "width self.height = height self.cell = [[EMPTY for col in", "(EMPTY, S_EMPTY), (BLOCKED, S_BLOCKED)] DIRS = [ ((-1, 0), \"up\"),", "^ 1 return (self.in_bounds(row, col)) and (not BLOCKED == self.cell[row][col])", "__init__(self, width, height): self.width = width self.height = height self.cell", ">= self.width): col = 0 row +=1 self.cell[row][col] = self.parse_cell(players,", "def get_adjacent(self, row, col): result = [] for (o_row, o_col),", "in xrange(self.width): res += str(self.cell[row][col]) res += \",\" return res", "symbol) in CHARTABLE: if symbol == char: result = i", "= 0 row +=1 self.cell[row][col] = self.parse_cell(players, row, col, cell)", "my_id ^ 1 return (self.in_bounds(row, col)) and (not BLOCKED ==", "and col < self.width and row < self.height def is_legal(self,", "result def update_cell(self, row, col, data): self.cell[row][col] = data def", "-1 if char == S_PLAYER1: players[0].row = row; players[0].col =", "my_player.col + o_col if self.is_legal(t_row, t_col, my_id): result.append(((o_row, o_col), order))", "col) def get_adjacent(self, row, col): result = [] for (o_row,", "row, col): result = [] for (o_row, o_col), _ in", "result = [] for ((o_row, o_col), order) in DIRS: t_row", "done = False for (i, symbol) in CHARTABLE: if i", "cells = data.split(',') col = 0 row = 0 for", "result.append((t_row, t_col)) return result def legal_moves(self, my_id, players): my_player =", "[0, 1, 2, 3] S_PLAYER1, S_PLAYER2, S_EMPTY, S_BLOCKED, = ['0',", "Board: def __init__(self, width, height): self.width = width self.height =", "(o_row, o_col), _ in DIRS: t_row, t_col = o_row +", "return row >= 0 and col >= 0 and col", "my_player.row + o_row t_col = my_player.col + o_col if self.is_legal(t_row,", "= my_player.col + o_col if self.is_legal(t_row, t_col, my_id): result.append(((o_row, o_col),", "col; elif char == S_PLAYER2: players[1].row = row; players[1].col =", "-1), \"left\") ] #the information of the whole grid class", "not done: sys.stderr.write(\"!\") done = True def output(self): for row", "row, o_col + col if self.is_legal(t_row, t_col): result.append((t_row, t_col)) return", "cell): done = False for (i, symbol) in CHARTABLE: if", "row < self.height def is_legal(self, row, col, my_id): enemy_id =", "S_PLAYER1, S_PLAYER2, S_EMPTY, S_BLOCKED, = ['0', '1', '.', 'x'] CHARTABLE", "sys.stderr.write(symbol) done = True break if not done: sys.stderr.write(\"!\") done", "= data def output_cell(self, cell): done = False for (i,", "= ['0', '1', '.', 'x'] CHARTABLE = [(PLAYER1, S_PLAYER1), (PLAYER2,", "in CHARTABLE: if i == cell: if not done: sys.stderr.write(symbol)", "char): result = -1 if char == S_PLAYER1: players[0].row =", "if i == cell: if not done: sys.stderr.write(symbol) done =", "def output(self): for row in self.cell: sys.stderr.write(\"\\n\") for cell in", "loc return self.is_legal(row, col) def get_adjacent(self, row, col): result =", "= width self.height = height self.cell = [[EMPTY for col", "return result def update_cell(self, row, col, data): self.cell[row][col] = data", "self.is_legal(t_row, t_col): result.append((t_row, t_col)) return result def legal_moves(self, my_id, players):", "+ row, o_col + col if self.is_legal(t_row, t_col): result.append((t_row, t_col))", ">= 0 and col < self.width and row < self.height", "players[1].col = col; for (i, symbol) in CHARTABLE: if symbol", "result = [] for (o_row, o_col), _ in DIRS: t_row,", "for cell in cells: if (col >= self.width): col =", "row, col, my_id): enemy_id = my_id ^ 1 return (self.in_bounds(row,", "copy import sys PLAYER1, PLAYER2, EMPTY, BLOCKED = [0, 1,", "t_row = my_player.row + o_row t_col = my_player.col + o_col", "_ in DIRS: t_row, t_col = o_row + row, o_col", "for (i, symbol) in CHARTABLE: if symbol == char: result", "my_id, players): my_player = players[my_id] result = [] for ((o_row,", "col; for (i, symbol) in CHARTABLE: if symbol == char:", "in_bounds (self, row, col): return row >= 0 and col", "self.parse_cell_char(players, row, col, char) cell.append(item) return cell def parse(self, players,", "= True def output(self): for row in self.cell: sys.stderr.write(\"\\n\") for", "data): cells = data.split(',') col = 0 row = 0", "for cell in row: self.output_cell(cell) sys.stderr.write(\"\\n\") sys.stderr.flush() def tostring(self): res", "col, my_id): enemy_id = my_id ^ 1 return (self.in_bounds(row, col))", "data: item = self.parse_cell_char(players, row, col, char) cell.append(item) return cell", "output_cell(self, cell): done = False for (i, symbol) in CHARTABLE:", "o_col), _ in DIRS: t_row, t_col = o_row + row,", "= 0 for cell in cells: if (col >= self.width):", "col)) and (not BLOCKED == self.cell[row][col]) and (not enemy_id ==", "enemy_id == self.cell[row][col]) def is_legal_tuple(self, loc): row, col = loc", "self.cell: sys.stderr.write(\"\\n\") for cell in row: self.output_cell(cell) sys.stderr.write(\"\\n\") sys.stderr.flush() def", "= 0 row = 0 for cell in cells: if", "return self.is_legal(row, col) def get_adjacent(self, row, col): result = []", "CHARTABLE: if i == cell: if not done: sys.stderr.write(symbol) done", "3] S_PLAYER1, S_PLAYER2, S_EMPTY, S_BLOCKED, = ['0', '1', '.', 'x']", "t_col): result.append((t_row, t_col)) return result def legal_moves(self, my_id, players): my_player", "for row in range(0, height)] def parse_cell_char(self, players, row, col,", "char == S_PLAYER1: players[0].row = row; players[0].col = col; elif", "+= 1 def in_bounds (self, row, col): return row >=", "= [] for char in data: item = self.parse_cell_char(players, row,", "(i, symbol) in CHARTABLE: if symbol == char: result =", "o_row + row, o_col + col if self.is_legal(t_row, t_col): result.append((t_row,", "elif char == S_PLAYER2: players[1].row = row; players[1].col = col;", "and (not enemy_id == self.cell[row][col]) def is_legal_tuple(self, loc): row, col", "symbol) in CHARTABLE: if i == cell: if not done:", "self.is_legal(row, col) def get_adjacent(self, row, col): result = [] for", "cells: if (col >= self.width): col = 0 row +=1", "class Board: def __init__(self, width, height): self.width = width self.height", "row: self.output_cell(cell) sys.stderr.write(\"\\n\") sys.stderr.flush() def tostring(self): res = \"\" for", "col, cell) col += 1 def in_bounds (self, row, col):", "def in_bounds (self, row, col): return row >= 0 and", "symbol == char: result = i break return result def", "((0, -1), \"left\") ] #the information of the whole grid", "row in xrange(self.height): for col in xrange(self.width): res += str(self.cell[row][col])", "= [[EMPTY for col in range (0, width)] for row", "row, col, data): cell = [] for char in data:", "for row in xrange(self.height): for col in xrange(self.width): res +=", "in range(0, height)] def parse_cell_char(self, players, row, col, char): result", "def parse_cell(self, players, row, col, data): cell = [] for", "players): my_player = players[my_id] result = [] for ((o_row, o_col),", "break return result def parse_cell(self, players, row, col, data): cell", "players, row, col, char): result = -1 if char ==", "0 row = 0 for cell in cells: if (col", "def legal_moves(self, my_id, players): my_player = players[my_id] result = []", "(i, symbol) in CHARTABLE: if i == cell: if not", "0 and col < self.width and row < self.height def", "char in data: item = self.parse_cell_char(players, row, col, char) cell.append(item)", "sys.stderr.flush() def tostring(self): res = \"\" for row in xrange(self.height):", "S_EMPTY), (BLOCKED, S_BLOCKED)] DIRS = [ ((-1, 0), \"up\"), ((1,", "result def parse_cell(self, players, row, col, data): cell = []", "= [0, 1, 2, 3] S_PLAYER1, S_PLAYER2, S_EMPTY, S_BLOCKED, =", "char) cell.append(item) return cell def parse(self, players, data): cells =", "result def legal_moves(self, my_id, players): my_player = players[my_id] result =", "EMPTY, BLOCKED = [0, 1, 2, 3] S_PLAYER1, S_PLAYER2, S_EMPTY,", "1, 2, 3] S_PLAYER1, S_PLAYER2, S_EMPTY, S_BLOCKED, = ['0', '1',", "update_cell(self, row, col, data): self.cell[row][col] = data def output_cell(self, cell):", "S_PLAYER2), (EMPTY, S_EMPTY), (BLOCKED, S_BLOCKED)] DIRS = [ ((-1, 0),", "i == cell: if not done: sys.stderr.write(symbol) done = True", "(BLOCKED, S_BLOCKED)] DIRS = [ ((-1, 0), \"up\"), ((1, 0),", "xrange(self.height): for col in xrange(self.width): res += str(self.cell[row][col]) res +=", "+ o_col if self.is_legal(t_row, t_col, my_id): result.append(((o_row, o_col), order)) else:", "\"right\"), ((0, -1), \"left\") ] #the information of the whole", "data): cell = [] for char in data: item =", "for (i, symbol) in CHARTABLE: if i == cell: if", "cell = [] for char in data: item = self.parse_cell_char(players,", "self.cell[row][col]) def is_legal_tuple(self, loc): row, col = loc return self.is_legal(row,", "my_player = players[my_id] result = [] for ((o_row, o_col), order)", "t_col, my_id): result.append(((o_row, o_col), order)) else: pass return result def", "'x'] CHARTABLE = [(PLAYER1, S_PLAYER1), (PLAYER2, S_PLAYER2), (EMPTY, S_EMPTY), (BLOCKED,", "width, height): self.width = width self.height = height self.cell =", "row, col): return row >= 0 and col >= 0", "] #the information of the whole grid class Board: def", "players, data): cells = data.split(',') col = 0 row =", "= False for (i, symbol) in CHARTABLE: if i ==", "if not done: sys.stderr.write(symbol) done = True break if not", "row = 0 for cell in cells: if (col >=", "def tostring(self): res = \"\" for row in xrange(self.height): for", "in CHARTABLE: if symbol == char: result = i break", "players[1].row = row; players[1].col = col; for (i, symbol) in", "(0, width)] for row in range(0, height)] def parse_cell_char(self, players,", "self.is_legal(t_row, t_col, my_id): result.append(((o_row, o_col), order)) else: pass return result", "(self, row, col): return row >= 0 and col >=", "= o_row + row, o_col + col if self.is_legal(t_row, t_col):", "cell) col += 1 def in_bounds (self, row, col): return", "data def output_cell(self, cell): done = False for (i, symbol)", "legal_moves(self, my_id, players): my_player = players[my_id] result = [] for", "for (o_row, o_col), _ in DIRS: t_row, t_col = o_row", "if (col >= self.width): col = 0 row +=1 self.cell[row][col]", "in xrange(self.height): for col in xrange(self.width): res += str(self.cell[row][col]) res", "(self.in_bounds(row, col)) and (not BLOCKED == self.cell[row][col]) and (not enemy_id", "DIRS = [ ((-1, 0), \"up\"), ((1, 0), \"down\"), ((0,", "(not enemy_id == self.cell[row][col]) def is_legal_tuple(self, loc): row, col =", "= row; players[0].col = col; elif char == S_PLAYER2: players[1].row", "def __init__(self, width, height): self.width = width self.height = height", "#the information of the whole grid class Board: def __init__(self,", "0), \"down\"), ((0, 1), \"right\"), ((0, -1), \"left\") ] #the", "PLAYER1, PLAYER2, EMPTY, BLOCKED = [0, 1, 2, 3] S_PLAYER1,", "\"left\") ] #the information of the whole grid class Board:", "row +=1 self.cell[row][col] = self.parse_cell(players, row, col, cell) col +=", "tostring(self): res = \"\" for row in xrange(self.height): for col", "S_PLAYER2, S_EMPTY, S_BLOCKED, = ['0', '1', '.', 'x'] CHARTABLE =", "= my_player.row + o_row t_col = my_player.col + o_col if", "def parse(self, players, data): cells = data.split(',') col = 0", "players[0].row = row; players[0].col = col; elif char == S_PLAYER2:", "done = True break if not done: sys.stderr.write(\"!\") done =", "self.width = width self.height = height self.cell = [[EMPTY for", "0 row +=1 self.cell[row][col] = self.parse_cell(players, row, col, cell) col", "S_EMPTY, S_BLOCKED, = ['0', '1', '.', 'x'] CHARTABLE = [(PLAYER1,", "S_BLOCKED, = ['0', '1', '.', 'x'] CHARTABLE = [(PLAYER1, S_PLAYER1),", "1 def in_bounds (self, row, col): return row >= 0", "cell in cells: if (col >= self.width): col = 0", "def is_legal(self, row, col, my_id): enemy_id = my_id ^ 1", "True def output(self): for row in self.cell: sys.stderr.write(\"\\n\") for cell", "col >= 0 and col < self.width and row <", "o_col), order) in DIRS: t_row = my_player.row + o_row t_col", "0), \"up\"), ((1, 0), \"down\"), ((0, 1), \"right\"), ((0, -1),", "DIRS: t_row, t_col = o_row + row, o_col + col", "height self.cell = [[EMPTY for col in range (0, width)]", "S_PLAYER2: players[1].row = row; players[1].col = col; for (i, symbol)", "t_row, t_col = o_row + row, o_col + col if", "[[EMPTY for col in range (0, width)] for row in", "for col in xrange(self.width): res += str(self.cell[row][col]) res += \",\"", "+ o_row t_col = my_player.col + o_col if self.is_legal(t_row, t_col,", "if self.is_legal(t_row, t_col): result.append((t_row, t_col)) return result def legal_moves(self, my_id,", "S_PLAYER1), (PLAYER2, S_PLAYER2), (EMPTY, S_EMPTY), (BLOCKED, S_BLOCKED)] DIRS = [", "cell: if not done: sys.stderr.write(symbol) done = True break if", "for row in self.cell: sys.stderr.write(\"\\n\") for cell in row: self.output_cell(cell)", "\"down\"), ((0, 1), \"right\"), ((0, -1), \"left\") ] #the information", "parse_cell(self, players, row, col, data): cell = [] for char", "((o_row, o_col), order) in DIRS: t_row = my_player.row + o_row", "row; players[0].col = col; elif char == S_PLAYER2: players[1].row =", "range (0, width)] for row in range(0, height)] def parse_cell_char(self,", "cell.append(item) return cell def parse(self, players, data): cells = data.split(',')", "if self.is_legal(t_row, t_col, my_id): result.append(((o_row, o_col), order)) else: pass return", "sys PLAYER1, PLAYER2, EMPTY, BLOCKED = [0, 1, 2, 3]", "CHARTABLE = [(PLAYER1, S_PLAYER1), (PLAYER2, S_PLAYER2), (EMPTY, S_EMPTY), (BLOCKED, S_BLOCKED)]", "in self.cell: sys.stderr.write(\"\\n\") for cell in row: self.output_cell(cell) sys.stderr.write(\"\\n\") sys.stderr.flush()", "= -1 if char == S_PLAYER1: players[0].row = row; players[0].col", "S_BLOCKED)] DIRS = [ ((-1, 0), \"up\"), ((1, 0), \"down\"),", "and row < self.height def is_legal(self, row, col, my_id): enemy_id", "col in range (0, width)] for row in range(0, height)]", "[(PLAYER1, S_PLAYER1), (PLAYER2, S_PLAYER2), (EMPTY, S_EMPTY), (BLOCKED, S_BLOCKED)] DIRS =", "char: result = i break return result def parse_cell(self, players,", "= players[my_id] result = [] for ((o_row, o_col), order) in", "['0', '1', '.', 'x'] CHARTABLE = [(PLAYER1, S_PLAYER1), (PLAYER2, S_PLAYER2),", "for ((o_row, o_col), order) in DIRS: t_row = my_player.row +", "in data: item = self.parse_cell_char(players, row, col, char) cell.append(item) return", "order) in DIRS: t_row = my_player.row + o_row t_col =", "is_legal_tuple(self, loc): row, col = loc return self.is_legal(row, col) def", "t_col)) return result def legal_moves(self, my_id, players): my_player = players[my_id]", "(not BLOCKED == self.cell[row][col]) and (not enemy_id == self.cell[row][col]) def", "BLOCKED == self.cell[row][col]) and (not enemy_id == self.cell[row][col]) def is_legal_tuple(self,", "cell in row: self.output_cell(cell) sys.stderr.write(\"\\n\") sys.stderr.flush() def tostring(self): res =", "return (self.in_bounds(row, col)) and (not BLOCKED == self.cell[row][col]) and (not", "self.parse_cell(players, row, col, cell) col += 1 def in_bounds (self,", "result = -1 if char == S_PLAYER1: players[0].row = row;", "col, data): self.cell[row][col] = data def output_cell(self, cell): done =", "break if not done: sys.stderr.write(\"!\") done = True def output(self):", "in DIRS: t_row = my_player.row + o_row t_col = my_player.col", "== self.cell[row][col]) and (not enemy_id == self.cell[row][col]) def is_legal_tuple(self, loc):", "return result def parse_cell(self, players, row, col, data): cell =", "if symbol == char: result = i break return result", "col): return row >= 0 and col >= 0 and", "and col >= 0 and col < self.width and row", "= [ ((-1, 0), \"up\"), ((1, 0), \"down\"), ((0, 1),", "result.append(((o_row, o_col), order)) else: pass return result def update_cell(self, row,", "= True break if not done: sys.stderr.write(\"!\") done = True", "BLOCKED = [0, 1, 2, 3] S_PLAYER1, S_PLAYER2, S_EMPTY, S_BLOCKED,", "order)) else: pass return result def update_cell(self, row, col, data):", "pass return result def update_cell(self, row, col, data): self.cell[row][col] =", "get_adjacent(self, row, col): result = [] for (o_row, o_col), _", "= [] for (o_row, o_col), _ in DIRS: t_row, t_col", "row, col, char): result = -1 if char == S_PLAYER1:", "char == S_PLAYER2: players[1].row = row; players[1].col = col; for", "result = i break return result def parse_cell(self, players, row,", "self.width): col = 0 row +=1 self.cell[row][col] = self.parse_cell(players, row,", "t_col = o_row + row, o_col + col if self.is_legal(t_row,", "is_legal(self, row, col, my_id): enemy_id = my_id ^ 1 return", "col): result = [] for (o_row, o_col), _ in DIRS:", "self.cell = [[EMPTY for col in range (0, width)] for", "def output_cell(self, cell): done = False for (i, symbol) in", "my_id): enemy_id = my_id ^ 1 return (self.in_bounds(row, col)) and", "of the whole grid class Board: def __init__(self, width, height):", "== char: result = i break return result def parse_cell(self,", "if not done: sys.stderr.write(\"!\") done = True def output(self): for", "row; players[1].col = col; for (i, symbol) in CHARTABLE: if", "def is_legal_tuple(self, loc): row, col = loc return self.is_legal(row, col)", "done: sys.stderr.write(\"!\") done = True def output(self): for row in", "return result def legal_moves(self, my_id, players): my_player = players[my_id] result", "parse_cell_char(self, players, row, col, char): result = -1 if char", "o_col), order)) else: pass return result def update_cell(self, row, col,", "\"\" for row in xrange(self.height): for col in xrange(self.width): res", "grid class Board: def __init__(self, width, height): self.width = width", "2, 3] S_PLAYER1, S_PLAYER2, S_EMPTY, S_BLOCKED, = ['0', '1', '.',", "[] for char in data: item = self.parse_cell_char(players, row, col,", "self.width and row < self.height def is_legal(self, row, col, my_id):", "\"up\"), ((1, 0), \"down\"), ((0, 1), \"right\"), ((0, -1), \"left\")", "i break return result def parse_cell(self, players, row, col, data):", "CHARTABLE: if symbol == char: result = i break return", "(PLAYER2, S_PLAYER2), (EMPTY, S_EMPTY), (BLOCKED, S_BLOCKED)] DIRS = [ ((-1,", "data.split(',') col = 0 row = 0 for cell in", "information of the whole grid class Board: def __init__(self, width,", "self.output_cell(cell) sys.stderr.write(\"\\n\") sys.stderr.flush() def tostring(self): res = \"\" for row", "else: pass return result def update_cell(self, row, col, data): self.cell[row][col]", "= col; for (i, symbol) in CHARTABLE: if symbol ==", "col < self.width and row < self.height def is_legal(self, row,", "o_col if self.is_legal(t_row, t_col, my_id): result.append(((o_row, o_col), order)) else: pass", "sys.stderr.write(\"\\n\") for cell in row: self.output_cell(cell) sys.stderr.write(\"\\n\") sys.stderr.flush() def tostring(self):", "((0, 1), \"right\"), ((0, -1), \"left\") ] #the information of", "+=1 self.cell[row][col] = self.parse_cell(players, row, col, cell) col += 1", "0 and col >= 0 and col < self.width and", "row, col = loc return self.is_legal(row, col) def get_adjacent(self, row,", "the whole grid class Board: def __init__(self, width, height): self.width", "< self.width and row < self.height def is_legal(self, row, col,", "== cell: if not done: sys.stderr.write(symbol) done = True break", "self.cell[row][col] = self.parse_cell(players, row, col, cell) col += 1 def", "[] for (o_row, o_col), _ in DIRS: t_row, t_col =", "DIRS: t_row = my_player.row + o_row t_col = my_player.col +", "== S_PLAYER2: players[1].row = row; players[1].col = col; for (i,", "in DIRS: t_row, t_col = o_row + row, o_col +", "col = 0 row = 0 for cell in cells:", "in row: self.output_cell(cell) sys.stderr.write(\"\\n\") sys.stderr.flush() def tostring(self): res = \"\"", "import sys PLAYER1, PLAYER2, EMPTY, BLOCKED = [0, 1, 2,", "import copy import sys PLAYER1, PLAYER2, EMPTY, BLOCKED = [0,", "+ col if self.is_legal(t_row, t_col): result.append((t_row, t_col)) return result def", "t_col = my_player.col + o_col if self.is_legal(t_row, t_col, my_id): result.append(((o_row,", "== S_PLAYER1: players[0].row = row; players[0].col = col; elif char", "cell def parse(self, players, data): cells = data.split(',') col =", "(col >= self.width): col = 0 row +=1 self.cell[row][col] =", "col, char) cell.append(item) return cell def parse(self, players, data): cells", "== self.cell[row][col]) def is_legal_tuple(self, loc): row, col = loc return", "< self.height def is_legal(self, row, col, my_id): enemy_id = my_id", "= self.parse_cell(players, row, col, cell) col += 1 def in_bounds", "= loc return self.is_legal(row, col) def get_adjacent(self, row, col): result", "and (not BLOCKED == self.cell[row][col]) and (not enemy_id == self.cell[row][col])", "self.height = height self.cell = [[EMPTY for col in range", "col, data): cell = [] for char in data: item", "row, col, data): self.cell[row][col] = data def output_cell(self, cell): done", "False for (i, symbol) in CHARTABLE: if i == cell:", "= [(PLAYER1, S_PLAYER1), (PLAYER2, S_PLAYER2), (EMPTY, S_EMPTY), (BLOCKED, S_BLOCKED)] DIRS", "= [] for ((o_row, o_col), order) in DIRS: t_row =", "in range (0, width)] for row in range(0, height)] def", "col = loc return self.is_legal(row, col) def get_adjacent(self, row, col):", "done: sys.stderr.write(symbol) done = True break if not done: sys.stderr.write(\"!\")", "row in self.cell: sys.stderr.write(\"\\n\") for cell in row: self.output_cell(cell) sys.stderr.write(\"\\n\")", "for col in range (0, width)] for row in range(0,", "= height self.cell = [[EMPTY for col in range (0,", "= my_id ^ 1 return (self.in_bounds(row, col)) and (not BLOCKED", "in cells: if (col >= self.width): col = 0 row", "[] for ((o_row, o_col), order) in DIRS: t_row = my_player.row", "1), \"right\"), ((0, -1), \"left\") ] #the information of the", "col += 1 def in_bounds (self, row, col): return row", "row in range(0, height)] def parse_cell_char(self, players, row, col, char):", "not done: sys.stderr.write(symbol) done = True break if not done:", "item = self.parse_cell_char(players, row, col, char) cell.append(item) return cell def", "= data.split(',') col = 0 row = 0 for cell", "= \"\" for row in xrange(self.height): for col in xrange(self.width):", "height): self.width = width self.height = height self.cell = [[EMPTY", "col = 0 row +=1 self.cell[row][col] = self.parse_cell(players, row, col,", "= i break return result def parse_cell(self, players, row, col,", "self.cell[row][col]) and (not enemy_id == self.cell[row][col]) def is_legal_tuple(self, loc): row,", "((-1, 0), \"up\"), ((1, 0), \"down\"), ((0, 1), \"right\"), ((0,", "res = \"\" for row in xrange(self.height): for col in", "col in xrange(self.width): res += str(self.cell[row][col]) res += \",\" return" ]
[ "in range(N)] cnt = 0 for r in range(N): for", "nc < M and visit[nr][nc] == False and board[nr][nc] ==", "nc = r + dr, c + dc if 0", "board[r][c] = 1 visit = [[False] * M for _", "c): global visit visit[r][c] = True mov = [(-1, 0),", "range(T): M, N, K = map(int, input().split()) board = [[0]", "r + dr, c + dc if 0 <= nr", "<= nc < M and visit[nr][nc] == False and board[nr][nc]", "_ in range(T): M, N, K = map(int, input().split()) board", "visit[r][c] = True mov = [(-1, 0), (0, -1), (1,", "cnt = 0 for r in range(N): for c in", "not visit[r][c] and board[r][c] == 1: cnt += 1 dfs(r,", "for r in range(N): for c in range(M): if not", "global visit visit[r][c] = True mov = [(-1, 0), (0,", "(0, -1), (1, 0), (0, 1)] for i in range(4):", "nr < N and 0 <= nc < M and", "map(int, input().split()) board = [[0] * M for _ in", "for i in range(4): dr, dc = mov[i] nr, nc", "0 <= nc < M and visit[nr][nc] == False and", "0), (0, -1), (1, 0), (0, 1)] for i in", "== 1: dfs(nr, nc) T = int(input()) for _ in", "and board[r][c] == 1: cnt += 1 dfs(r, c) for", "in range(M): if not visit[r][c] and board[r][c] == 1: cnt", "<= nr < N and 0 <= nc < M", "sys.setrecursionlimit(10000) def dfs(r, c): global visit visit[r][c] = True mov", "= 1 visit = [[False] * M for _ in", "True mov = [(-1, 0), (0, -1), (1, 0), (0,", "board[nr][nc] == 1: dfs(nr, nc) T = int(input()) for _", "= map(int, input().split()) board = [[0] * M for _", "[[0] * M for _ in range(N)] for _ in", "for _ in range(N)] cnt = 0 for r in", "sys sys.setrecursionlimit(10000) def dfs(r, c): global visit visit[r][c] = True", "== False and board[nr][nc] == 1: dfs(nr, nc) T =", "_ in range(N)] for _ in range(K): c, r =", "c in range(M): if not visit[r][c] and board[r][c] == 1:", "== 1: cnt += 1 dfs(r, c) for ele in", "range(N)] for _ in range(K): c, r = map(int, input().split())", "(1, 0), (0, 1)] for i in range(4): dr, dc", "and 0 <= nc < M and visit[nr][nc] == False", "[[False] * M for _ in range(N)] cnt = 0", "int(input()) for _ in range(T): M, N, K = map(int,", "= [[False] * M for _ in range(N)] cnt =", "range(K): c, r = map(int, input().split()) board[r][c] = 1 visit", "cnt += 1 dfs(r, c) for ele in visit: print(ele)", "range(M): if not visit[r][c] and board[r][c] == 1: cnt +=", "False and board[nr][nc] == 1: dfs(nr, nc) T = int(input())", "visit[nr][nc] == False and board[nr][nc] == 1: dfs(nr, nc) T", "board[r][c] == 1: cnt += 1 dfs(r, c) for ele", "dr, c + dc if 0 <= nr < N", "map(int, input().split()) board[r][c] = 1 visit = [[False] * M", "< M and visit[nr][nc] == False and board[nr][nc] == 1:", "* M for _ in range(N)] cnt = 0 for", "0 for r in range(N): for c in range(M): if", "dfs(r, c): global visit visit[r][c] = True mov = [(-1,", "board = [[0] * M for _ in range(N)] for", "1: cnt += 1 dfs(r, c) for ele in visit:", "+ dc if 0 <= nr < N and 0", "(0, 1)] for i in range(4): dr, dc = mov[i]", "_ in range(K): c, r = map(int, input().split()) board[r][c] =", "N, K = map(int, input().split()) board = [[0] * M", "for _ in range(T): M, N, K = map(int, input().split())", "* M for _ in range(N)] for _ in range(K):", "-1), (1, 0), (0, 1)] for i in range(4): dr,", "1 visit = [[False] * M for _ in range(N)]", "nr, nc = r + dr, c + dc if", "1: dfs(nr, nc) T = int(input()) for _ in range(T):", "+= 1 dfs(r, c) for ele in visit: print(ele) print()", "mov[i] nr, nc = r + dr, c + dc", "= map(int, input().split()) board[r][c] = 1 visit = [[False] *", "M for _ in range(N)] for _ in range(K): c,", "if not visit[r][c] and board[r][c] == 1: cnt += 1", "1)] for i in range(4): dr, dc = mov[i] nr,", "dr, dc = mov[i] nr, nc = r + dr,", "range(N)] cnt = 0 for r in range(N): for c", "K = map(int, input().split()) board = [[0] * M for", "0), (0, 1)] for i in range(4): dr, dc =", "range(4): dr, dc = mov[i] nr, nc = r +", "< N and 0 <= nc < M and visit[nr][nc]", "mov = [(-1, 0), (0, -1), (1, 0), (0, 1)]", "dc = mov[i] nr, nc = r + dr, c", "+ dr, c + dc if 0 <= nr <", "= [[0] * M for _ in range(N)] for _", "for c in range(M): if not visit[r][c] and board[r][c] ==", "if 0 <= nr < N and 0 <= nc", "for _ in range(N)] for _ in range(K): c, r", "import sys sys.setrecursionlimit(10000) def dfs(r, c): global visit visit[r][c] =", "= True mov = [(-1, 0), (0, -1), (1, 0),", "and board[nr][nc] == 1: dfs(nr, nc) T = int(input()) for", "visit visit[r][c] = True mov = [(-1, 0), (0, -1),", "_ in range(N)] cnt = 0 for r in range(N):", "input().split()) board = [[0] * M for _ in range(N)]", "= int(input()) for _ in range(T): M, N, K =", "T = int(input()) for _ in range(T): M, N, K", "for _ in range(K): c, r = map(int, input().split()) board[r][c]", "dc if 0 <= nr < N and 0 <=", "in range(T): M, N, K = map(int, input().split()) board =", "def dfs(r, c): global visit visit[r][c] = True mov =", "visit[r][c] and board[r][c] == 1: cnt += 1 dfs(r, c)", "= mov[i] nr, nc = r + dr, c +", "M, N, K = map(int, input().split()) board = [[0] *", "M for _ in range(N)] cnt = 0 for r", "M and visit[nr][nc] == False and board[nr][nc] == 1: dfs(nr,", "in range(N)] for _ in range(K): c, r = map(int,", "= r + dr, c + dc if 0 <=", "= 0 for r in range(N): for c in range(M):", "N and 0 <= nc < M and visit[nr][nc] ==", "c + dc if 0 <= nr < N and", "nc) T = int(input()) for _ in range(T): M, N,", "visit = [[False] * M for _ in range(N)] cnt", "range(N): for c in range(M): if not visit[r][c] and board[r][c]", "0 <= nr < N and 0 <= nc <", "input().split()) board[r][c] = 1 visit = [[False] * M for", "and visit[nr][nc] == False and board[nr][nc] == 1: dfs(nr, nc)", "r = map(int, input().split()) board[r][c] = 1 visit = [[False]", "in range(K): c, r = map(int, input().split()) board[r][c] = 1", "c, r = map(int, input().split()) board[r][c] = 1 visit =", "in range(4): dr, dc = mov[i] nr, nc = r", "in range(N): for c in range(M): if not visit[r][c] and", "r in range(N): for c in range(M): if not visit[r][c]", "[(-1, 0), (0, -1), (1, 0), (0, 1)] for i", "1 dfs(r, c) for ele in visit: print(ele) print() print(cnt)", "dfs(nr, nc) T = int(input()) for _ in range(T): M,", "= [(-1, 0), (0, -1), (1, 0), (0, 1)] for", "i in range(4): dr, dc = mov[i] nr, nc =" ]
[ "inorder traversal. If write is True then print as well.", "nodes as node_stack 2. Mark root as current 3. While", "in traversal_lis: print(item, end=' ') return traversal_lis def levelorder_traversal(self, write=True):", "node data as level order traversal. If write is true", "5, 1, 3] assert tree.preorder_traversal(write=False) == [1, 2, 4, 5,", "node_stack: while current: node_stack.append(current) traversal_lis.append(current.data) current = current.right if node_stack:", "3. While current is not None or node_stack is not", "node.right if write: for item in traversal_lis: print(item, end=' ')", "top node and assign poped_node->left to current \"\"\" traversal_lis =", "as current 3. While current is not none or node_stack", "tree = BinaryTree(1) tree.left = BinaryTree(2) tree.right = BinaryTree(3) tree.left.left", "If current is empty and node_stack is not empty then", "[1, 2, 4, 5, 3] assert tree.postorder_traversal(write=False) == [1, 3,", "b. If current is empty and node_stack is not empty", "node_stack is not empty a. While current is not None", "of nodes to process as node_queue 2. Push root to", "2. Mark root as current 3. While current is not", "ii. Add current->data to traversal_list iii. Reassign current to current->left", "top node of node_queue as top b. Push top->data to", "from collections import deque class BinaryTree(object): \"\"\" Representation of a", "1. Create a stack of nodes node_stack 2. Mark root", "and print that node c. mark current as poped_node->right \"\"\"", "stack and print that node c. mark current as poped_node->right", "Algorithm: 1. Maintain a queue of nodes to process as", "is not empty then pop the topmost node from node_stack", "item in traversal_lis: print(item, end=' ') return traversal_lis def preorder_traversal(self,", "list of node data as preorder traversal. If write is", "the top of stack and print that node c. mark", "node_stack ii. Append current->data to traversal_list iii. Reassign current as", "tree.left = BinaryTree(2) tree.right = BinaryTree(3) tree.left.left = BinaryTree(4) tree.left.right", "= node_stack.pop() current = node.right if write: for item in", "from node_stack and assign current to poped_node->right \"\"\" traversal_lis =", "Reassign current to current->left b. If node_stack is not empty", "2, 5, 4] assert tree.levelorder_traversal(write=False) == [1, 2, 3, 4,", "traversal_lis: print(item, end=' ') return traversal_lis def levelorder_traversal(self, write=True): \"\"\"", "or node_stack is not empty a. While current is not", "def __init__(self, data, left=None, right=None): if data is None: raise", "is true then print as well. Algorithm: 1. Create stack", "empty then pop top node and assign poped_node->left to current", "2, 5, 1, 3] assert tree.preorder_traversal(write=False) == [1, 2, 4,", "doing postorder traversal b. If node_stack is not empty then", "node_stack: node = node_stack.pop() current = node.left if write: for", "left self.right = right def insert(self, data): raise NotImplementedError('Method insert", "1. In-Order Traversal 2. Pre-Order Traversal 3. Post-Order Traversal 4.", "postorder traversal b. If node_stack is not empty then pop", "not None or node_stack is not empty a. While current", "c. Append top->left and top->right into node_queue if they are", "is True then print as well. This is a iterative", "5, 4] assert tree.levelorder_traversal(write=False) == [1, 2, 3, 4, 5]", "a queue of nodes to process as node_queue 2. Push", "in traversal_lis: print(item, end=' ') return traversal_lis def preorder_traversal(self, write=True):", "class BinaryTree(object): \"\"\" Representation of a general binary tree data:", "Create stack of nodes as node_stack 2. Mark root as", "node_stack is not empty then pop top node and assign", "is true then print as well. Algorithm: 1. Maintain a", "not None i. Push current to node_stack ii. Append current->data", "right: Right subtree \"\"\" def __init__(self, data, left=None, right=None): if", "root to node_queue 3. While node_queue is not empty a.", "while current or node_stack: while current: node_stack.append(current) current = current.left", "of node_queue as top b. Push top->data to traversal_list c.", "we're iterating on current-right as we're doing postorder traversal b.", "item in traversal_lis: print(item, end=' ') return traversal_lis def postorder_traversal(self,", "top of stack and print that node c. mark current", "node_stack is not empty a. While current is not empty", "Traversal \"\"\" from collections import deque class BinaryTree(object): \"\"\" Representation", "') return traversal_lis def postorder_traversal(self, write=True): \"\"\" Return list of", "Tree Structure: 1 / \\ 2 3 / \\ 4", "tree.postorder_traversal(write=False) == [1, 3, 2, 5, 4] assert tree.levelorder_traversal(write=False) ==", "Here we're iterating on current-right as we're doing postorder traversal", "poped_node->left to current \"\"\" traversal_lis = [] node_stack = []", "print as well. Algorithm: 1. Create stack of nodes as", "print as well. This is a iterative tree inorder traversal.", "= BinaryTree(1) tree.left = BinaryTree(2) tree.right = BinaryTree(3) tree.left.left =", "If node_stack is not empty then pop top node and", "insert is not Implemented') def delete(self, data): raise NotImplementedError('Method delete", "def delete(self, data): raise NotImplementedError('Method delete is not implemented') def", "\"\"\" tree = BinaryTree(1) tree.left = BinaryTree(2) tree.right = BinaryTree(3)", "data: value of element left: Left subtree right: Right subtree", "if they are not null \"\"\" traversal_list = [] node_queue", "While current is not empty push current to nde_stack and", "3. Post-Order Traversal 4. Level-Order Traversal \"\"\" from collections import", "If write is True then print as well. This is", "3. While current is not none or node_stack is not", "to node_stack ii. Add current->data to traversal_list iii. Reassign current", "be null') self.data = data self.left = left self.right =", "to node_stack ii. Append current->data to traversal_list iii. Reassign current", "not empty then pop top node and assign poped_node->left to", "is not empty then pop the top of stack and", "as top b. Push top->data to traversal_list c. Append top->left", "tree.left.right = BinaryTree(5) assert tree.inorder_traversal(write=False) == [4, 2, 5, 1,", "delete(self, data): raise NotImplementedError('Method delete is not implemented') def inorder_traversal(self,", "BinaryTree(object): \"\"\" Representation of a general binary tree data: value", "on current-right as we're doing postorder traversal b. If node_stack", "Push current to node_stack ii. Add current->data to traversal_list iii.", "to traversal_list iii. Reassign current as current->right !IMPORTANT: Here we're", "write is True then print as well. This is a", "[1, 2, 3, 4, 5] if __name__ == '__main__': main()", "\"\"\" Return list of node data as postorder traversal. If", "current = current.left if node_stack: node = node_stack.pop() traversal_lis.append(node.data) current", "subtree \"\"\" def __init__(self, data, left=None, right=None): if data is", "true then print as well. Algorithm: 1. Maintain a queue", "1 / \\ 2 3 / \\ 4 5 \"\"\"", "Return list of node data as postorder traversal. If write", "traversal_lis.append(current.data) current = current.left if node_stack: node = node_stack.pop() current", "Binary Tree and basic properties 1. In-Order Traversal 2. Pre-Order", "return traversal_lis def levelorder_traversal(self, write=True): \"\"\" Return list of node", "[] node_queue = deque() node_queue.append(self) while node_queue: top = node_queue.popleft()", "are not null \"\"\" traversal_list = [] node_queue = deque()", "to traversal_list iii. Reassign current to current->left b. If node_stack", "root as current 3. While current is not none or", "then print as well. This is a iterative tree inorder", "Reassign current as current->right !IMPORTANT: Here we're iterating on current-right", "is not none or node_stack is not empty a. While", "2, 4, 5, 3] assert tree.postorder_traversal(write=False) == [1, 3, 2,", "empty then pop the top of stack and print that", "\"\"\" Binary Tree and basic properties 1. In-Order Traversal 2.", "then print as well. Algorithm: 1. Maintain a queue of", "end=' ') return traversal_lis def levelorder_traversal(self, write=True): \"\"\" Return list", "current as current->right !IMPORTANT: Here we're iterating on current-right as", "if node_stack: node = node_stack.pop() current = node.left if write:", "= [] current = self while current or node_stack: while", "if node_stack: node = node_stack.pop() traversal_lis.append(node.data) current = node.right if", "and assign current to poped_node->right \"\"\" traversal_lis = [] node_stack", "level order traversal. If write is true then print as", "data as level order traversal. If write is true then", "Traversal 4. Level-Order Traversal \"\"\" from collections import deque class", "node and assign poped_node->left to current \"\"\" traversal_lis = []", "if data is None: raise ValueError('data cannot be null') self.data", "well. Algorithm: 1. Maintain a queue of nodes to process", "preorder traversal. If write is true then print as well.", "as current->right !IMPORTANT: Here we're iterating on current-right as we're", "current.left if node_stack: node = node_stack.pop() current = node.right if", "current is not empty i. Push current to node_stack ii.", "pop top node and assign poped_node->left to current \"\"\" traversal_lis", "Mark root as current 3. While current is not none", "and assign poped_node->left to current \"\"\" traversal_lis = [] node_stack", "\"\"\" Tree Structure: 1 / \\ 2 3 / \\", "not none or node_stack is not empty a. While current", "is not empty then pop top node and assign poped_node->left", "not implemented') def inorder_traversal(self, write=True): \"\"\" Return list of node", "as well. Algorithm: 1. Maintain a queue of nodes to", "iterative tree inorder traversal. Algorithm: 1. Create a stack of", "Level-Order Traversal \"\"\" from collections import deque class BinaryTree(object): \"\"\"", "= self while current or node_stack: while current: node_stack.append(current) traversal_lis.append(current.data)", "true then print as well. Algorithm: 1. Create stack of", "!IMPORTANT: Here we're iterating on current-right as we're doing postorder", "top b. Push top->data to traversal_list c. Append top->left and", "is not None or node_stack is not empty a. While", "end=' ') return traversal_list def main(): \"\"\" Tree Structure: 1", "current-right as we're doing postorder traversal b. If node_stack is", "= node_stack.pop() traversal_lis.append(node.data) current = node.right if write: for item", "assign current to poped_node->right \"\"\" traversal_lis = [] node_stack =", "traversal. If write is True then print as well. This", "of stack and print that node c. mark current as", "current is not empty push current to nde_stack and reassign", "tree.levelorder_traversal(write=False) == [1, 2, 3, 4, 5] if __name__ ==", "of node data as preorder traversal. If write is true", "list of node data as inorder traversal. If write is", "traversal_list def main(): \"\"\" Tree Structure: 1 / \\ 2", "= BinaryTree(3) tree.left.left = BinaryTree(4) tree.left.right = BinaryTree(5) assert tree.inorder_traversal(write=False)", "= current.right if node_stack: node = node_stack.pop() current = node.left", "While current is not empty i. Push current to node_stack", "current or node_stack: while current: node_stack.append(current) traversal_lis.append(current.data) current = current.left", "top->left and top->right into node_queue if they are not null", "traversal_lis: print(item, end=' ') return traversal_lis def preorder_traversal(self, write=True): \"\"\"", "push current to nde_stack and reassign current to current->left b.", "preorder_traversal(self, write=True): \"\"\" Return list of node data as preorder", "current = node.right if write: for item in traversal_lis: print(item,", "not empty then pop the top of stack and print", "tree.preorder_traversal(write=False) == [1, 2, 4, 5, 3] assert tree.postorder_traversal(write=False) ==", "is not None i. Push current to node_stack ii. Append", "current to current->left b. If current is empty and node_stack", "node of node_queue as top b. Push top->data to traversal_list", "') return traversal_lis def levelorder_traversal(self, write=True): \"\"\" Return list of", "ii. Append current->data to traversal_list iii. Reassign current as current->right", "__init__(self, data, left=None, right=None): if data is None: raise ValueError('data", "right def insert(self, data): raise NotImplementedError('Method insert is not Implemented')", "empty a. While current is not empty i. Push current", "Push top->data to traversal_list c. Append top->left and top->right into", "traversal_list = [] node_queue = deque() node_queue.append(self) while node_queue: top", "to node_queue 3. While node_queue is not empty a. Get", "= right def insert(self, data): raise NotImplementedError('Method insert is not", "assert tree.levelorder_traversal(write=False) == [1, 2, 3, 4, 5] if __name__", "i. Push current to node_stack ii. Append current->data to traversal_list", "== [1, 2, 3, 4, 5] if __name__ == '__main__':", "and node_stack is not empty then pop the top of", "a iterative tree inorder traversal. Algorithm: 1. Create a stack", "node_stack = [] current = self while current or node_stack:", "Maintain a queue of nodes to process as node_queue 2.", "current: node_stack.append(current) current = current.left if node_stack: node = node_stack.pop()", "traversal_list iii. Reassign current to current->left b. If node_stack is", "node_queue if they are not null \"\"\" traversal_list = []", "a stack of nodes node_stack 2. Mark root as current", "not empty then pop the topmost node from node_stack and", "current.right if node_stack: node = node_stack.pop() current = node.left if", "Add current->data to traversal_list iii. Reassign current to current->left b.", "as preorder traversal. If write is true then print as", "process as node_queue 2. Push root to node_queue 3. While", "null \"\"\" traversal_list = [] node_queue = deque() node_queue.append(self) while", "item in traversal_lis: print(item, end=' ') return traversal_lis def levelorder_traversal(self,", "= node.right if write: for item in traversal_lis: print(item, end='", "then pop the topmost node from node_stack and assign current", "') return traversal_list def main(): \"\"\" Tree Structure: 1 /", "i. Push current to node_stack ii. Add current->data to traversal_list", "import deque class BinaryTree(object): \"\"\" Representation of a general binary", "of nodes node_stack 2. Mark root as current 3. While", "of node data as postorder traversal. If write is true", "not empty i. Push current to node_stack ii. Add current->data", "to traversal_list c. Append top->left and top->right into node_queue if", "While current is not none or node_stack is not empty", "as node_queue 2. Push root to node_queue 3. While node_queue", "write is true then print as well. Algorithm: 1. Create", "current to node_stack ii. Append current->data to traversal_list iii. Reassign", "iii. Reassign current to current->left b. If node_stack is not", "[1, 3, 2, 5, 4] assert tree.levelorder_traversal(write=False) == [1, 2,", "assign poped_node->left to current \"\"\" traversal_lis = [] node_stack =", "raise NotImplementedError('Method insert is not Implemented') def delete(self, data): raise", "BinaryTree(5) assert tree.inorder_traversal(write=False) == [4, 2, 5, 1, 3] assert", "Algorithm: 1. Create a stack of nodes node_stack 2. Mark", "= current.left if node_stack: node = node_stack.pop() traversal_lis.append(node.data) current =", "node.left if write: for item in traversal_lis: print(item, end=' ')", "current = self while current or node_stack: while current: node_stack.append(current)", "current->data to traversal_list iii. Reassign current as current->right !IMPORTANT: Here", "traversal b. If node_stack is not empty then pop top", "is not empty i. Push current to node_stack ii. Add", "not empty a. While current is not empty push current", "= node_stack.pop() current = node.left if write: for item in", "node_queue 2. Push root to node_queue 3. While node_queue is", "then pop the top of stack and print that node", "3] assert tree.preorder_traversal(write=False) == [1, 2, 4, 5, 3] assert", "1. Maintain a queue of nodes to process as node_queue", "Return list of node data as preorder traversal. If write", "while current: node_stack.append(current) traversal_lis.append(current.data) current = current.right if node_stack: node", "if node_stack: node = node_stack.pop() current = node.right if write:", "print as well. Algorithm: 1. Maintain a queue of nodes", "= BinaryTree(5) assert tree.inorder_traversal(write=False) == [4, 2, 5, 1, 3]", "as postorder traversal. If write is true then print as", "iterating on current-right as we're doing postorder traversal b. If", "node data as preorder traversal. If write is true then", "Traversal 2. Pre-Order Traversal 3. Post-Order Traversal 4. Level-Order Traversal", "value of element left: Left subtree right: Right subtree \"\"\"", "collections import deque class BinaryTree(object): \"\"\" Representation of a general", "and basic properties 1. In-Order Traversal 2. Pre-Order Traversal 3.", "node_stack ii. Add current->data to traversal_list iii. Reassign current to", "deque class BinaryTree(object): \"\"\" Representation of a general binary tree", "current 3. While current is not none or node_stack is", "is not empty a. While current is not empty i.", "2. Push root to node_queue 3. While node_queue is not", "delete is not implemented') def inorder_traversal(self, write=True): \"\"\" Return list", "null') self.data = data self.left = left self.right = right", "print that node c. mark current as poped_node->right \"\"\" traversal_lis", "Push root to node_queue 3. While node_queue is not empty", "5, 3] assert tree.postorder_traversal(write=False) == [1, 3, 2, 5, 4]", "queue of nodes to process as node_queue 2. Push root", "empty i. Push current to node_stack ii. Add current->data to", "top->right into node_queue if they are not null \"\"\" traversal_list", "not null \"\"\" traversal_list = [] node_queue = deque() node_queue.append(self)", "of node data as level order traversal. If write is", "nodes node_stack 2. Mark root as current 3. While current", "node = node_stack.pop() current = node.left if write: for item", "as we're doing postorder traversal b. If node_stack is not", "traversal. If write is true then print as well. Algorithm:", "node data as inorder traversal. If write is True then", "current->data to traversal_list iii. Reassign current to current->left b. If", "write=True): \"\"\" Return list of node data as level order", "current: node_stack.append(current) traversal_lis.append(current.data) current = current.left if node_stack: node =", "\\ 2 3 / \\ 4 5 \"\"\" tree =", "= node.left if write: for item in traversal_lis: print(item, end='", "not Implemented') def delete(self, data): raise NotImplementedError('Method delete is not", "a general binary tree data: value of element left: Left", "data self.left = left self.right = right def insert(self, data):", "If node_stack is not empty then pop the topmost node", "node_stack.append(current) current = current.left if node_stack: node = node_stack.pop() traversal_lis.append(node.data)", "In-Order Traversal 2. Pre-Order Traversal 3. Post-Order Traversal 4. Level-Order", "data as preorder traversal. If write is true then print", "to current \"\"\" traversal_lis = [] node_stack = [] current", "= [] node_stack = [] current = self while current", "current->left b. If current is empty and node_stack is not", "traversal_lis.append(current.data) current = current.right if node_stack: node = node_stack.pop() current", "node_queue: top = node_queue.popleft() traversal_list.append(top.data) if top.left: node_queue.append(top.left) if top.right:", "assert tree.postorder_traversal(write=False) == [1, 3, 2, 5, 4] assert tree.levelorder_traversal(write=False)", "print(item, end=' ') return traversal_lis def levelorder_traversal(self, write=True): \"\"\" Return", "ValueError('data cannot be null') self.data = data self.left = left", "traversal_lis def postorder_traversal(self, write=True): \"\"\" Return list of node data", "mark current as poped_node->right \"\"\" traversal_lis = [] node_stack =", "self while current or node_stack: while current: node_stack.append(current) traversal_lis.append(current.data) current", "while current or node_stack: while current: node_stack.append(current) traversal_lis.append(current.data) current =", "nde_stack and reassign current to current->left b. If current is", "While current is not None or node_stack is not empty", "= BinaryTree(4) tree.left.right = BinaryTree(5) assert tree.inorder_traversal(write=False) == [4, 2,", "Tree and basic properties 1. In-Order Traversal 2. Pre-Order Traversal", "as level order traversal. If write is true then print", "write=True): \"\"\" Return list of node data as inorder traversal.", "current = node.left if write: for item in traversal_lis: print(item,", "traversal_lis def levelorder_traversal(self, write=True): \"\"\" Return list of node data", "3. While node_queue is not empty a. Get top node", "while node_queue: top = node_queue.popleft() traversal_list.append(top.data) if top.left: node_queue.append(top.left) if", "as current 3. While current is not None or node_stack", "1, 3] assert tree.preorder_traversal(write=False) == [1, 2, 4, 5, 3]", "current or node_stack: while current: node_stack.append(current) traversal_lis.append(current.data) current = current.right", "/ \\ 4 5 \"\"\" tree = BinaryTree(1) tree.left =", "left: Left subtree right: Right subtree \"\"\" def __init__(self, data,", "This is a iterative tree inorder traversal. Algorithm: 1. Create", "node_queue.append(top.right) if write: for item in traversal_list: print(item, end=' ')", "stack of nodes as node_stack 2. Mark root as current", "None i. Push current to node_stack ii. Append current->data to", "data, left=None, right=None): if data is None: raise ValueError('data cannot", "5 \"\"\" tree = BinaryTree(1) tree.left = BinaryTree(2) tree.right =", "= [] node_queue = deque() node_queue.append(self) while node_queue: top =", "node_queue 3. While node_queue is not empty a. Get top", "4] assert tree.levelorder_traversal(write=False) == [1, 2, 3, 4, 5] if", "node_queue is not empty a. Get top node of node_queue", "current to poped_node->right \"\"\" traversal_lis = [] node_stack = []", "= current.left if node_stack: node = node_stack.pop() current = node.right", "\"\"\" from collections import deque class BinaryTree(object): \"\"\" Representation of", "return traversal_list def main(): \"\"\" Tree Structure: 1 / \\", "node_stack: while current: node_stack.append(current) current = current.left if node_stack: node", "node_stack.pop() current = node.right if write: for item in traversal_lis:", "2 3 / \\ 4 5 \"\"\" tree = BinaryTree(1)", "to current->left b. If current is empty and node_stack is", "current as poped_node->right \"\"\" traversal_lis = [] node_stack = []", "\"\"\" traversal_lis = [] node_stack = [] current = self", "current \"\"\" traversal_lis = [] node_stack = [] current =", "traversal_list.append(top.data) if top.left: node_queue.append(top.left) if top.right: node_queue.append(top.right) if write: for", "that node c. mark current as poped_node->right \"\"\" traversal_lis =", "empty a. While current is not empty push current to", "Right subtree \"\"\" def __init__(self, data, left=None, right=None): if data", "3] assert tree.postorder_traversal(write=False) == [1, 3, 2, 5, 4] assert", "node_stack is not empty then pop the top of stack", "properties 1. In-Order Traversal 2. Pre-Order Traversal 3. Post-Order Traversal", "empty a. While current is not None i. Push current", "is a iterative tree inorder traversal. Algorithm: 1. Create a", "not empty a. Get top node of node_queue as top", "then pop top node and assign poped_node->left to current \"\"\"", "NotImplementedError('Method delete is not implemented') def inorder_traversal(self, write=True): \"\"\" Return", "traversal_list iii. Reassign current as current->right !IMPORTANT: Here we're iterating", "as poped_node->right \"\"\" traversal_lis = [] node_stack = [] current", "write: for item in traversal_lis: print(item, end=' ') return traversal_lis", "traversal_lis def preorder_traversal(self, write=True): \"\"\" Return list of node data", "then print as well. Algorithm: 1. Create stack of nodes", "is not empty a. Get top node of node_queue as", "is empty and node_stack is not empty then pop the", "node_stack.append(current) traversal_lis.append(current.data) current = current.left if node_stack: node = node_stack.pop()", "\\ 4 5 \"\"\" tree = BinaryTree(1) tree.left = BinaryTree(2)", "traversal_list: print(item, end=' ') return traversal_list def main(): \"\"\" Tree", "Left subtree right: Right subtree \"\"\" def __init__(self, data, left=None,", "or node_stack: while current: node_stack.append(current) current = current.left if node_stack:", "data is None: raise ValueError('data cannot be null') self.data =", "Append current->data to traversal_list iii. Reassign current as current->right !IMPORTANT:", "current: node_stack.append(current) traversal_lis.append(current.data) current = current.right if node_stack: node =", "current = current.left if node_stack: node = node_stack.pop() current =", "Push current to node_stack ii. Append current->data to traversal_list iii.", "postorder traversal. If write is true then print as well.", "While node_queue is not empty a. Get top node of", "BinaryTree(4) tree.left.right = BinaryTree(5) assert tree.inorder_traversal(write=False) == [4, 2, 5,", "or node_stack: while current: node_stack.append(current) traversal_lis.append(current.data) current = current.right if", "while current: node_stack.append(current) traversal_lis.append(current.data) current = current.left if node_stack: node", "print(item, end=' ') return traversal_lis def postorder_traversal(self, write=True): \"\"\" Return", "reassign current to current->left b. If current is empty and", "b. Push top->data to traversal_list c. Append top->left and top->right", "general binary tree data: value of element left: Left subtree", "top.left: node_queue.append(top.left) if top.right: node_queue.append(top.right) if write: for item in", "to current->left b. If node_stack is not empty then pop", "self.data = data self.left = left self.right = right def", "element left: Left subtree right: Right subtree \"\"\" def __init__(self,", "basic properties 1. In-Order Traversal 2. Pre-Order Traversal 3. Post-Order", "inorder traversal. Algorithm: 1. Create a stack of nodes node_stack", "in traversal_lis: print(item, end=' ') return traversal_lis def postorder_traversal(self, write=True):", "for item in traversal_lis: print(item, end=' ') return traversal_lis def", "pop the topmost node from node_stack and assign current to", "postorder_traversal(self, write=True): \"\"\" Return list of node data as postorder", "as node_stack 2. Mark root as current 3. While current", "node_queue.popleft() traversal_list.append(top.data) if top.left: node_queue.append(top.left) if top.right: node_queue.append(top.right) if write:", "Return list of node data as inorder traversal. If write", "node = node_stack.pop() current = node.right if write: for item", "insert(self, data): raise NotImplementedError('Method insert is not Implemented') def delete(self,", "and reassign current to current->left b. If current is empty", "node_stack: node = node_stack.pop() current = node.right if write: for", "True then print as well. This is a iterative tree", "not empty a. While current is not None i. Push", "def main(): \"\"\" Tree Structure: 1 / \\ 2 3", "node = node_stack.pop() traversal_lis.append(node.data) current = node.right if write: for", "as well. This is a iterative tree inorder traversal. Algorithm:", "node_stack and assign current to poped_node->right \"\"\" traversal_lis = []", "as inorder traversal. If write is True then print as", "current.left if node_stack: node = node_stack.pop() traversal_lis.append(node.data) current = node.right", "list of node data as level order traversal. If write", "poped_node->right \"\"\" traversal_lis = [] node_stack = [] current =", "node_queue = deque() node_queue.append(self) while node_queue: top = node_queue.popleft() traversal_list.append(top.data)", "Return list of node data as level order traversal. If", "traversal. Algorithm: 1. Create a stack of nodes node_stack 2.", "self.right = right def insert(self, data): raise NotImplementedError('Method insert is", "item in traversal_list: print(item, end=' ') return traversal_list def main():", "data as postorder traversal. If write is true then print", "If write is true then print as well. Algorithm: 1.", "None or node_stack is not empty a. While current is", "== [1, 2, 4, 5, 3] assert tree.postorder_traversal(write=False) == [1,", "current to current->left b. If node_stack is not empty then", "is not empty a. While current is not empty push", "node_stack.pop() current = node.left if write: for item in traversal_lis:", "[] node_stack = [] current = self while current or", "to process as node_queue 2. Push root to node_queue 3.", "3, 2, 5, 4] assert tree.levelorder_traversal(write=False) == [1, 2, 3,", "node_stack is not empty then pop the topmost node from", "4, 5, 3] assert tree.postorder_traversal(write=False) == [1, 3, 2, 5,", "= BinaryTree(2) tree.right = BinaryTree(3) tree.left.left = BinaryTree(4) tree.left.right =", "if top.right: node_queue.append(top.right) if write: for item in traversal_list: print(item,", "is None: raise ValueError('data cannot be null') self.data = data", "b. If node_stack is not empty then pop the topmost", "tree.right = BinaryTree(3) tree.left.left = BinaryTree(4) tree.left.right = BinaryTree(5) assert", "\"\"\" Representation of a general binary tree data: value of", "data): raise NotImplementedError('Method insert is not Implemented') def delete(self, data):", "of node data as inorder traversal. If write is True", "== [1, 3, 2, 5, 4] assert tree.levelorder_traversal(write=False) == [1,", "current 3. While current is not None or node_stack is", "traversal_lis = [] node_stack = [] current = self while", "Pre-Order Traversal 3. Post-Order Traversal 4. Level-Order Traversal \"\"\" from", "b. If node_stack is not empty then pop top node", "top = node_queue.popleft() traversal_list.append(top.data) if top.left: node_queue.append(top.left) if top.right: node_queue.append(top.right)", "') return traversal_lis def preorder_traversal(self, write=True): \"\"\" Return list of", "= node_queue.popleft() traversal_list.append(top.data) if top.left: node_queue.append(top.left) if top.right: node_queue.append(top.right) if", "of a general binary tree data: value of element left:", "node c. mark current as poped_node->right \"\"\" traversal_lis = []", "tree inorder traversal. Algorithm: 1. Create a stack of nodes", "current = current.right if node_stack: node = node_stack.pop() current =", "tree.left.left = BinaryTree(4) tree.left.right = BinaryTree(5) assert tree.inorder_traversal(write=False) == [4,", "def inorder_traversal(self, write=True): \"\"\" Return list of node data as", "nodes to process as node_queue 2. Push root to node_queue", "tree.inorder_traversal(write=False) == [4, 2, 5, 1, 3] assert tree.preorder_traversal(write=False) ==", "right=None): if data is None: raise ValueError('data cannot be null')", "While current is not None i. Push current to node_stack", "inorder_traversal(self, write=True): \"\"\" Return list of node data as inorder", "Post-Order Traversal 4. Level-Order Traversal \"\"\" from collections import deque", "deque() node_queue.append(self) while node_queue: top = node_queue.popleft() traversal_list.append(top.data) if top.left:", "node from node_stack and assign current to poped_node->right \"\"\" traversal_lis", "\"\"\" def __init__(self, data, left=None, right=None): if data is None:", "Get top node of node_queue as top b. Push top->data", "assert tree.inorder_traversal(write=False) == [4, 2, 5, 1, 3] assert tree.preorder_traversal(write=False)", "raise NotImplementedError('Method delete is not implemented') def inorder_traversal(self, write=True): \"\"\"", "c. mark current as poped_node->right \"\"\" traversal_lis = [] node_stack", "current is not none or node_stack is not empty a.", "empty a. Get top node of node_queue as top b.", "for item in traversal_list: print(item, end=' ') return traversal_list def", "subtree right: Right subtree \"\"\" def __init__(self, data, left=None, right=None):", "of element left: Left subtree right: Right subtree \"\"\" def", "return traversal_lis def postorder_traversal(self, write=True): \"\"\" Return list of node", "stack of nodes node_stack 2. Mark root as current 3.", "Create a stack of nodes node_stack 2. Mark root as", "empty and node_stack is not empty then pop the top", "end=' ') return traversal_lis def preorder_traversal(self, write=True): \"\"\" Return list", "topmost node from node_stack and assign current to poped_node->right \"\"\"", "return traversal_lis def preorder_traversal(self, write=True): \"\"\" Return list of node", "top->data to traversal_list c. Append top->left and top->right into node_queue", "not empty a. While current is not empty i. Push", "2. Pre-Order Traversal 3. Post-Order Traversal 4. Level-Order Traversal \"\"\"", "pop the top of stack and print that node c.", "end=' ') return traversal_lis def postorder_traversal(self, write=True): \"\"\" Return list", "if top.left: node_queue.append(top.left) if top.right: node_queue.append(top.right) if write: for item", "well. Algorithm: 1. Create stack of nodes as node_stack 2.", "node_queue.append(self) while node_queue: top = node_queue.popleft() traversal_list.append(top.data) if top.left: node_queue.append(top.left)", "current->left b. If node_stack is not empty then pop the", "implemented') def inorder_traversal(self, write=True): \"\"\" Return list of node data", "current to node_stack ii. Add current->data to traversal_list iii. Reassign", "BinaryTree(3) tree.left.left = BinaryTree(4) tree.left.right = BinaryTree(5) assert tree.inorder_traversal(write=False) ==", "tree data: value of element left: Left subtree right: Right", "none or node_stack is not empty a. While current is", "assert tree.preorder_traversal(write=False) == [1, 2, 4, 5, 3] assert tree.postorder_traversal(write=False)", "def levelorder_traversal(self, write=True): \"\"\" Return list of node data as", "write=True): \"\"\" Return list of node data as preorder traversal.", "a. While current is not empty push current to nde_stack", "\"\"\" Return list of node data as preorder traversal. If", "<reponame>daemonslayer/Notebook \"\"\" Binary Tree and basic properties 1. In-Order Traversal", "is not implemented') def inorder_traversal(self, write=True): \"\"\" Return list of", "current is not None or node_stack is not empty a.", "if write: for item in traversal_list: print(item, end=' ') return", "left=None, right=None): if data is None: raise ValueError('data cannot be", "traversal_lis: print(item, end=' ') return traversal_lis def postorder_traversal(self, write=True): \"\"\"", "is not empty push current to nde_stack and reassign current", "self while current or node_stack: while current: node_stack.append(current) current =", "to nde_stack and reassign current to current->left b. If current", "node_stack 2. Mark root as current 3. While current is", "node_queue as top b. Push top->data to traversal_list c. Append", "node_stack.pop() traversal_lis.append(node.data) current = node.right if write: for item in", "of nodes as node_stack 2. Mark root as current 3.", "node_stack: node = node_stack.pop() traversal_lis.append(node.data) current = node.right if write:", "cannot be null') self.data = data self.left = left self.right", "current or node_stack: while current: node_stack.append(current) current = current.left if", "order traversal. If write is true then print as well.", "\"\"\" traversal_list = [] node_queue = deque() node_queue.append(self) while node_queue:", "a. While current is not empty i. Push current to", "= data self.left = left self.right = right def insert(self,", "well. This is a iterative tree inorder traversal. Algorithm: 1.", "1. Create stack of nodes as node_stack 2. Mark root", "and top->right into node_queue if they are not null \"\"\"", "the topmost node from node_stack and assign current to poped_node->right", "write: for item in traversal_list: print(item, end=' ') return traversal_list", "[4, 2, 5, 1, 3] assert tree.preorder_traversal(write=False) == [1, 2,", "empty push current to nde_stack and reassign current to current->left", "a. While current is not None i. Push current to", "node_queue.append(top.left) if top.right: node_queue.append(top.right) if write: for item in traversal_list:", "is not empty a. While current is not None i.", "BinaryTree(1) tree.left = BinaryTree(2) tree.right = BinaryTree(3) tree.left.left = BinaryTree(4)", "Implemented') def delete(self, data): raise NotImplementedError('Method delete is not implemented')", "to poped_node->right \"\"\" traversal_lis = [] node_stack = [] current", "traversal_list c. Append top->left and top->right into node_queue if they", "write=True): \"\"\" Return list of node data as postorder traversal.", "== [4, 2, 5, 1, 3] assert tree.preorder_traversal(write=False) == [1,", "self.left = left self.right = right def insert(self, data): raise", "node data as postorder traversal. If write is true then", "as well. Algorithm: 1. Create stack of nodes as node_stack", "traversal_lis.append(node.data) current = node.right if write: for item in traversal_lis:", "= self while current or node_stack: while current: node_stack.append(current) current", "current->right !IMPORTANT: Here we're iterating on current-right as we're doing", "current is empty and node_stack is not empty then pop", "into node_queue if they are not null \"\"\" traversal_list =", "is not Implemented') def delete(self, data): raise NotImplementedError('Method delete is", "Mark root as current 3. While current is not None", "current is not None i. Push current to node_stack ii.", "main(): \"\"\" Tree Structure: 1 / \\ 2 3 /", "node_stack: while current: node_stack.append(current) traversal_lis.append(current.data) current = current.left if node_stack:", "None: raise ValueError('data cannot be null') self.data = data self.left", "raise ValueError('data cannot be null') self.data = data self.left =", "/ \\ 2 3 / \\ 4 5 \"\"\" tree", "4. Level-Order Traversal \"\"\" from collections import deque class BinaryTree(object):", "\"\"\" Return list of node data as level order traversal.", "= deque() node_queue.append(self) while node_queue: top = node_queue.popleft() traversal_list.append(top.data) if", "we're doing postorder traversal b. If node_stack is not empty", "data as inorder traversal. If write is True then print", "def postorder_traversal(self, write=True): \"\"\" Return list of node data as", "3 / \\ 4 5 \"\"\" tree = BinaryTree(1) tree.left", "print(item, end=' ') return traversal_lis def preorder_traversal(self, write=True): \"\"\" Return", "node_stack.append(current) traversal_lis.append(current.data) current = current.right if node_stack: node = node_stack.pop()", "a. Get top node of node_queue as top b. Push", "4 5 \"\"\" tree = BinaryTree(1) tree.left = BinaryTree(2) tree.right", "def insert(self, data): raise NotImplementedError('Method insert is not Implemented') def", "empty then pop the topmost node from node_stack and assign", "Traversal 3. Post-Order Traversal 4. Level-Order Traversal \"\"\" from collections", "in traversal_list: print(item, end=' ') return traversal_list def main(): \"\"\"", "if write: for item in traversal_lis: print(item, end=' ') return", "BinaryTree(2) tree.right = BinaryTree(3) tree.left.left = BinaryTree(4) tree.left.right = BinaryTree(5)", "or node_stack: while current: node_stack.append(current) traversal_lis.append(current.data) current = current.left if", "\"\"\" Return list of node data as inorder traversal. If", "iii. Reassign current as current->right !IMPORTANT: Here we're iterating on", "Structure: 1 / \\ 2 3 / \\ 4 5", "= left self.right = right def insert(self, data): raise NotImplementedError('Method", "root as current 3. While current is not None or", "levelorder_traversal(self, write=True): \"\"\" Return list of node data as level", "Append top->left and top->right into node_queue if they are not", "they are not null \"\"\" traversal_list = [] node_queue =", "[] current = self while current or node_stack: while current:", "while current: node_stack.append(current) current = current.left if node_stack: node =", "print(item, end=' ') return traversal_list def main(): \"\"\" Tree Structure:", "NotImplementedError('Method insert is not Implemented') def delete(self, data): raise NotImplementedError('Method", "not empty push current to nde_stack and reassign current to", "write is true then print as well. Algorithm: 1. Maintain", "Algorithm: 1. Create stack of nodes as node_stack 2. Mark", "def preorder_traversal(self, write=True): \"\"\" Return list of node data as", "binary tree data: value of element left: Left subtree right:", "top.right: node_queue.append(top.right) if write: for item in traversal_list: print(item, end='", "data): raise NotImplementedError('Method delete is not implemented') def inorder_traversal(self, write=True):", "Representation of a general binary tree data: value of element", "current to nde_stack and reassign current to current->left b. If", "list of node data as postorder traversal. If write is" ]
[ "as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_HOST,", "CONF_PASSWORD, CONF_PATH, CONF_USERNAME DOMAIN = \"vaddio_conferenceshot\" DATA_SCHEMA = vol.Schema( {", "cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, } ) SERVICE_RECALL_PRESET = \"move_to_preset\"", "vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, } )", "import CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_USERNAME DOMAIN = \"vaddio_conferenceshot\" DATA_SCHEMA =", "vol import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_HOST, CONF_PASSWORD,", "vol.Required(CONF_PASSWORD): cv.string, } ) SERVICE_RECALL_PRESET = \"move_to_preset\" ATTR_PRESET_ID = \"preset\"", "cv from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_USERNAME DOMAIN =", "as cv from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_USERNAME DOMAIN", "import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const", "vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, } ) SERVICE_RECALL_PRESET =", "= vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, }", "import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PATH,", "DOMAIN = \"vaddio_conferenceshot\" DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME):", "= \"vaddio_conferenceshot\" DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string,", "voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import", "DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string,", "cv.string, vol.Required(CONF_PASSWORD): cv.string, } ) SERVICE_RECALL_PRESET = \"move_to_preset\" ATTR_PRESET_ID =", "vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, } ) SERVICE_RECALL_PRESET = \"move_to_preset\" ATTR_PRESET_ID", "CONF_PATH, CONF_USERNAME DOMAIN = \"vaddio_conferenceshot\" DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST):", "homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_USERNAME", "{ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, } ) SERVICE_RECALL_PRESET", "homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_USERNAME DOMAIN = \"vaddio_conferenceshot\" DATA_SCHEMA", "CONF_USERNAME DOMAIN = \"vaddio_conferenceshot\" DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string,", "from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_USERNAME DOMAIN = \"vaddio_conferenceshot\"", "CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_USERNAME DOMAIN = \"vaddio_conferenceshot\" DATA_SCHEMA = vol.Schema(", "\"vaddio_conferenceshot\" DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD):" ]
[ "result = reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding time {time.time() - start} s\") result_ctx", "OpuUserInput.from_traits(X_enc, self._runner.traits) self._debug(str(user_input)) if user_input.is_batch and not self._s.simulated: # With", "= self.device.random_matrix if rnd_mat is None or rnd_mat.shape != (n_features,", "self.disable_pbar = disable_pbar self.rescale = rescale # Get trace and", "self.__opu_config @property def rescale(self): return self._rescale @rescale.setter def rescale(self, value):", "your machine the random matrix is then generated at __init__,", "calls. .. warning:: when making several transform calls, prefer calling", "online: bool, is_2d_features: bool, **override): \"\"\"Internal working of the fitXd", "if not found n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), # min_n_components", "close it if not self._s.simulated: state[\"__online_acq\"] = self.device.acq_state.value == AcqState.online.value", "self.device.reserve(self._s.n_samples_by_pass) if self._s.detect_trigger: # Detect trigger issue, and take action", "lightonml.internal import config, output_roi, utils, types from lightonml.internal.user_input import OpuUserInput,", "configuration files raise RuntimeError(no_config_msg) opu_type = self.config[\"type\"] frametime_us = self.config[\"input\"][\"frametime_us\"]", "transform for 1d vectors The function can be either called", "OpuSettings: \"\"\"Returns immutable settings associated with the OPU Settings are", "bool = False, n_2d_features=None, **override) -> ContextArray: \"\"\"Performs the nonlinear", "vector or n_features must be specified\" # tr_settings has no", "one, performance will be improved with the online flag set", "# noinspection PyUnresolvedReferences import lightonopu version.append(f\"lightonopu version {lightonopu.__version__}\") except ImportError:", "the minimum output size min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0), ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\", 5), detect_trigger=self.config.get(\"detect_trigger_issue\",", "OpuUserInput, InputTraits from lightonml.internal.simulated_device import SimulatedOpuDevice from lightonml.context import ContextArray", "query self.config here, in order not to # need a", "not released the resources, an error will be raised, call", "if verbose_level != -1: warnings.warn(\"Verbose level arg will removed in", "output = output / (self._s.stdev * sqrt(n_features)) elif self.rescale is", "is OutputRescaling.variance: n_features = user_input.n_features_s output = output / (self._s.stdev", "for overriding transform settings (advanced parameters) Returns ------- Y: np.ndarray", "self._base_exposure_us = self.device.exposure_us if self._s.simulated: # build the random matrix", "take the one passed as input if opu_device: if type(opu_device).__name__", "real\") self._resize_rnd_matrix(value, self._n_components) self._max_n_features = value @property def _s(self) ->", "the one given in `fit1d` or `fit2d`. encoder_cls: encoding.base.BaseTransformer, optional", "\\\\lvert \\\\mathbf{R} \\\\mathbf{x} \\\\rvert^2 \\\\mbox{ (non-linear transform, the default)} ..", "n_features: int = None, packed: bool = False, online=False, **override):", "args for overriding transform settings (advanced parameters) \"\"\" return self.__fit(X,", "bool = False, online=False, **override): \"\"\" Configure OPU transform for", "provided packed: bool Set to true if the input vectors", "object\"\"\" # Load it when asked first time if not", "error will be raised, call `close()` or shutdown the kernel", "user input was tensor \"\"\" output = user_input.reshape_output(output) # If", "and the \"real\" number of features must be provided as", "= X else: assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't do", "= user_input.unravel_features(prepared_X) # Run the OPU transform prepared_input = OpuUserInput.from_traits(prepared_X,", "= X.shape[-1]`` If tqdm module is available, it is used", "else: self.device.output_roi = self._output_roi.compute_roi(value) # We used to call device.reserve", "has get_params method, it's for transmitting it to decoder init", "This function is the one-liner equivalent of `fit1d` and `transform`", "if no_input and self.input_roi_strategy is InputRoiStrategy.auto: # If no input_roi,", "optional class or instance of class that transforms the output", "\\\\mathbf{R}\\\\mathbf{x} \\\\mbox{ (linear transform)} Main methods are `transform`, `linear_transform`, `fit1d`", "no input_roi, replace auto by full strategy settings.input_roi_strategy = InputRoiStrategy.full", "PyPackageRequirements,PyUnresolvedReferences import torch return torch.from_numpy(output) else: return output def _raw_linear_transform(self,", "rescaling method for `linear_transform`. Ignored by `transform`. .. seealso:: `lightonml.types.OutputRescaling`", "be provided as n_features defaults to False online: bool, optional", "if needed output = self._post_transform(result_ctx, user_input, encoder, decoder_cls) # Rescale", "on the input device .. seealso:: `lightonml.internal.types.InputRoiStrategy` open_at_init: bool, optional", "# acq stack can't be pickled, will be restored state.pop(\"_acq_stack\")", "representation if True, each input vector is assumed to be", "from math import sqrt import pkg_resources from lightonml.encoding.base import NoEncoding,", "transform the input into binary vectors to be processed by", "or np.ndarray of length 2 If the input is bit-packed,", "this machine.\\n\" \\ \"You may want to run the OPU", "decoder_cls: encoder.base.BaseTransformer, optional class or instance of class that transforms", "device directly from lightonopu.internal.device import OpuDevice if not self.__config_file and", "If not provided, follow system's setting (usually True) disable_pbar: bool,", "self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn() no_config_msg = \"No configuration", "# Get default value pass_default = attr.fields(OpuSettings).n_samples_by_pass.default # Common settings", "cores. Parameters ---------- X: np.ndarray or torch.Tensor input vector, or", "\"\"\" if X is not None: # Input is provided,", "no OPU is available on your machine the random matrix", "library from lightonopu import linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi = output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy,", "# Detect trigger issue, and take action if needed issue", "\"\"\" import time from math import sqrt import pkg_resources from", "transformation matrix. If tqdm module is available, it is used", "if self.device.active: return self.device.open() # initial reservation for giving batch", "start = time.time() result = reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding time {time.time() -", "encoder = encoder_cls X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, self._runner.traits)", "except ImportError: raise RuntimeError(\"Need a lightonopu version with linear_reconstruction module\")", "features for the input, necessary if X parameter isn't provided", "needed for linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\") # initialize linear_reconstruction library from lightonopu", "attribute to add metadata \"\"\" self.fit2d(X, n_2d_features, packed, False, **override)", "then `transform`, or you might encounter an inconsistency in the", "If you need to transform one vector after each other,", "self.device.active: return self.device.open() # initial reservation for giving batch transforms", "transformed one by one, performance will be improved with the", "= OpuUserInput.from_traits(X, traits) if self._s.simulated: prepared_X = X else: assert", "for packed input :/\") if inspect.isclass(encoder_cls): encoder = encoder_cls() else:", "available with this OPU\") # Start acquisition only if online.", "int, optional deprecated, use lightonml.set_verbose_level() instead .. seealso:: `lightonml.set_verbose_level` input_roi_strategy:", "is\" \\ \" in online mode, only single vectors\" with", "input_vectors, binary encoded, packed or not packed: bool, optional whether", "\"\"\" if self.device.active: return self.device.open() # initial reservation for giving", "a buffer ready to use self.device.reserve(self._s.n_samples_by_pass) if self._s.detect_trigger: # Detect", "the nonlinear random projections of one or several input vectors.", "parameters) \"\"\" return self.__fit(X, n_features, packed, online, True, **override) def", "resources, an error will be raised, call `close()` or shutdown", "online option. If you need to transform one vector after", "ndarray, type is actually ContextArray, with a context attribute to", "be 1d or 2d. In all cases ``output.shape[:-1] = X.shape[:-1]``", "\"\"\" if traits is None: assert self._runner, \"Call fit1d or", "is negligible\"\"\" # Get default value pass_default = attr.fields(OpuSettings).n_samples_by_pass.default #", "online=False, **override): \"\"\" Configure OPU transform for 2d vectors The", "in 1.3, \" \"Use lightonml.set_verbose_level instead\", DeprecationWarning) lightonml.set_verbose_level(verbose_level) else: verbose_level", "_tr_settings(self, no_input=False, **override) -> TransformSettings: \"\"\"Returns transform settings for feeding", "of 2d input_vectors, binary encoded, packed or not n_features: tuple(int)", "input vector, or batch of 1d input_vectors, binary encoded, packed", "self.device.build_random_matrix(n_features, n_components) self._print(\"OK\") def version(self, devices=False): \"\"\"Returns a multi-line string", "# Load it when asked first time if not self.__opu_config:", "there's no OPU on this host as we didn't find", "use lightonml.set_verbose_level() instead .. seealso:: `lightonml.set_verbose_level` input_roi_strategy: types.InputRoiStrategy, optional describes", "entering fit self._acq_stack = ExitStack() self._trace(\"OPU initialized\") # Open at", "= TransformSettings(self.input_roi_strategy, self.n_components) settings = attr.evolve(init, **override) if no_input and", "to run the OPU in a simulated manner, by passing", "return self.transform(X) def __fit(self, X, n_features: IntOrTuple, packed: bool, online:", "to decoder init if inspect.isclass(decoder_cls): if hasattr(encoder, \"get_params\"): decoder =", "after the decoding step if self.rescale is OutputRescaling.variance: n_features =", "detect_trigger=self.config.get(\"detect_trigger_issue\", False), no_single_transform=self.config.get(\"no_single_transform\", False), stdev=self.config[\"output\"].get(\"stdev\", 1.), **kwargs) def _resize_rnd_matrix(self, n_features:", "interface that acquires hardware resources used by the OPU device.\"\"\"", "no_single_transform=self.config.get(\"no_single_transform\", False), stdev=self.config[\"output\"].get(\"stdev\", 1.), **kwargs) def _resize_rnd_matrix(self, n_features: int, n_components:", "also sets the output ROI self.n_components = n_components self.input_roi_strategy =", "the \"real\" number of features must be provided as n_2d_features", "InputRoiStrategy.full, \\ \"ROI strategy must be full for linear_transform to", "version(self, devices=False): \"\"\"Returns a multi-line string containing name and versions", "result_ctx = self._raw_linear_transform(X_enc, traits, user_input) # Decoding, add context, and", "to device.acquiring() self._n_components = value @property def max_n_features(self) -> int:", "to our technology.\" if simulated and opu_device is not None:", "decoder_cls(**encoder.get_params()) else: decoder = decoder_cls() else: decoder = decoder_cls output", "one vector after the other defaults to False override: dict,", "OPU output and decoded output in a tuple \"\"\" if", "int: return self._n_components @n_components.setter def n_components(self, value: int): if self._s.simulated:", "TransformRunner, FitTransformRunner from lightonml.internal.types import InputRoiStrategy, IntOrTuple, TransformOutput, AcqState from", "and a context-manager interface. Unless `open_at_init=False`, these resources are acquired", "must be transformed one by one, performance will be improved", "device is properly instantiated. If opu_device is of type SimulatedOpuDevice,", "or if input is bit-packed packed: bool, optional whether the", "and not self._s.simulated: # With batch input start acquisition first", "``n_features = 8*X.shape[-1]`` Otherwise ``n_features = X.shape[-1]`` If tqdm module", "self.device._OpuDevice__opu.nb_prelim = 1 self._debug(\"trigger issue detected, workaround applied\") else: self._debug(\"trigger", "input vectors must be transformed one by one, performance will", "exposure_us, seq_nb_prelim, None, verbose_level, name) self._base_frametime_us = self.device.frametime_us self._base_exposure_us =", "order to initiate the random matrix config_file : str, optional", "online flag set to True. Parameters ---------- X: np.ndarray or", "decoder init if inspect.isclass(decoder_cls): if hasattr(encoder, \"get_params\"): decoder = decoder_cls(**encoder.get_params())", "they can't be pickled state.pop(\"_debug\") state.pop(\"_trace\") state.pop(\"_print\") # acq stack", "RuntimeError(no_config_msg) opu_type = self.config[\"type\"] frametime_us = self.config[\"input\"][\"frametime_us\"] exposure_us = self.config[\"output\"][\"exposure_us\"]", "settings for feeding to TransformRunner\"\"\" init = TransformSettings(self.input_roi_strategy, self.n_components) settings", "to the minimum output size min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0), ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\", 5),", "max_n_features(self, value: int): if not self._s.simulated: raise AttributeError(\"max_n_feature can't be", "self._s.simulated: # With batch input start acquisition first assert self.device.acq_state.value", "X is not None: # Input is provided, do the", "for `linear_transform`. Ignored by `transform`. .. seealso:: `lightonml.types.OutputRescaling` Attributes ----------", "vector, or batch of 1d input_vectors, binary encoded, packed or", "and optional convert back to torch if needed output =", "{time.time() - start} s\") if self._s.simulated: result_ctx = rp_opu else:", "suitable for formatting prepared_X = user_input.unravel_features(prepared_X) # Run the OPU", "lightonopu.internal.device import OpuDevice if not self.__config_file and not config.host_has_opu_config(): #", "to result afterwards start = time.time() result = reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding", "no_input=False, **override) -> TransformSettings: \"\"\"Returns transform settings for feeding to", "self._runner.traits) self._debug(str(user_input)) if user_input.is_batch and not self._s.simulated: # With batch", "output = user_input.reshape_output(output) # If encoder has get_params method, it's", "self._print(\"OPU: computing the random matrix... \", end='', flush=True) self.device.build_random_matrix(n_features, n_components)", "Number of features for the input, necessary if X parameter", "config.host_has_opu_config(): # Looks like there's no OPU on this host", "to display the features on the input device \"\"\" def", "complete array of nonlinear random projections of X, of size", "dimensions, with `n_features`. When input is bit-packed the packed flag", "first time if not self.__opu_config: self.__opu_config = config.load_config(self.__config_file, self._trace) if", "ROI self.n_components = n_components self.input_roi_strategy = input_roi_strategy # Runner initialized", "= decoder_cls(**encoder.get_params()) else: decoder = decoder_cls() else: decoder = decoder_cls", "n_components) self._print(\"OK\") def version(self, devices=False): \"\"\"Returns a multi-line string containing", "prefer calling `fit1d` and then `transform`, or you might encounter", "All Rights Reserved. # This file is subject to the", "False, **override) return self.transform(X) def __fit(self, X, n_features: IntOrTuple, packed:", "must be then provided with `n_features` When input vectors must", "transform of X, for Nitro (non-linear) photonic cores. Parameters ----------", "is deprecated, you must now use fit1d and transform\") def", "by the OPU device\"\"\" self._acq_stack.close() self.device.close() self._debug(\"OPU closed\") @property def", "SimulatedOpuDevice, in order to initiate or resize the random matrix", "it tr_settings = self._tr_settings(no_input=True, **override) traits = InputTraits(n_features, packed) self._runner", "add metadata \"\"\" self.fit1d(X, None, packed, False, **override) return self.transform(X)", "input isn't bit-packed. override: keyword args for overriding transform settings", "torch.Tensor a 1d input vector, or batch of 1d input_vectors,", "progress display Parameters ---------- X: np.ndarray or torch.Tensor a 1d", "time {time.time() - start} s\") if self._s.simulated: result_ctx = rp_opu", "in bit-packed representation if True, each input vector is assumed", "for closing at the end af an indent block \"\"\"", "will be made on this vector to optimize transform parameters", "from lightonopu.internal.device import OpuDevice # noinspection PyPep8Naming class OPU: \"\"\"Interface", "lightonml.internal.user_input import OpuUserInput, InputTraits from lightonml.internal.simulated_device import SimulatedOpuDevice from lightonml.context", "TransformRunner(self._s, tr_settings, traits, device=self.device, disable_pbar=self.disable_pbar) self._acq_stack.close() if online: if self._s.no_single_transform:", "`fit2d`, and accept NumPy arrays or PyTorch tensors. The non-linear", "ContextArray: \"\"\"Performs the nonlinear random projections of 1d input vector(s).", "that acquires hardware resources used by the OPU device.\"\"\" self.__active_before_enter", "1 simulated: bool, optional performs the random projection using CPU,", "self._acq_stack = ExitStack() self._trace(\"OPU initialized\") # Open at init, unless", "import OutputRescaling # Import lightonopu only for typechecking, as it's", "def _post_transform(output, user_input, encoder, decoder_cls): \"\"\"Final steps after transform 1.", "\\\\mbox{ (linear transform)} Main methods are `transform`, `linear_transform`, `fit1d` and", "OPU parameters to it, or just vector dimensions, with `n_features`.", "input data is in bit-packed representation defaults to False override:", "OpuUserInput.from_traits(X, traits) if self._s.simulated: prepared_X = X else: assert self.device.acq_state.value", "= \"No configuration files for the OPU was found on", "try: import lightonopu.linear_reconstruction as reconstruction except ImportError: raise RuntimeError(\"Need a", "Decoding forgets about the context, re-add it to result afterwards", "@n_components.setter def n_components(self, value: int): if self._s.simulated: self._resize_rnd_matrix(self.max_n_features, value) else:", "@property def max_n_components(self): return self._output_roi.max_components @property def n_components(self) -> int:", "compute it tr_settings = self._tr_settings(no_input=True, **override) traits = InputTraits(n_features, packed)", "in `fit1d` or `fit2d`. encoder_cls: encoder.base.BaseTransformer, optional class or instance", "if type(opu_device).__name__ not in [\"SimulatedOpuDevice\", \"OpuDevice\"]: raise TypeError(\"opu_device must be", "be a 1d array, and the \"real\" number of features", "# Copyright (c) 2020 LightOn, All Rights Reserved. # This", "context attribute to add metadata \"\"\" self.fit1d(X, None, packed, False,", "\"\"\"Interface to the OPU. .. math:: \\\\mathbf{y} = \\\\lvert \\\\mathbf{R}", "with user input user_input = OpuUserInput.from_input(X, packed, is_2d_features, n_features) tr_settings", "self._s.no_single_transform: raise RuntimeError(\"Online transform isn't available with this OPU\") #", "min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0), ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\", 5), detect_trigger=self.config.get(\"detect_trigger_issue\", False), no_single_transform=self.config.get(\"no_single_transform\", False), stdev=self.config[\"output\"].get(\"stdev\",", "methods are `transform`, `linear_transform`, `fit1d` and `fit2d`, and accept NumPy", "packed: bool Set to true if the input vectors will", "2d input_vectors, binary encoded, packed or not n_features: tuple(int) Number", "1.4.1 or later, needed for linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\") # initialize linear_reconstruction", "path to the configuration file (for dev purpose) config_override: dict,", "input if opu_device: if type(opu_device).__name__ not in [\"SimulatedOpuDevice\", \"OpuDevice\"]: raise", "the output, intentionally after the decoding step if self.rescale is", "transform for 2d vectors The function can be either called", "from lightonml.internal.runner import TransformRunner, FitTransformRunner from lightonml.internal.types import InputRoiStrategy, IntOrTuple,", "it, or just vector dimensions, with ``n_features``. When input is", "reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding time {time.time() - start} s\") result_ctx = ContextArray(result,", "self.__opu_config = None self.__config_file = config_file self.__config_override = config_override self._max_n_features", "We used to call device.reserve here, but moved to device.acquiring()", "packed input :/\") if inspect.isclass(encoder_cls): encoder = encoder_cls() else: encoder", "Union[OutputRescaling, str] = OutputRescaling.variance): self.__opu_config = None self.__config_file = config_file", "method for `linear_transform`. Ignored by `transform`. max_n_features: int maximum number", "to true if the transforms will be made one vector", "or resize the random matrix device: OpuDevice or SimulatedOpuDevice underlying", "linked to the minimum output size min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0), ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\",", "has no input_roi, since it uses X to compute it", "are acquired automatically at init. If another process or kernel", "packed or not packed: bool, optional whether the input data", "traits) if self._s.simulated: prepared_X = X else: assert self.device.acq_state.value !=", "files for the OPU was found on this machine.\\n\" \\", "self.__fit(X, n_features, packed, online, False, **override) def fit2d(self, X=None, n_features:", "by passing the \" \\ \"simulated argument to True at", "immutable settings associated with the OPU Settings are immutable (attrs", "# This also sets the output ROI self.n_components = n_components", "to the configuration file (for dev purpose) config_override: dict, optional", "None or rnd_mat.shape != (n_features, n_components): self._print(\"OPU: computing the random", "attr.fields(OpuSettings).n_samples_by_pass.default # Common settings to both simulated and base kwargs", "no_input and self.input_roi_strategy is InputRoiStrategy.auto: # If no input_roi, replace", "will be restored state.pop(\"_acq_stack\") # If acquisition is ongoing, close", "self.device.active self.open() return self def __exit__(self, *args): # Don't close", "is bit-packed, specifies the shape of each input vector. Not", "and may not be present if TYPE_CHECKING: from lightonopu.internal.device import", "the random matrix config_file : str, optional path to the", "self.device.input_shape, \"output_max_shape\": self.device.output_shape_max, \"frametime_us\": self._base_frametime_us, \"exposure_us\": self._base_exposure_us} if isinstance(self.device, SimulatedOpuDevice):", "just vector dimensions, with ``n_features``. When input is bit-packed the", "native operation for the OPU, and performs at a higher", "optional optical processing unit instance linked to a physical or", "at init.\\n\" \\ \"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \" \\ \"for more details.\\n\"", "torch if needed output = self._post_transform(result_ctx, user_input, encoder, decoder_cls) #", "FitTransformRunner from lightonml.internal.types import InputRoiStrategy, IntOrTuple, TransformOutput, AcqState from lightonml.types", "Decoding, add context, and optional convert back to torch if", "override: keyword args for overriding transform settings (advanced parameters) Returns", "= self._runner.transform(user_input) else: out = self._runner.transform(user_input) return self._post_transform(out, user_input, encoder,", "user_input.n_features_s output = output / (self._s.stdev * sqrt(n_features)) elif self.rescale", "user_input.reshape_output(output) # If encoder has get_params method, it's for transmitting", "called before, for setting vector dimensions or online option. If", "rp_opu else: # Decoding forgets about the context, re-add it", "result_ctx = rp_opu else: # Decoding forgets about the context,", "linear_transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Do a linear", "happens on input assert n_features, \"either input vector or n_features", "if X parameter isn't provided packed: bool Set to true", "bit-packed, specifies the shape of each input vector. Not needed", "simulated manner, by passing the \" \\ \"simulated argument to", "user_input = OpuUserInput.from_traits(X_enc, traits) _, result_ctx = self._raw_linear_transform(X_enc, traits, user_input)", "\"\"\"Returns a multi-line string containing name and versions of the", "an ndarray, type is actually ContextArray, with a context attribute", "self._base_exposure_us} if isinstance(self.device, SimulatedOpuDevice): # Notice we never query self.config", "each input vector is assumed to be a 1d array,", "shutdown the kernel on the OPU object to release it.", "on input assert n_features, \"either input vector or n_features must", "= self._runner.traits if user_input is None: user_input = OpuUserInput.from_traits(X, traits)", "\", end='', flush=True) self.device.build_random_matrix(n_features, n_components) self._print(\"OK\") def version(self, devices=False): \"\"\"Returns", "of 1d input vector(s). This function is the one-liner equivalent", "config, output_roi, utils, types from lightonml.internal.user_input import OpuUserInput, InputTraits from", "X: np.ndarray or torch.Tensor Fit will be made on this", "the one passed as input if opu_device: if type(opu_device).__name__ not", "forces the setting of acquiring hardware resource at init. If", "start their own. self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod def _post_transform(output, user_input, encoder, decoder_cls):", "or not n_features: tuple(int) Number of features for the input,", "yet implemented for packed input :/\") if inspect.isclass(encoder_cls): encoder =", "Run the OPU transform prepared_input = OpuUserInput.from_traits(prepared_X, traits) start =", "self.config here, in order not to # need a configuration", "to use self.device.reserve(self._s.n_samples_by_pass) if self._s.detect_trigger: # Detect trigger issue, and", "parameters n_features: int Number of features for the input, necessary", "is of type SimulatedOpuDevice, the random matrix is generated at", "if user input was tensor \"\"\" output = user_input.reshape_output(output) #", "lightonml.set_verbose_level(verbose_level) else: verbose_level = lightonml.get_verbose_level() self._debug = lightonml.get_debug_fn() self._trace =", "not None: utils.recurse_update(self.__opu_config, self.__config_override) return self.__opu_config @property def rescale(self): return", "packed flag must be set to True. Number of features", "bit-packed. override: keyword args for overriding transform settings (advanced parameters)", "set if device is real\") self._resize_rnd_matrix(value, self._n_components) self._max_n_features = value", "OPU object to release it. Parameters ---------- n_components : int,", "X, packed: bool = False, n_2d_features=None, **override) -> ContextArray: \"\"\"Performs", "output def _raw_linear_transform(self, X, traits=None, user_input=None): \"\"\" Do linear_transform of", "-> OpuSettings: \"\"\"Returns immutable settings associated with the OPU Settings", "and versions of the OPU\"\"\" version = [] # Build", "self.__config_override) return self.__opu_config @property def rescale(self): return self._rescale @rescale.setter def", "user input user_input = OpuUserInput.from_input(X, packed, is_2d_features, n_features) tr_settings =", "batch of 2d input_vectors, binary encoded, packed or not packed:", "self.__config_override is not None: utils.recurse_update(self.__opu_config, self.__config_override) return self.__opu_config @property def", "n_features: tuple(int) Number of features for the input, necessary if", "- start} s\") result_ctx = ContextArray(result, rp_opu.context) return rp_opu, result_ctx", "simulated=False, rescale: Union[OutputRescaling, str] = OutputRescaling.variance): self.__opu_config = None self.__config_file", "input vectors. Each vector must have the same dimensions as", "setting vector dimensions or online option. If you need to", "**override) self._runner = FitTransformRunner(self._s, tr_settings, user_input, device=self.device, disable_pbar=self.disable_pbar) else: #", "time.time() result = reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding time {time.time() - start} s\")", "True) if open_at_init: self.open() def _tr_settings(self, no_input=False, **override) -> TransformSettings:", "at __init__, using max_n_features and n_components max_n_features: int, optional maximum", "else: out = self._runner.transform(user_input) return self._post_transform(out, user_input, encoder, decoder_cls) def", "the fit function. Parameters ---------- X: np.ndarray or torch.Tensor input", "accept NumPy arrays or PyTorch tensors. The non-linear transform (`transform`)", "transformation (read-only) input_roi_strategy: types.InputRoiStrategy, optional describes how to display the", "of the OPU\"\"\" version = [] # Build OPU name", "(attrs frozen), so generate it at each call. Performance impact", "one vector after each other, add `online=True` in the fit", "equivalent of `fit2d` and `transform` calls. .. warning:: when making", "linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi = output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy, self._s.allowed_roi, self._s.min_n_components) # This", "of each input vector. Not needed if the input isn't", "are `transform`, `linear_transform`, `fit1d` and `fit2d`, and accept NumPy arrays", "config_override: dict, optional for override of the config_file (for dev", "@property def _s(self) -> OpuSettings: \"\"\"Returns immutable settings associated with", "if user_input is None: user_input = OpuUserInput.from_traits(X, traits) if self._s.simulated:", "for simulated device return OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default, simulated=True, **kwargs ) return", "value: int): if not self._s.simulated: raise AttributeError(\"max_n_feature can't be set", "disable_pbar self.rescale = rescale # Get trace and print functions", "# Open at init, unless relevant host.json option is False", "SimulatedOpuDevice) rnd_mat = self.device.random_matrix if rnd_mat is None or rnd_mat.shape", "SimulatedOpuDevice underlying hardware that performs transformation (read-only) input_roi_strategy: types.InputRoiStrategy, optional", "OPU device\"\"\" self._acq_stack.close() self.device.close() self._debug(\"OPU closed\") @property def config(self): \"\"\"Returns", "self._post_transform(result_ctx, user_input, encoder, decoder_cls) # Rescale the output, intentionally after", "working of the fitXd calls Instantiates a TransformRunner, and start", "self._runner.traits if user_input is None: user_input = OpuUserInput.from_traits(X, traits) if", "int): if not self._s.simulated: raise AttributeError(\"max_n_feature can't be set if", "n_features, packed, online, True, **override) def transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding)", "`transform`. .. seealso:: `lightonml.types.OutputRescaling` Attributes ---------- n_components: int dimensionality of", "def fit_transform2d(self, X, packed: bool = False, n_2d_features=None, **override) ->", "files raise RuntimeError(no_config_msg) opu_type = self.config[\"type\"] frametime_us = self.config[\"input\"][\"frametime_us\"] exposure_us", "if self._s.detect_trigger: # Detect trigger issue, and take action if", "vector to optimize transform parameters n_features: int Number of features", "random matrix is generated at __init__, using max_n_features and n_components", "it is used for progress display Parameters ---------- X: np.ndarray", "or torch.Tensor a 1d input vector, or batch of 1d", "def version(self, devices=False): \"\"\"Returns a multi-line string containing name and", "and `transform` calls. .. warning:: when making several transform calls,", "either called with input vector, for fitting OPU parameters to", "reservation for giving batch transforms a buffer ready to use", "or torch.Tensor a 2d input vector, or batch of 2d", "input :/\") if inspect.isclass(encoder_cls): encoder = encoder_cls() else: encoder =", "2d input vector, or batch of 2d input_vectors, binary encoded,", "= utils.detect_trigger_issue(self.device) if issue: # noinspection PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim = 1", "\"\"\" Configure OPU transform for 2d vectors The function can", "be pickled state.pop(\"_debug\") state.pop(\"_trace\") state.pop(\"_print\") # acq stack can't be", "output def transform1d(self, *args, **kwargs): raise RuntimeError(\"transform1d is deprecated, you", "self.device.acq_state.value != AcqState.online.value, \\ \"Can't transform a batch of vectors", "-> int: return self._s.max_n_features @max_n_features.setter def max_n_features(self, value: int): if", "with self.device.acquiring(n_images=self._s.n_samples_by_pass): out = self._runner.transform(user_input) else: out = self._runner.transform(user_input) return", "context-manager interface. Unless `open_at_init=False`, these resources are acquired automatically at", "transform calls, prefer calling `fit1d` and then `transform`, or you", "# Remove logging functions, they can't be pickled state.pop(\"_debug\") state.pop(\"_trace\")", "self._rescale = OutputRescaling[value.lower()] else: assert isinstance(value, OutputRescaling) self._rescale = value", "specified\" # tr_settings has no input_roi, since it uses X", "decoder_cls output = decoder.transform(output) if user_input.is_tensor: # noinspection PyPackageRequirements,PyUnresolvedReferences import", "single vectors\" with self.device.acquiring(n_images=self._s.n_samples_by_pass): out = self._runner.transform(user_input) else: out =", "\"exposure_us\": self._base_exposure_us} if isinstance(self.device, SimulatedOpuDevice): # Notice we never query", "(torch or numpy) X2 = user_input.reshape_input(raveled_features=True, leave_single_dim=True) try: import lightonopu.linear_reconstruction", "will transform used only if opu_device is a SimulatedOpuDevice, in", "will be already bit-packed online: bool, optional Set to true", "for override of the config_file (for dev purpose) verbose_level: int,", "X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, self._runner.traits) self._debug(str(user_input)) if user_input.is_batch", "output = self._post_transform(result_ctx, user_input, encoder, decoder_cls) # Rescale the output,", "prepared_X = reconstruction.encode_batch(X2) self._trace(f\"Encoding time {time.time() - start} s\") #", "isn't bit-packed. override: keyword args for overriding transform settings (advanced", "int = -1, input_roi_strategy: types.InputRoiStrategy = types.InputRoiStrategy.full, open_at_init: bool =", "X.shape[-1]`` If tqdm module is available, it is used for", "encounter an inconsistency in the transformation matrix. The input data", "a context attribute to add metadata \"\"\" self.fit1d(X, None, packed,", "Do a linear transform of X, for Nitro (non-linear) photonic", "encoding.base.BaseTransformer, optional class or instance of class that transforms the", "cases ``output.shape[:-1] = X.shape[:-1]`` packed: bool, optional whether the input", "use defaults of OpuSettings if not found n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\",", "if devices: version.append(self.device.versions()) return '\\n'.join(version) def __getstate__(self): state = self.__dict__.copy()", "\"Can't transform a batch of vectors when acquisition is\" \\", "hasattr(encoder, \"get_params\"): decoder = decoder_cls(**encoder.get_params()) else: decoder = decoder_cls() else:", "not config.host_has_opu_config(): # Looks like there's no OPU on this", "parameters) Returns ------- Y: np.ndarray or torch.Tensor complete array of", "value @property def max_n_components(self): return self._output_roi.max_components @property def n_components(self) ->", "before transform\" assert self.device.active, \"OPU device isn't active, use opu.open()", "a linear transform of X, for Nitro (non-linear) photonic cores.", "if X parameter isn't provided, or if input is bit-packed", "* sqrt(self.n_components)) return output def transform1d(self, *args, **kwargs): raise RuntimeError(\"transform1d", "def __init__(self, n_components: int = 200000, opu_device: Optional[Union[\"OpuDevice\", SimulatedOpuDevice]] =", "to True at init.\\n\" \\ \"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \" \\ \"for", "import linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi = output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy, self._s.allowed_roi, self._s.min_n_components) #", "of OpuSettings if not found n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"),", "processed by the opu. decoder_cls: encoder.base.BaseTransformer, optional class or instance", "that transforms the output of the opu back into the", "np.ndarray or torch.Tensor complete array of nonlinear random projections of", "with `n_features`. When input is bit-packed the packed flag must", "using max_n_features and n_components max_n_features: int, optional maximum number of", "(c) 2020 LightOn, All Rights Reserved. # This file is", "stack can't be pickled, will be restored state.pop(\"_acq_stack\") # If", "vector. Not needed if the input isn't bit-packed. override: keyword", "return self.__fit(X, n_features, packed, online, False, **override) def fit2d(self, X=None,", "= {\"input_shape\": self.device.input_shape, \"output_max_shape\": self.device.output_shape_max, \"frametime_us\": self._base_frametime_us, \"exposure_us\": self._base_exposure_us} if", "pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), # min_n_components is linked to the", "the input, necessary if X parameter isn't provided packed: bool", "OpuDevice or SimulatedOpuDevice, optional optical processing unit instance linked to", "with this OPU\") # Start acquisition only if online. Batch", "if inspect.isclass(decoder_cls): if hasattr(encoder, \"get_params\"): decoder = decoder_cls(**encoder.get_params()) else: decoder", "in order to initiate or resize the random matrix device:", "This module contains the OPU class \"\"\" import time from", "self._resize_rnd_matrix(value, self._n_components) self._max_n_features = value @property def _s(self) -> OpuSettings:", "our technology.\" if simulated and opu_device is not None: raise", "one or several input vectors. The `fit1d` or `fit2d` method", "flush=True) self.device.build_random_matrix(n_features, n_components) self._print(\"OK\") def version(self, devices=False): \"\"\"Returns a multi-line", "If tqdm module is available, it is used for progress", "transform parameters n_features: int Number of features for the input,", "\\ \" in online mode, only single vectors\" with self.device.acquiring(n_images=self._s.n_samples_by_pass):", "if the input vectors will be already bit-packed online: bool,", "if device is real\") self._resize_rnd_matrix(value, self._n_components) self._max_n_features = value @property", "str = \"\", config_override: dict = None, verbose_level: int =", "self._s.simulated: raise AttributeError(\"max_n_feature can't be set if device is real\")", "self._resize_rnd_matrix(max_n_features, n_components) else: # Make sure lightonopu is at 1.4.1", "and not config.host_has_opu_config(): # Looks like there's no OPU on", "transform writeable only if opu_device is a SimulatedOpuDevice, in order", "= value @property def max_n_features(self) -> int: return self._s.max_n_features @max_n_features.setter", "settings def fit1d(self, X=None, n_features: int = None, packed: bool", "None, packed: bool = False, online=False, **override): \"\"\" Configure OPU", "def __enter__(self): \"\"\"Context manager interface that acquires hardware resources used", "_, result_ctx = self._raw_linear_transform(X_enc, traits, user_input) # Decoding, add context,", "parameters) \"\"\" return self.__fit(X, n_features, packed, online, False, **override) def", "_resize_rnd_matrix(self, n_features: int, n_components: int): \"\"\"Resize device's random matrix\"\"\" assert", "= lightonml.get_print_fn() self._acq_stack = ExitStack() # Restore online acquisition if", "output of the opu back into the appropriate format. Returns", "packed raise RuntimeError(\"Linear transform isn't yet implemented for packed input", "ongoing, close it if not self._s.simulated: state[\"__online_acq\"] = self.device.acq_state.value ==", "traits, user_input) # Decoding, add context, and optional convert back", "on this machine.\\n\" \\ \"You may want to run the", "the opu. decoder_cls: encoding.base.BaseTransformer, optional class or instance of class", "from lightonml.internal.types import InputRoiStrategy, IntOrTuple, TransformOutput, AcqState from lightonml.types import", "keyword args for overriding transform settings (advanced parameters) \"\"\" return", "None # type: Optional[TransformRunner] # ExitStack for device acquisition, initialized", "and opu_device is not None: raise ValueError(\"simulated and opu_device arguments", "self._output_roi = output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy, self._s.allowed_roi, self._s.min_n_components) # This also sets", "start online acq if needs be. \"\"\" if X is", "Instantiate device directly from lightonopu.internal.device import OpuDevice if not self.__config_file", "simulated: self.device = SimulatedOpuDevice() else: # Instantiate device directly from", "single vectors\" assert self._runner.t.input_roi_strategy == InputRoiStrategy.full, \\ \"ROI strategy must", "\"\"\"Releases hardware resources used by the OPU device\"\"\" self._acq_stack.close() self.device.close()", "device is real\") self._resize_rnd_matrix(value, self._n_components) self._max_n_features = value @property def", "an inconsistency in the transformation matrix. If tqdm module is", "def rescale(self, value): # If str it's the enum value", "the default)} .. math:: \\\\mathbf{y} = \\\\mathbf{R}\\\\mathbf{x} \\\\mbox{ (linear transform)}", "self.__dict__.copy() # Remove logging functions, they can't be pickled state.pop(\"_debug\")", "or use the context manager interface for closing at the", "/ (self._s.stdev * sqrt(n_features)) elif self.rescale is OutputRescaling.norm: output =", "the end af an indent block \"\"\" if self.device.active: return", "OPU will transform used only if opu_device is a SimulatedOpuDevice,", "provided, a device is properly instantiated. If opu_device is of", "instantiated. If opu_device is of type SimulatedOpuDevice, the random matrix", "self._s.allowed_roi, self._s.min_n_components) # This also sets the output ROI self.n_components", "False, online=False, **override): \"\"\" Configure OPU transform for 2d vectors", "# Input is provided, do the fit with user input", "# Run the OPU transform prepared_input = OpuUserInput.from_traits(prepared_X, traits) start", "vector dimensions, with ``n_features``. When input is bit-packed the packed", "on the OPU object to release it. Parameters ---------- n_components", "= None self.__config_file = config_file self.__config_override = config_override self._max_n_features =", "decoded output in a tuple \"\"\" if traits is None:", "if X is not None: # Input is provided, do", "of features for the input, necessary if X parameter isn't", "bit-packed representation defaults to False override: keyword args for overriding", "= InputTraits(n_features, packed) self._runner = TransformRunner(self._s, tr_settings, traits, device=self.device, disable_pbar=self.disable_pbar)", "in [\"SimulatedOpuDevice\", \"OpuDevice\"]: raise TypeError(\"opu_device must be of type SimulatedOpuDevice", "pkg_resources.require(\"lightonopu>=1.4.1\") # initialize linear_reconstruction library from lightonopu import linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape))", "data can be bit-packed, where ``n_features = 8*X.shape[-1]`` Otherwise ``n_features", "False override: dict, optional keyword args for overriding transform settings", "configuration files for the OPU was found on this machine.\\n\"", "file for simulated device return OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default, simulated=True, **kwargs )", "decoder_cls) def linear_transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Do", "tuple \"\"\" if traits is None: assert self._runner, \"Call fit1d", "using CPU, in case no OPU is available on your", "encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Performs the nonlinear random projections", "value if isinstance(value, str): self._rescale = OutputRescaling[value.lower()] else: assert isinstance(value,", "random projections of X, of size self.n_components If input is", "tuple or np.ndarray of length 2 If the input is", "self.close() def open(self): \"\"\"Acquires hardware resources used by the OPU", "optional class or instance of class that transform the input", "(non-linear transform, the default)} .. math:: \\\\mathbf{y} = \\\\mathbf{R}\\\\mathbf{x} \\\\mbox{", "be provided as n_2d_features defaults to False n_2d_features: list, tuple", "binary features that the OPU will transform writeable only if", "lightonml.get_print_fn() no_config_msg = \"No configuration files for the OPU was", "is available on your machine the random matrix is then", "if rnd_mat is None or rnd_mat.shape != (n_features, n_components): self._print(\"OPU:", "formatting prepared_X = user_input.unravel_features(prepared_X) # Run the OPU transform prepared_input", "transform prepared_input = OpuUserInput.from_traits(prepared_X, traits) start = time.time() with self.device.acquiring(n_images=self._s.n_samples_by_pass):", "= self._tr_settings(no_input=True, **override) traits = InputTraits(n_features, packed) self._runner = TransformRunner(self._s,", "self.device.output_shape_max, \"frametime_us\": self._base_frametime_us, \"exposure_us\": self._base_exposure_us} if isinstance(self.device, SimulatedOpuDevice): # Notice", "max_n_features and n_components rescale: types.OutputRescaling, optional, output rescaling method for", "access to our technology.\" if simulated and opu_device is not", "can't be pickled state.pop(\"_debug\") state.pop(\"_trace\") state.pop(\"_print\") # acq stack can't", "necessary if X parameter isn't provided, or if input is", "= user_input.reshape_output(output) # If encoder has get_params method, it's for", "the setting of acquiring hardware resource at init. If not", "import ExitStack import attr import inspect import lightonml from lightonml.internal.config", "you must now use fit1d and transform\") def transform2d(self, *args,", "**kwargs): raise RuntimeError(\"transform2d is deprecated, you must now use fit2d", "host as we didn't find configuration files raise RuntimeError(no_config_msg) opu_type", "version with linear_reconstruction module\") start = time.time() prepared_X = reconstruction.encode_batch(X2)", "the random matrix is generated at __init__, using max_n_features and", "import Optional, Union, Tuple, TYPE_CHECKING import numpy as np from", "was already active if not self.__active_before_enter: self.close() def open(self): \"\"\"Acquires", "assert isinstance(value, OutputRescaling) self._rescale = value @property def max_n_components(self): return", "and performs at a higher speed than `linear_transform`. Acquiring/releasing hardware", "self._n_components @n_components.setter def n_components(self, value: int): if self._s.simulated: self._resize_rnd_matrix(self.max_n_features, value)", "packed) self._runner = TransformRunner(self._s, tr_settings, traits, device=self.device, disable_pbar=self.disable_pbar) self._acq_stack.close() if", "it at each call. Performance impact is negligible\"\"\" # Get", "\"real\" number of features must be provided as n_features defaults", "argument to True at init.\\n\" \\ \"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \" \\", "or several input vectors. The `fit1d` or `fit2d` method must", "\\\\mbox{ (non-linear transform, the default)} .. math:: \\\\mathbf{y} = \\\\mathbf{R}\\\\mathbf{x}", "their own. self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod def _post_transform(output, user_input, encoder, decoder_cls): \"\"\"Final", "self._s.simulated: result_ctx = rp_opu else: # Decoding forgets about the", "it to result afterwards start = time.time() result = reconstruction.decode_batch(rp_opu)", "resources used by the OPU device\"\"\" self._acq_stack.close() self.device.close() self._debug(\"OPU closed\")", "import ContextArray from lightonml.internal.settings import OpuSettings, TransformSettings from lightonml.internal.runner import", "verbose_level: int, optional deprecated, use lightonml.set_verbose_level() instead .. seealso:: `lightonml.set_verbose_level`", "provided, or if input is bit-packed packed: bool, optional whether", "the resources, an error will be raised, call `close()` or", "rescale # Get trace and print functions if verbose_level !=", "non-linear transform (`transform`) is a native operation for the OPU,", "Each vector must have the same dimensions as the one", "before, for setting vector dimensions or online option. If you", "prefer calling `fit2d` and then `transform`, or you might encounter", "\"simulated argument to True at init.\\n\" \\ \"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \"", "{lightonopu.__version__}\") except ImportError: pass if devices: version.append(self.device.versions()) return '\\n'.join(version) def", "optional describes how to display the features on the input", "function is the one-liner equivalent of `fit1d` and `transform` calls.", "in bit-packed representation defaults to False override: keyword args for", "a configuration file for simulated device return OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default, simulated=True,", "device.reserve here, but moved to device.acquiring() self._n_components = value @property", "the one given in `fit1d` or `fit2d`. encoder_cls: encoder.base.BaseTransformer, optional", "with a context attribute to add metadata \"\"\" self.fit1d(X, None,", "with input vector, for fitting OPU parameters to it, or", "input_roi, since it uses X to compute it tr_settings =", "one by one, performance will be improved with the online", "available on your machine the random matrix is then generated", "0) name = self.config[\"name\"] self.device = OpuDevice(opu_type, frametime_us, exposure_us, seq_nb_prelim,", "passing the \" \\ \"simulated argument to True at init.\\n\"", "Ignored by `transform`. max_n_features: int maximum number of binary features", "\"\"\" return self.__fit(X, n_features, packed, online, False, **override) def fit2d(self,", "= time.time() result = reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding time {time.time() - start}", "online, True, **override) def transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput:", "is set to 1 simulated: bool, optional performs the random", "**override) def transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Performs", "!= AcqState.online.value, \\ \"Can't transform a batch of vectors when", "noinspection PyPackageRequirements,PyUnresolvedReferences import torch return torch.from_numpy(output) else: return output def", "features on the input device \"\"\" def __init__(self, n_components: int", "default)} .. math:: \\\\mathbf{y} = \\\\mathbf{R}\\\\mathbf{x} \\\\mbox{ (linear transform)} Main", "done by open/close and a context-manager interface. Unless `open_at_init=False`, these", "as the one given in `fit1d` or `fit2d`. encoder_cls: encoding.base.BaseTransformer,", "1d or 2d. In all cases ``output.shape[:-1] = X.shape[:-1]`` packed:", "configuration file (for dev purpose) config_override: dict, optional for override", "1 self._debug(\"trigger issue detected, workaround applied\") else: self._debug(\"trigger issue not", "ContextArray, with a context attribute to add metadata \"\"\" self.fit1d(X,", "is properly instantiated. If opu_device is of type SimulatedOpuDevice, the", "fit1d or fit2d before linear_transform\" traits = self._runner.traits if traits.packed:", "(non-linear) photonic cores. Parameters ---------- X: np.ndarray or torch.Tensor input", "one-liner equivalent of `fit1d` and `transform` calls. .. warning:: when", "dev purpose) config_override: dict, optional for override of the config_file", "InputTraits from lightonml.internal.simulated_device import SimulatedOpuDevice from lightonml.context import ContextArray from", "or fit2d before transform\" assert self.device.active, \"OPU device isn't active,", "= OutputRescaling[value.lower()] else: assert isinstance(value, OutputRescaling) self._rescale = value @property", "\"Call fit1d or fit2d before linear_transform\" traits = self._runner.traits if", "and transform\") def transform2d(self, *args, **kwargs): raise RuntimeError(\"transform2d is deprecated,", "tensor \"\"\" output = user_input.reshape_output(output) # If encoder has get_params", "kernel on the OPU object to release it. Parameters ----------", "False if open_at_init is None: open_at_init = get_host_option(\"lightonml_open_at_init\", True) if", "ready to use self.device.reserve(self._s.n_samples_by_pass) if self._s.detect_trigger: # Detect trigger issue,", "details.\\n\" \\ \"See also https://lighton.ai/products for getting access to our", "logging functions, they can't be pickled state.pop(\"_debug\") state.pop(\"_trace\") state.pop(\"_print\") #", "not found n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), # min_n_components is", "mode, only single vectors\" assert self._runner.t.input_roi_strategy == InputRoiStrategy.full, \\ \"ROI", "output = decoder.transform(output) if user_input.is_tensor: # noinspection PyPackageRequirements,PyUnresolvedReferences import torch", "vectors\" assert self._runner.t.input_roi_strategy == InputRoiStrategy.full, \\ \"ROI strategy must be", "# We used to call device.reserve here, but moved to", "n_features must be specified\" # tr_settings has no input_roi, since", "import lightonopu.linear_reconstruction as reconstruction except ImportError: raise RuntimeError(\"Need a lightonopu", "\" \"Use lightonml.set_verbose_level instead\", DeprecationWarning) lightonml.set_verbose_level(verbose_level) else: verbose_level = lightonml.get_verbose_level()", "the OPU device .. seealso:: `close()` or use the context", "OpuSettings, TransformSettings from lightonml.internal.runner import TransformRunner, FitTransformRunner from lightonml.internal.types import", "Not needed if the input isn't bit-packed. override: keyword args", "packed or not n_features: tuple(int) Number of features for the", "# Import lightonopu only for typechecking, as it's an optional", "SimulatedOpuDevice]] = None, max_n_features: int = 1000, config_file: str =", "isinstance(value, str): self._rescale = OutputRescaling[value.lower()] else: assert isinstance(value, OutputRescaling) self._rescale", "inspect.isclass(encoder_cls): encoder = encoder_cls() else: encoder = encoder_cls X_enc =", "user_input is None: user_input = OpuUserInput.from_traits(X, traits) if self._s.simulated: prepared_X", "= lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn() self._acq_stack =", "to InputRoiStrategy.full.\" # X2 is now numpy 2D, whatever the", "attribute to add metadata \"\"\" assert self._runner, \"Call fit1d or", "Optional[TransformRunner] # ExitStack for device acquisition, initialized when entering fit", "the initial shape and the type (torch or numpy) X2", "False), stdev=self.config[\"output\"].get(\"stdev\", 1.), **kwargs) def _resize_rnd_matrix(self, n_features: int, n_components: int):", "ImportError: pass if devices: version.append(self.device.versions()) return '\\n'.join(version) def __getstate__(self): state", "# noinspection PyPackageRequirements,PyUnresolvedReferences import torch return torch.from_numpy(output) else: return output", "type SimulatedOpuDevice or OpuDevice\") self.device = opu_device elif simulated: self.device", "linear transform when acquisition is\" \\ \" in online mode,", "value: int): if self._s.simulated: self._resize_rnd_matrix(self.max_n_features, value) else: self.device.output_roi = self._output_roi.compute_roi(value)", "the terms and conditions defined in # file 'LICENSE.txt', which", "terms and conditions defined in # file 'LICENSE.txt', which is", "no_config_msg = \"No configuration files for the OPU was found", "be correct.\\n\" \\ \"Set input_roi_strategy attribute to InputRoiStrategy.full.\" # X2", "optimize transform parameters n_features: int Number of features for the", "self._trace) if self.__config_override is not None: utils.recurse_update(self.__opu_config, self.__config_override) return self.__opu_config", "metadata \"\"\" self.fit1d(X, None, packed, False, **override) return self.transform(X) def", "a SimulatedOpuDevice, in order to initiate the random matrix config_file", "for 2d vectors The function can be either called with", "must be provided as n_features defaults to False online: bool,", "is an ndarray, type is actually ContextArray, with a context", "``n_features = X.shape[-1]`` If tqdm module is available, it is", "name and versions of the OPU\"\"\" version = [] #", "n_samples_by_pass=pass_default, simulated=True, **kwargs ) return OpuSettings( max_n_features=int(np.prod(self.device.input_shape)), # Will use", "conditions defined in # file 'LICENSE.txt', which is part of", "self.config[\"name\"] self.device = OpuDevice(opu_type, frametime_us, exposure_us, seq_nb_prelim, None, verbose_level, name)", "warnings.warn(\"Verbose level arg will removed in 1.3, \" \"Use lightonml.set_verbose_level", "be already bit-packed online: bool, optional Set to true if", "if hasattr(encoder, \"get_params\"): decoder = decoder_cls(**encoder.get_params()) else: decoder = decoder_cls()", "these resources are acquired automatically at init. If another process", "vector, or batch of 2d input_vectors, binary encoded, packed or", "**override): \"\"\" Configure OPU transform for 2d vectors The function", "initialized\") # Open at init, unless relevant host.json option is", "\\\\mathbf{y} = \\\\mathbf{R}\\\\mathbf{x} \\\\mbox{ (linear transform)} Main methods are `transform`,", "/ (self._s.stdev * sqrt(self.n_components)) return output def transform1d(self, *args, **kwargs):", "# If str it's the enum value if isinstance(value, str):", "= self._runner.transform(user_input) return self._post_transform(out, user_input, encoder, decoder_cls) def linear_transform(self, X,", "1.), **kwargs) def _resize_rnd_matrix(self, n_features: int, n_components: int): \"\"\"Resize device's", "The non-linear transform (`transform`) is a native operation for the", "it. Parameters ---------- n_components : int, dimensionality of the target", "not None: # Input is provided, do the fit with", "transform1d(self, *args, **kwargs): raise RuntimeError(\"transform1d is deprecated, you must now", "get_host_option(\"lightonml_open_at_init\", True) if open_at_init: self.open() def _tr_settings(self, no_input=False, **override) ->", "InputRoiStrategy.auto: # If no input_roi, replace auto by full strategy", "release it. Parameters ---------- n_components : int, dimensionality of the", "and the type (torch or numpy) X2 = user_input.reshape_input(raveled_features=True, leave_single_dim=True)", "`transform`, `linear_transform`, `fit1d` and `fit2d`, and accept NumPy arrays or", "or batch of 1d input_vectors, binary encoded, packed or not", "device.acquiring() self._n_components = value @property def max_n_features(self) -> int: return", "instance linked to a physical or simulated device. If not", "= self._output_roi.compute_roi(value) # We used to call device.reserve here, but", "of class that transforms the output of the opu back", "self.device.active, \"OPU device isn't active, use opu.open() or \\\"with opu:\\\"\"", "encoded, packed or not batch can be 1d or 2d.", "\"\"\" return self.__fit(X, n_features, packed, online, True, **override) def transform(self,", "detected\") self._debug(\"OPU opened\") def close(self): \"\"\"Releases hardware resources used by", "kernel has not released the resources, an error will be", "Acquiring/releasing hardware device resources is done by open/close and a", "be pickled, will be restored state.pop(\"_acq_stack\") # If acquisition is", "be raised, call `close()` or shutdown the kernel on the", "start} s\") # Restore the dimension after batch encoding to", "def open(self): \"\"\"Acquires hardware resources used by the OPU device", "a lightonopu version with linear_reconstruction module\") start = time.time() prepared_X", "opu:\\\"\" if inspect.isclass(encoder_cls): encoder = encoder_cls() else: encoder = encoder_cls", ".. seealso:: `lightonml.set_verbose_level` input_roi_strategy: types.InputRoiStrategy, optional describes how to display", "provided, no fitting happens on input assert n_features, \"either input", "functions, they can't be pickled state.pop(\"_debug\") state.pop(\"_trace\") state.pop(\"_print\") # acq", "types.OutputRescaling, output rescaling method for `linear_transform`. Ignored by `transform`. max_n_features:", "opu. decoder_cls: encoder.base.BaseTransformer, optional class or instance of class that", "computing the random matrix... \", end='', flush=True) self.device.build_random_matrix(n_features, n_components) self._print(\"OK\")", "must be set to True. When input vectors must be", "X: np.ndarray or torch.Tensor input vector, or batch of input", "Reserved. # This file is subject to the terms and", "'\\n'.join(version) def __getstate__(self): state = self.__dict__.copy() # Remove logging functions,", "PyTorch tensors. The non-linear transform (`transform`) is a native operation", "True) disable_pbar: bool, optional disable display of the progress bar", "manager interface for closing at the end af an indent", "the input device .. seealso:: `lightonml.internal.types.InputRoiStrategy` open_at_init: bool, optional forces", "\"You may want to run the OPU in a simulated", "matrix if not done already self._resize_rnd_matrix(max_n_features, n_components) else: # Make", "`n_features`. When input is bit-packed the packed flag must be", "at init. If another process or kernel has not released", "self._max_n_features = value @property def _s(self) -> OpuSettings: \"\"\"Returns immutable", "might encounter an inconsistency in the transformation matrix. If tqdm", "already bit-packed online: bool, optional Set to true if the", "self._debug(\"trigger issue not detected\") self._debug(\"OPU opened\") def close(self): \"\"\"Releases hardware", "tr_settings, traits, device=self.device, disable_pbar=self.disable_pbar) self._acq_stack.close() if online: if self._s.no_single_transform: raise", "1d vectors The function can be either called with input", "to True. Parameters ---------- X: np.ndarray or torch.Tensor a 2d", "self._runner.transform(user_input) else: out = self._runner.transform(user_input) return self._post_transform(out, user_input, encoder, decoder_cls)", "source code package. \"\"\" This module contains the OPU class", "and self.input_roi_strategy is InputRoiStrategy.auto: # If no input_roi, replace auto", "optional performs the random projection using CPU, in case no", "\"\"\"Final steps after transform 1. reshape 2. decode the output", "shape and the type (torch or numpy) X2 = user_input.reshape_input(raveled_features=True,", "= reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding time {time.time() - start} s\") result_ctx =", "- start} s\") if self._s.simulated: result_ctx = rp_opu else: #", "several input vectors. The `fit1d` or `fit2d` method must be", "vector, or batch of input vectors. Each vector must have", "bool, optional whether the input data is in bit-packed representation", "decoder = decoder_cls output = decoder.transform(output) if user_input.is_tensor: # noinspection", "__init__, using max_n_features and n_components max_n_features: int, optional maximum number", "order to initiate or resize the random matrix device: OpuDevice", "RuntimeError(\"transform1d is deprecated, you must now use fit1d and transform\")", "InputTraits(n_features, packed) self._runner = TransformRunner(self._s, tr_settings, traits, device=self.device, disable_pbar=self.disable_pbar) self._acq_stack.close()", "str, optional path to the configuration file (for dev purpose)", "made on this vector to optimize transform parameters n_features: int", "Configure OPU transform for 2d vectors The function can be", "X.shape[:-1]`` packed: bool, optional whether the input data is in", "if True, each input vector is assumed to be a", "rescale: types.OutputRescaling, optional, output rescaling method for `linear_transform`. Ignored by", "def config(self): \"\"\"Returns the internal configuration object\"\"\" # Load it", "specifies the shape of each input vector. Not needed if", "initiate the random matrix config_file : str, optional path to", "fit2d and transform\") def fit_transform1d(self, X, packed: bool = False,", "didn't find configuration files raise RuntimeError(no_config_msg) opu_type = self.config[\"type\"] frametime_us", "self.device.exposure_us if self._s.simulated: # build the random matrix if not", "machine the random matrix is then generated at __init__, using", "at the end af an indent block \"\"\" if self.device.active:", "time.time() with self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu = self._runner.transform(prepared_input, linear=True) self._trace(f\"Transform time {time.time()", "resize the random matrix device: OpuDevice or SimulatedOpuDevice underlying hardware", "# Restore online acquisition if it was the case if", "\"\"\" output = user_input.reshape_output(output) # If encoder has get_params method,", "# This file is subject to the terms and conditions", "inconsistency in the transformation matrix. If tqdm module is available,", "\\ \"ROI strategy must be full for linear_transform to be", "detected, workaround applied\") else: self._debug(\"trigger issue not detected\") self._debug(\"OPU opened\")", "online acq if needs be. \"\"\" if X is not", "dict, optional for override of the config_file (for dev purpose)", "prepared_X = user_input.unravel_features(prepared_X) # Run the OPU transform prepared_input =", "input_roi, replace auto by full strategy settings.input_roi_strategy = InputRoiStrategy.full assert", "to display the features on the input device .. seealso::", "or torch.Tensor input vector, or batch of input vectors. Each", "out = self._runner.transform(user_input) else: out = self._runner.transform(user_input) return self._post_transform(out, user_input,", "is provided, do the fit with user input user_input =", "speed than `linear_transform`. Acquiring/releasing hardware device resources is done by", "necessary if X parameter isn't provided packed: bool Set to", "not n_features: tuple(int) Number of features for the input, necessary", "n_components): self._print(\"OPU: computing the random matrix... \", end='', flush=True) self.device.build_random_matrix(n_features,", "-1, input_roi_strategy: types.InputRoiStrategy = types.InputRoiStrategy.full, open_at_init: bool = None, disable_pbar=False,", "batch of vectors when acquisition is\" \\ \" in online", "max_n_features: int = 1000, config_file: str = \"\", config_override: dict", "None, packed, False, **override) return self.transform(X) def fit_transform2d(self, X, packed:", "a 1d input vector, or batch of 1d input_vectors, binary", "online mode, only single vectors\" assert self._runner.t.input_roi_strategy == InputRoiStrategy.full, \\", "file 'LICENSE.txt', which is part of this source code package.", "self._print = lightonml.get_print_fn() self._acq_stack = ExitStack() # Restore online acquisition", "encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Do a linear transform of", "n_features: Tuple[int, int] = None, packed: bool = False, online=False,", "overriding transform settings (advanced parameters) \"\"\" return self.__fit(X, n_features, packed,", "decoder_cls: encoding.base.BaseTransformer, optional class or instance of class that transforms", "module is available, it is used for progress display Parameters", "self.device.acq_state.value != AcqState.online.value, \\ \"Can't do linear transform when acquisition", "the appropriate format. Returns ------- Y: np.ndarray or torch.Tensor complete", "if the transforms will be made one vector after the", "keyword args for overriding transform settings (advanced parameters) Returns -------", "already self._resize_rnd_matrix(max_n_features, n_components) else: # Make sure lightonopu is at", "Number of features must be then provided with `n_features` When", "after transform 1. reshape 2. decode the output 3. convert", "dimensions as the one given in `fit1d` or `fit2d`. encoder_cls:", "matrix. If tqdm module is available, it is used for", "output_roi, utils, types from lightonml.internal.user_input import OpuUserInput, InputTraits from lightonml.internal.simulated_device", "def __fit(self, X, n_features: IntOrTuple, packed: bool, online: bool, is_2d_features:", "only for typechecking, as it's an optional module and may", "= SimulatedOpuDevice() else: # Instantiate device directly from lightonopu.internal.device import", "return torch.from_numpy(output) else: return output def _raw_linear_transform(self, X, traits=None, user_input=None):", "now use fit2d and transform\") def fit_transform1d(self, X, packed: bool", "# initialize linear_reconstruction library from lightonopu import linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi", "technology.\" if simulated and opu_device is not None: raise ValueError(\"simulated", "OPU in a simulated manner, by passing the \" \\", "= 1 self._debug(\"trigger issue detected, workaround applied\") else: self._debug(\"trigger issue", "Restore the dimension after batch encoding to something suitable for", "fit1d or fit2d before transform\" assert self.device.active, \"OPU device isn't", "ExitStack() # Restore online acquisition if it was the case", "to a physical or simulated device. If not provided, a", "encoder has get_params method, it's for transmitting it to decoder", "calling `fit1d` and then `transform`, or you might encounter an", "decoder_cls): \"\"\"Final steps after transform 1. reshape 2. decode the", "properly instantiated. If opu_device is of type SimulatedOpuDevice, the random", "self._max_n_features = max_n_features self.disable_pbar = disable_pbar self.rescale = rescale #", "be specified\" # tr_settings has no input_roi, since it uses", "**override): \"\"\"Internal working of the fitXd calls Instantiates a TransformRunner,", "= user_input.n_features_s output = output / (self._s.stdev * sqrt(n_features)) elif", "ContextArray(result, rp_opu.context) return rp_opu, result_ctx def __enter__(self): \"\"\"Context manager interface", "config_file self.__config_override = config_override self._max_n_features = max_n_features self.disable_pbar = disable_pbar", "int dimensionality of the target projection space. rescale: types.OutputRescaling, output", "optional for override of the config_file (for dev purpose) verbose_level:", "for overriding transform settings (advanced parameters) \"\"\" return self.__fit(X, n_features,", "self._trace(f\"Encoding time {time.time() - start} s\") # Restore the dimension", "in the transformation matrix. The input data can be bit-packed,", "batch of input vectors. Each vector must have the same", "is linked to the minimum output size min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0), ones_range=self.config[\"ones_range\"],", "transforms the output of the opu back into the appropriate", "module and may not be present if TYPE_CHECKING: from lightonopu.internal.device", "X=None, n_features: int = None, packed: bool = False, online=False,", "return self._s.max_n_features @max_n_features.setter def max_n_features(self, value: int): if not self._s.simulated:", "or you might encounter an inconsistency in the transformation matrix.", "else: # Decoding forgets about the context, re-add it to", "max_n_features and n_components max_n_features: int, optional maximum number of binary", "on this vector to optimize transform parameters n_features: int Number", "return self.device.open() # initial reservation for giving batch transforms a", ".. seealso:: `close()` or use the context manager interface for", "user_input = OpuUserInput.from_traits(X_enc, self._runner.traits) self._debug(str(user_input)) if user_input.is_batch and not self._s.simulated:", "fit1d(self, X=None, n_features: int = None, packed: bool = False,", "= X.shape[:-1]`` packed: bool, optional whether the input data is", "or SimulatedOpuDevice underlying hardware that performs transformation (read-only) input_roi_strategy: types.InputRoiStrategy,", "of features must be provided as n_features defaults to False", "self._runner.traits if traits.packed: # TODO implement for packed raise RuntimeError(\"Linear", "def n_components(self) -> int: return self._n_components @n_components.setter def n_components(self, value:", "negligible\"\"\" # Get default value pass_default = attr.fields(OpuSettings).n_samples_by_pass.default # Common", "from contextlib import ExitStack import attr import inspect import lightonml", "str it's the enum value if isinstance(value, str): self._rescale =", "np.ndarray or torch.Tensor a 1d input vector, or batch of", "= config_file self.__config_override = config_override self._max_n_features = max_n_features self.disable_pbar =", "making several transform calls, prefer calling `fit2d` and then `transform`,", "forgets about the context, re-add it to result afterwards start", "assert isinstance(self.device, SimulatedOpuDevice) rnd_mat = self.device.random_matrix if rnd_mat is None", "`linear_transform`, `fit1d` and `fit2d`, and accept NumPy arrays or PyTorch", "utils.detect_trigger_issue(self.device) if issue: # noinspection PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim = 1 self._debug(\"trigger", "get_params method, it's for transmitting it to decoder init if", "If another process or kernel has not released the resources,", "optional module and may not be present if TYPE_CHECKING: from", "projections of X, of size self.n_components If input is an", "open_at_init: bool = None, disable_pbar=False, simulated=False, rescale: Union[OutputRescaling, str] =", "available, it is used for progress display Parameters ---------- X:", "OpuSettings if not found n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), #", "X parameter isn't provided, or if input is bit-packed packed:", "configuration object\"\"\" # Load it when asked first time if", "from lightonml.internal.user_input import OpuUserInput, InputTraits from lightonml.internal.simulated_device import SimulatedOpuDevice from", "Don't close if OPU was already active if not self.__active_before_enter:", "parameters to it, or just vector dimensions, with `n_features`. When", "asked first time if not self.__opu_config: self.__opu_config = config.load_config(self.__config_file, self._trace)", "= OpuUserInput.from_traits(prepared_X, traits) start = time.time() with self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu =", "rp_opu = self._runner.transform(prepared_input, linear=True) self._trace(f\"Transform time {time.time() - start} s\")", "to False override: dict, optional keyword args for overriding transform", "int = None, packed: bool = False, online=False, **override): \"\"\"", "a context attribute to add metadata \"\"\" assert self._runner, \"Call", "\"\"\"Returns the internal configuration object\"\"\" # Load it when asked", "or SimulatedOpuDevice, optional optical processing unit instance linked to a", "open_at_init: self.open() def _tr_settings(self, no_input=False, **override) -> TransformSettings: \"\"\"Returns transform", "== InputRoiStrategy.full, \\ \"ROI strategy must be full for linear_transform", "number of binary features that the OPU will transform used", "used by the OPU device.\"\"\" self.__active_before_enter = self.device.active self.open() return", "-> TransformOutput: \"\"\" Performs the nonlinear random projections of one", "performs at a higher speed than `linear_transform`. Acquiring/releasing hardware device", "random matrix device: OpuDevice or SimulatedOpuDevice underlying hardware that performs", "= -1, input_roi_strategy: types.InputRoiStrategy = types.InputRoiStrategy.full, open_at_init: bool = None,", "self._output_roi.compute_roi(value) # We used to call device.reserve here, but moved", "else: verbose_level = lightonml.get_verbose_level() self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn()", "containing name and versions of the OPU\"\"\" version = []", "torch.Tensor Fit will be made on this vector to optimize", "then provided with `n_features` When input vectors must be transformed", "you might encounter an inconsistency in the transformation matrix. The", "\"frametime_us\": self._base_frametime_us, \"exposure_us\": self._base_exposure_us} if isinstance(self.device, SimulatedOpuDevice): # Notice we", "on the input device \"\"\" def __init__(self, n_components: int =", "inspect import lightonml from lightonml.internal.config import get_host_option, opu_version from lightonml.internal", "metadata \"\"\" self.fit2d(X, n_2d_features, packed, False, **override) return self.transform(X) def", "SimulatedOpuDevice from lightonml.context import ContextArray from lightonml.internal.settings import OpuSettings, TransformSettings", "(read-only) input_roi_strategy: types.InputRoiStrategy, optional describes how to display the features", "linear_transform to be correct.\\n\" \\ \"Set input_roi_strategy attribute to InputRoiStrategy.full.\"", "sure lightonopu is at 1.4.1 or later, needed for linear_reconstruction", "the decoding step if self.rescale is OutputRescaling.variance: n_features = user_input.n_features_s", "issue: # noinspection PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim = 1 self._debug(\"trigger issue detected,", "optional whether the input data is in bit-packed representation defaults", "given in `fit1d` or `fit2d`. encoder_cls: encoding.base.BaseTransformer, optional class or", "part of this source code package. \"\"\" This module contains", "you must now use fit2d and transform\") def fit_transform1d(self, X,", "the OPU will transform used only if opu_device is a", "self._runner.transform(user_input) return self._post_transform(out, user_input, encoder, decoder_cls) def linear_transform(self, X, encoder_cls=NoEncoding,", "to be correct.\\n\" \\ \"Set input_roi_strategy attribute to InputRoiStrategy.full.\" #", "the OPU. .. math:: \\\\mathbf{y} = \\\\lvert \\\\mathbf{R} \\\\mathbf{x} \\\\rvert^2", "self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn() self._acq_stack", "self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn() no_config_msg", "input is bit-packed packed: bool, optional whether the input data", "hardware device resources is done by open/close and a context-manager", "else: # Instantiate device directly from lightonopu.internal.device import OpuDevice if", "\"\"\" Configure OPU transform for 1d vectors The function can", "TransformOutput: \"\"\" Performs the nonlinear random projections of one or", "machine.\\n\" \\ \"You may want to run the OPU in", "user_input, encoder, decoder_cls) # Rescale the output, intentionally after the", "is bit-packed packed: bool, optional whether the input data is", "@property def max_n_features(self) -> int: return self._s.max_n_features @max_n_features.setter def max_n_features(self,", "file is subject to the terms and conditions defined in", "if not self._s.simulated: raise AttributeError(\"max_n_feature can't be set if device", "TransformRunner\"\"\" init = TransformSettings(self.input_roi_strategy, self.n_components) settings = attr.evolve(init, **override) if", "step if self.rescale is OutputRescaling.variance: n_features = user_input.n_features_s output =", "input device .. seealso:: `lightonml.internal.types.InputRoiStrategy` open_at_init: bool, optional forces the", "self._s.simulated: # build the random matrix if not done already", "when asked first time if not self.__opu_config: self.__opu_config = config.load_config(self.__config_file,", "of type SimulatedOpuDevice, the random matrix is generated at __init__,", "maximum number of binary features that the OPU will transform", "`fit1d` and `transform` calls. .. warning:: when making several transform", "self.device.output_roi = self._output_roi.compute_roi(value) # We used to call device.reserve here,", "input is bit-packed, specifies the shape of each input vector.", "def fit_transform1d(self, X, packed: bool = False, **override) -> ContextArray:", "add metadata \"\"\" self.fit2d(X, n_2d_features, packed, False, **override) return self.transform(X)", "array, and the \"real\" number of features must be provided", "= rescale # Get trace and print functions if verbose_level", "*args, **kwargs): raise RuntimeError(\"transform1d is deprecated, you must now use", "1000, config_file: str = \"\", config_override: dict = None, verbose_level:", "isinstance(self.device, SimulatedOpuDevice): # Notice we never query self.config here, in", "str): self._rescale = OutputRescaling[value.lower()] else: assert isinstance(value, OutputRescaling) self._rescale =", "the OPU object to release it. Parameters ---------- n_components :", "from typing import Optional, Union, Tuple, TYPE_CHECKING import numpy as", "the nonlinear random projections of 2d input vector(s). This function", "the other defaults to False override: dict, optional keyword args", "state): self.__dict__.update(state) # Restore logging functions removed at getstate self._debug", "lightonopu only for typechecking, as it's an optional module and", "OPU is available on your machine the random matrix is", "or just vector dimensions, with ``n_features``. When input is bit-packed", "ContextArray, with a context attribute to add metadata \"\"\" self.fit2d(X,", "= disable_pbar self.rescale = rescale # Get trace and print", "fit2d before transform\" assert self.device.active, \"OPU device isn't active, use", "manager interface that acquires hardware resources used by the OPU", "self._print(\"OK\") def version(self, devices=False): \"\"\"Returns a multi-line string containing name", "Load it when asked first time if not self.__opu_config: self.__opu_config", "when making several transform calls, prefer calling `fit1d` and then", "\"Set input_roi_strategy attribute to InputRoiStrategy.full.\" # X2 is now numpy", "for the input, necessary if X parameter isn't provided packed:", "OutputRescaling.variance): self.__opu_config = None self.__config_file = config_file self.__config_override = config_override", "Restore online acquisition if it was the case if state.get(\"__online_acq\",", "self._trace(f\"Transform time {time.time() - start} s\") if self._s.simulated: result_ctx =", "or 2d. In all cases ``output.shape[:-1] = X.shape[:-1]`` packed: bool,", "traits) _, result_ctx = self._raw_linear_transform(X_enc, traits, user_input) # Decoding, add", "already active if not self.__active_before_enter: self.close() def open(self): \"\"\"Acquires hardware", "must be set to True. Number of features must be", "vector after the other defaults to False override: dict, optional", "warnings from typing import Optional, Union, Tuple, TYPE_CHECKING import numpy", "OPU. .. math:: \\\\mathbf{y} = \\\\lvert \\\\mathbf{R} \\\\mathbf{x} \\\\rvert^2 \\\\mbox{", "acquisition first assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't transform a", "int maximum number of binary features that the OPU will", "packed, online, True, **override) def transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) ->", "input vectors. The `fit1d` or `fit2d` method must be called", "\"either input vector or n_features must be specified\" # tr_settings", "self.config[\"output\"][\"exposure_us\"] seq_nb_prelim = self.config.get(\"sequence_nb_prelim\", 0) name = self.config[\"name\"] self.device =", "for progress display Parameters ---------- X: np.ndarray or torch.Tensor a", "= lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn() no_config_msg =", "# Notice we never query self.config here, in order not", "ExitStack() self._trace(\"OPU initialized\") # Open at init, unless relevant host.json", "order not to # need a configuration file for simulated", "no OPU on this host as we didn't find configuration", "interface. Unless `open_at_init=False`, these resources are acquired automatically at init.", "Start acquisition only if online. Batch transform start their own.", "= ContextArray(result, rp_opu.context) return rp_opu, result_ctx def __enter__(self): \"\"\"Context manager", "\"OpuDevice\"]: raise TypeError(\"opu_device must be of type SimulatedOpuDevice or OpuDevice\")", "n_components: int = 200000, opu_device: Optional[Union[\"OpuDevice\", SimulatedOpuDevice]] = None, max_n_features:", "# file 'LICENSE.txt', which is part of this source code", "be made one vector after the other defaults to False", "**override) -> ContextArray: \"\"\"Performs the nonlinear random projections of 2d", "bool Set to true if the input vectors will be", "n_features, \"either input vector or n_features must be specified\" #", "X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, traits) _, result_ctx =", "by `transform`. max_n_features: int maximum number of binary features that", "# Make sure lightonopu is at 1.4.1 or later, needed", "return '\\n'.join(version) def __getstate__(self): state = self.__dict__.copy() # Remove logging", "is\" \\ \" in online mode, only single vectors\" assert", "for formatting prepared_X = user_input.unravel_features(prepared_X) # Run the OPU transform", "to TransformRunner\"\"\" init = TransformSettings(self.input_roi_strategy, self.n_components) settings = attr.evolve(init, **override)", "this source code package. \"\"\" This module contains the OPU", "a multi-line string containing name and versions of the OPU\"\"\"", "defaults to False online: bool, optional Set to true if", "or \\\"with opu:\\\"\" if inspect.isclass(encoder_cls): encoder = encoder_cls() else: encoder", "is actually ContextArray, with a context attribute to add metadata", "encoder = encoder_cls X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, traits)", "**override) if no_input and self.input_roi_strategy is InputRoiStrategy.auto: # If no", "decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Do a linear transform of X,", "def linear_transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Do a", "return output def transform1d(self, *args, **kwargs): raise RuntimeError(\"transform1d is deprecated,", "IntOrTuple, TransformOutput, AcqState from lightonml.types import OutputRescaling # Import lightonopu", "settings to both simulated and base kwargs = {\"input_shape\": self.device.input_shape,", "else: assert isinstance(value, OutputRescaling) self._rescale = value @property def max_n_components(self):", "given in `fit1d` or `fit2d`. encoder_cls: encoder.base.BaseTransformer, optional class or", "isinstance(value, OutputRescaling) self._rescale = value @property def max_n_components(self): return self._output_roi.max_components", "state def __setstate__(self, state): self.__dict__.update(state) # Restore logging functions removed", "add context, and optional convert back to torch if needed", "rp_opu.context) return rp_opu, result_ctx def __enter__(self): \"\"\"Context manager interface that", "Tuple, TYPE_CHECKING import numpy as np from contextlib import ExitStack", "be full for linear_transform to be correct.\\n\" \\ \"Set input_roi_strategy", "\"for more details.\\n\" \\ \"See also https://lighton.ai/products for getting access", "verbose_level, name) self._base_frametime_us = self.device.frametime_us self._base_exposure_us = self.device.exposure_us if self._s.simulated:", "vectors to be processed by the opu. decoder_cls: encoding.base.BaseTransformer, optional", "Nitro (non-linear) photonic cores. Parameters ---------- X: np.ndarray or torch.Tensor", "return state def __setstate__(self, state): self.__dict__.update(state) # Restore logging functions", "enum value if isinstance(value, str): self._rescale = OutputRescaling[value.lower()] else: assert", "user_input, device=self.device, disable_pbar=self.disable_pbar) else: # Only dimensions are provided, no", "return self._post_transform(out, user_input, encoder, decoder_cls) def linear_transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding)", "do linear transform when acquisition is\" \\ \" in online", "-> int: return self._n_components @n_components.setter def n_components(self, value: int): if", "improved with the online flag set to True. Parameters ----------", "the input data is in bit-packed representation defaults to False", "OpuSettings( max_n_features=int(np.prod(self.device.input_shape)), # Will use defaults of OpuSettings if not", "binary vectors to be processed by the opu. decoder_cls: encoding.base.BaseTransformer,", "features on the input device .. seealso:: `lightonml.internal.types.InputRoiStrategy` open_at_init: bool,", "devices: version.append(self.device.versions()) return '\\n'.join(version) def __getstate__(self): state = self.__dict__.copy() #", "max_n_components(self): return self._output_roi.max_components @property def n_components(self) -> int: return self._n_components", "if self._s.simulated: # build the random matrix if not done", "giving batch transforms a buffer ready to use self.device.reserve(self._s.n_samples_by_pass) if", "`fit2d` and `transform` calls. .. warning:: when making several transform", "encoder.base.BaseTransformer, optional class or instance of class that transforms the", "bool = False, **override) -> ContextArray: \"\"\"Performs the nonlinear random", "OutputRescaling[value.lower()] else: assert isinstance(value, OutputRescaling) self._rescale = value @property def", "output size min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0), ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\", 5), detect_trigger=self.config.get(\"detect_trigger_issue\", False), no_single_transform=self.config.get(\"no_single_transform\",", "open_at_init is None: open_at_init = get_host_option(\"lightonml_open_at_init\", True) if open_at_init: self.open()", "impact is negligible\"\"\" # Get default value pass_default = attr.fields(OpuSettings).n_samples_by_pass.default", "n_features) tr_settings = self._tr_settings(no_input=False, **override) self._runner = FitTransformRunner(self._s, tr_settings, user_input,", "rnd_mat.shape != (n_features, n_components): self._print(\"OPU: computing the random matrix... \",", "strategy must be full for linear_transform to be correct.\\n\" \\", "Looks like there's no OPU on this host as we", "---------- X: np.ndarray or torch.Tensor input vector, or batch of", "fit1d or fit2d before linear_transform\" traits = self._runner.traits if user_input", "= get_host_option(\"lightonml_open_at_init\", True) if open_at_init: self.open() def _tr_settings(self, no_input=False, **override)", "**override) -> TransformSettings: \"\"\"Returns transform settings for feeding to TransformRunner\"\"\"", "True. Parameters ---------- X: np.ndarray or torch.Tensor Fit will be", "the target projection space. rescale: types.OutputRescaling, output rescaling method for", "not done already self._resize_rnd_matrix(max_n_features, n_components) else: # Make sure lightonopu", "= output / (self._s.stdev * sqrt(self.n_components)) return output def transform1d(self,", "shape of each input vector. Not needed if the input", "are immutable (attrs frozen), so generate it at each call.", "transform used only if opu_device is a SimulatedOpuDevice, in order", "with `n_features` When input vectors must be transformed one by", "features must be provided as n_features defaults to False online:", "will removed in 1.3, \" \"Use lightonml.set_verbose_level instead\", DeprecationWarning) lightonml.set_verbose_level(verbose_level)", "Ignored by `transform`. .. seealso:: `lightonml.types.OutputRescaling` Attributes ---------- n_components: int", "of `fit2d` and `transform` calls. .. warning:: when making several", "sets the output ROI self.n_components = n_components self.input_roi_strategy = input_roi_strategy", "time {time.time() - start} s\") # Restore the dimension after", "set to True. Parameters ---------- X: np.ndarray or torch.Tensor a", "isn't yet implemented for packed input :/\") if inspect.isclass(encoder_cls): encoder", "input, necessary if X parameter isn't provided, or if input", "decoder_cls) # Rescale the output, intentionally after the decoding step", "can't be pickled, will be restored state.pop(\"_acq_stack\") # If acquisition", "verbose_level = lightonml.get_verbose_level() self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print", "transform 1. reshape 2. decode the output 3. convert to", "it if not self._s.simulated: state[\"__online_acq\"] = self.device.acq_state.value == AcqState.online.value self._acq_stack.close()", "take action if needed issue = utils.detect_trigger_issue(self.device) if issue: #", "code package. \"\"\" This module contains the OPU class \"\"\"", "disable display of the progress bar when verbose_level is set", "not be present if TYPE_CHECKING: from lightonopu.internal.device import OpuDevice #", "for device acquisition, initialized when entering fit self._acq_stack = ExitStack()", "transform\") def fit_transform1d(self, X, packed: bool = False, **override) ->", "ImportError: raise RuntimeError(\"Need a lightonopu version with linear_reconstruction module\") start", "_post_transform(output, user_input, encoder, decoder_cls): \"\"\"Final steps after transform 1. reshape", "the input isn't bit-packed. override: keyword args for overriding transform", "else: return output def _raw_linear_transform(self, X, traits=None, user_input=None): \"\"\" Do", "https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \" \\ \"for more details.\\n\" \\ \"See also https://lighton.ai/products", "by full strategy settings.input_roi_strategy = InputRoiStrategy.full assert settings.input_roi is None", "want to run the OPU in a simulated manner, by", "# Common settings to both simulated and base kwargs =", "used to call device.reserve here, but moved to device.acquiring() self._n_components", "self.input_roi_strategy is InputRoiStrategy.auto: # If no input_roi, replace auto by", "or `fit2d` method must be called before, for setting vector", "`transform`, or you might encounter an inconsistency in the transformation", "packed, False, **override) return self.transform(X) def fit_transform2d(self, X, packed: bool", "from lightonml.internal import config, output_roi, utils, types from lightonml.internal.user_input import", "n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), # min_n_components is linked to", "# Start acquisition only if online. Batch transform start their", "and decoded output in a tuple \"\"\" if traits is", "exposure_us = self.config[\"output\"][\"exposure_us\"] seq_nb_prelim = self.config.get(\"sequence_nb_prelim\", 0) name = self.config[\"name\"]", "self.rescale is OutputRescaling.variance: n_features = user_input.n_features_s output = output /", "are provided, no fitting happens on input assert n_features, \"either", "# Looks like there's no OPU on this host as", "`n_features` When input vectors must be transformed one by one,", "but moved to device.acquiring() self._n_components = value @property def max_n_features(self)", "---------- X: np.ndarray or torch.Tensor a 2d input vector, or", "associated with the OPU Settings are immutable (attrs frozen), so", "\\ \"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \" \\ \"for more details.\\n\" \\ \"See", "contextlib import ExitStack import attr import inspect import lightonml from", "to be processed by the opu. decoder_cls: encoder.base.BaseTransformer, optional class", "encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, self._runner.traits) self._debug(str(user_input)) if user_input.is_batch and not", "dimension after batch encoding to something suitable for formatting prepared_X", "OutputRescaling) self._rescale = value @property def max_n_components(self): return self._output_roi.max_components @property", "\"\"\"Performs the nonlinear random projections of 2d input vector(s). This", "\"\"\"Returns transform settings for feeding to TransformRunner\"\"\" init = TransformSettings(self.input_roi_strategy,", "self.config.get(\"sequence_nb_prelim\", 0) name = self.config[\"name\"] self.device = OpuDevice(opu_type, frametime_us, exposure_us,", "encoder_cls: encoding.base.BaseTransformer, optional class or instance of class that transform", "{time.time() - start} s\") result_ctx = ContextArray(result, rp_opu.context) return rp_opu,", "base kwargs = {\"input_shape\": self.device.input_shape, \"output_max_shape\": self.device.output_shape_max, \"frametime_us\": self._base_frametime_us, \"exposure_us\":", "raise RuntimeError(\"Linear transform isn't yet implemented for packed input :/\")", "subject to the terms and conditions defined in # file", "\" \\ \"simulated argument to True at init.\\n\" \\ \"See", "fitting happens on input assert n_features, \"either input vector or", "False, **override) def fit2d(self, X=None, n_features: Tuple[int, int] = None,", "**override): \"\"\" Configure OPU transform for 1d vectors The function", "module contains the OPU class \"\"\" import time from math", "# initial reservation for giving batch transforms a buffer ready", "noinspection PyPep8Naming class OPU: \"\"\"Interface to the OPU. .. math::", "stdev=self.config[\"output\"].get(\"stdev\", 1.), **kwargs) def _resize_rnd_matrix(self, n_features: int, n_components: int): \"\"\"Resize", "closed on pickling return state def __setstate__(self, state): self.__dict__.update(state) #", "encounter an inconsistency in the transformation matrix. If tqdm module", "bool, optional performs the random projection using CPU, in case", "if inspect.isclass(encoder_cls): encoder = encoder_cls() else: encoder = encoder_cls X_enc", "to transform one vector after each other, add `online=True` in", "rescale(self, value): # If str it's the enum value if", "is then generated at __init__, using max_n_features and n_components rescale:", "binary encoded, packed or not n_features: tuple(int) Number of features", "max_n_features(self) -> int: return self._s.max_n_features @max_n_features.setter def max_n_features(self, value: int):", "to true if the input vectors will be already bit-packed", "matrix\"\"\" assert isinstance(self.device, SimulatedOpuDevice) rnd_mat = self.device.random_matrix if rnd_mat is", "self._s.simulated: self._resize_rnd_matrix(self.max_n_features, value) else: self.device.output_roi = self._output_roi.compute_roi(value) # We used", "result afterwards start = time.time() result = reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding time", "!= -1: warnings.warn(\"Verbose level arg will removed in 1.3, \"", "start = time.time() prepared_X = reconstruction.encode_batch(X2) self._trace(f\"Encoding time {time.time() -", "instead .. seealso:: `lightonml.set_verbose_level` input_roi_strategy: types.InputRoiStrategy, optional describes how to", "types.InputRoiStrategy.full, open_at_init: bool = None, disable_pbar=False, simulated=False, rescale: Union[OutputRescaling, str]", "must be called before, for setting vector dimensions or online", "import inspect import lightonml from lightonml.internal.config import get_host_option, opu_version from", ": OpuDevice or SimulatedOpuDevice, optional optical processing unit instance linked", "TODO implement for packed raise RuntimeError(\"Linear transform isn't yet implemented", "self.__active_before_enter = self.device.active self.open() return self def __exit__(self, *args): #", "\"OPU device isn't active, use opu.open() or \\\"with opu:\\\"\" if", "Runner initialized when entering fit self._runner = None # type:", "X2 = user_input.reshape_input(raveled_features=True, leave_single_dim=True) try: import lightonopu.linear_reconstruction as reconstruction except", "\"Call fit1d or fit2d before transform\" assert self.device.active, \"OPU device", "def _s(self) -> OpuSettings: \"\"\"Returns immutable settings associated with the", "defaults to False n_2d_features: list, tuple or np.ndarray of length", "\\ \"Can't do linear transform when acquisition is\" \\ \"", "be set if device is real\") self._resize_rnd_matrix(value, self._n_components) self._max_n_features =", "`transform`. max_n_features: int maximum number of binary features that the", "is deprecated, you must now use fit2d and transform\") def", "prepared_X = X else: assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't", "you need to transform one vector after each other, add", "of binary features that the OPU will transform writeable only", "before linear_transform\" traits = self._runner.traits if user_input is None: user_input", "is closed on pickling return state def __setstate__(self, state): self.__dict__.update(state)", "follow system's setting (usually True) disable_pbar: bool, optional disable display", "input vector is assumed to be a 1d array, and", "self.__fit(X, n_features, packed, online, True, **override) def transform(self, X, encoder_cls=NoEncoding,", "packed, online, False, **override) def fit2d(self, X=None, n_features: Tuple[int, int]", "return self.__opu_config @property def rescale(self): return self._rescale @rescale.setter def rescale(self,", "Optional[Union[\"OpuDevice\", SimulatedOpuDevice]] = None, max_n_features: int = 1000, config_file: str", "calls, prefer calling `fit1d` and then `transform`, or you might", "import lightonml from lightonml.internal.config import get_host_option, opu_version from lightonml.internal import", "setting (usually True) disable_pbar: bool, optional disable display of the", "at __init__, using max_n_features and n_components rescale: types.OutputRescaling, optional, output", "input vector, or batch of input vectors. Each vector must", "implement for packed raise RuntimeError(\"Linear transform isn't yet implemented for", "it when asked first time if not self.__opu_config: self.__opu_config =", "arg will removed in 1.3, \" \"Use lightonml.set_verbose_level instead\", DeprecationWarning)", "@rescale.setter def rescale(self, value): # If str it's the enum", "a 2d input vector, or batch of 2d input_vectors, binary", "from lightonml.context import ContextArray from lightonml.internal.settings import OpuSettings, TransformSettings from", "for transmitting it to decoder init if inspect.isclass(decoder_cls): if hasattr(encoder,", "the transformation matrix. The input data can be bit-packed, where", "defaults of OpuSettings if not found n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0),", "for fitting OPU parameters to it, or just vector dimensions,", "\"real\" number of features must be provided as n_2d_features defaults", "n_components(self) -> int: return self._n_components @n_components.setter def n_components(self, value: int):", "replace auto by full strategy settings.input_roi_strategy = InputRoiStrategy.full assert settings.input_roi", "whether the input data is in bit-packed representation if True,", "import OpuDevice # noinspection PyPep8Naming class OPU: \"\"\"Interface to the", "of acquiring hardware resource at init. If not provided, follow", "and base kwargs = {\"input_shape\": self.device.input_shape, \"output_max_shape\": self.device.output_shape_max, \"frametime_us\": self._base_frametime_us,", "= OutputRescaling.variance): self.__opu_config = None self.__config_file = config_file self.__config_override =", "generated at __init__, using max_n_features and n_components rescale: types.OutputRescaling, optional,", "OPU\") # Start acquisition only if online. Batch transform start", "if not self._s.simulated: version.append(opu_version(self.__opu_config)) # module version version.append(f\"lightonml version {lightonml.__version__}\")", "this vector to optimize transform parameters n_features: int Number of", "nonlinear random projections of 2d input vector(s). This function is", "input is bit-packed the packed flag must be set to", "`fit1d` or `fit2d`. encoder_cls: encoder.base.BaseTransformer, optional class or instance of", "encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, traits) _, result_ctx = self._raw_linear_transform(X_enc, traits,", "linear=True) self._trace(f\"Transform time {time.time() - start} s\") if self._s.simulated: result_ctx", "default value pass_default = attr.fields(OpuSettings).n_samples_by_pass.default # Common settings to both", "of X, of size self.n_components If input is an ndarray,", "2 If the input is bit-packed, specifies the shape of", "dict, optional keyword args for overriding transform settings (advanced parameters)", "prepared_input = OpuUserInput.from_traits(prepared_X, traits) start = time.time() with self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu", "and conditions defined in # file 'LICENSE.txt', which is part", "removed in 1.3, \" \"Use lightonml.set_verbose_level instead\", DeprecationWarning) lightonml.set_verbose_level(verbose_level) else:", "OPU on this host as we didn't find configuration files", "with linear_reconstruction module\") start = time.time() prepared_X = reconstruction.encode_batch(X2) self._trace(f\"Encoding", "\"output_max_shape\": self.device.output_shape_max, \"frametime_us\": self._base_frametime_us, \"exposure_us\": self._base_exposure_us} if isinstance(self.device, SimulatedOpuDevice): #", "import OpuDevice if not self.__config_file and not config.host_has_opu_config(): # Looks", "is assumed to be a 1d array, and the \"real\"", "self._rescale = value @property def max_n_components(self): return self._output_roi.max_components @property def", "to initiate the random matrix config_file : str, optional path", "contains the OPU class \"\"\" import time from math import", ".. math:: \\\\mathbf{y} = \\\\mathbf{R}\\\\mathbf{x} \\\\mbox{ (linear transform)} Main methods", ": str, optional path to the configuration file (for dev", "optional keyword args for overriding transform settings (advanced parameters) \"\"\"", "data is in bit-packed representation defaults to False override: keyword", "X, traits=None, user_input=None): \"\"\" Do linear_transform of X, and return", "**override) return self.transform(X) def fit_transform2d(self, X, packed: bool = False,", "to add metadata \"\"\" self.fit1d(X, None, packed, False, **override) return", "user_input = OpuUserInput.from_input(X, packed, is_2d_features, n_features) tr_settings = self._tr_settings(no_input=False, **override)", "opu_device : OpuDevice or SimulatedOpuDevice, optional optical processing unit instance", "at 1.4.1 or later, needed for linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\") # initialize", "configuration file for simulated device return OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default, simulated=True, **kwargs", "except ImportError: pass if devices: version.append(self.device.versions()) return '\\n'.join(version) def __getstate__(self):", "OutputRescaling # Import lightonopu only for typechecking, as it's an", "for the OPU was found on this machine.\\n\" \\ \"You", "class or instance of class that transform the input into", "vector is assumed to be a 1d array, and the", "import pkg_resources from lightonml.encoding.base import NoEncoding, NoDecoding import warnings from", "\"\"\" self.fit2d(X, n_2d_features, packed, False, **override) return self.transform(X) def __fit(self,", "= config.load_config(self.__config_file, self._trace) if self.__config_override is not None: utils.recurse_update(self.__opu_config, self.__config_override)", "= None, verbose_level: int = -1, input_roi_strategy: types.InputRoiStrategy = types.InputRoiStrategy.full,", "tr_settings, user_input, device=self.device, disable_pbar=self.disable_pbar) else: # Only dimensions are provided,", "@property def config(self): \"\"\"Returns the internal configuration object\"\"\" # Load", "output rescaling method for `linear_transform`. Ignored by `transform`. max_n_features: int", "input assert n_features, \"either input vector or n_features must be", "when entering fit self._runner = None # type: Optional[TransformRunner] #", "is subject to the terms and conditions defined in #", "value @property def _s(self) -> OpuSettings: \"\"\"Returns immutable settings associated", "encoder, decoder_cls) # Rescale the output, intentionally after the decoding", "number of features must be provided as n_2d_features defaults to", "the input is bit-packed, specifies the shape of each input", "the OPU class \"\"\" import time from math import sqrt", "af an indent block \"\"\" if self.device.active: return self.device.open() #", "self.__opu_config = config.load_config(self.__config_file, self._trace) if self.__config_override is not None: utils.recurse_update(self.__opu_config,", "isinstance(self.device, SimulatedOpuDevice) rnd_mat = self.device.random_matrix if rnd_mat is None or", "`fit2d` and then `transform`, or you might encounter an inconsistency", "\\ \"Set input_roi_strategy attribute to InputRoiStrategy.full.\" # X2 is now", "must now use fit1d and transform\") def transform2d(self, *args, **kwargs):", "1d input_vectors, binary encoded, packed or not batch can be", "n_components: int dimensionality of the target projection space. rescale: types.OutputRescaling,", "5), detect_trigger=self.config.get(\"detect_trigger_issue\", False), no_single_transform=self.config.get(\"no_single_transform\", False), stdev=self.config[\"output\"].get(\"stdev\", 1.), **kwargs) def _resize_rnd_matrix(self,", "be bit-packed, where ``n_features = 8*X.shape[-1]`` Otherwise ``n_features = X.shape[-1]``", "open/close and a context-manager interface. Unless `open_at_init=False`, these resources are", "@max_n_features.setter def max_n_features(self, value: int): if not self._s.simulated: raise AttributeError(\"max_n_feature", "Copyright (c) 2020 LightOn, All Rights Reserved. # This file", "context, and optional convert back to torch if needed output", "projection space. opu_device : OpuDevice or SimulatedOpuDevice, optional optical processing", "input vector(s). This function is the one-liner equivalent of `fit1d`", "random matrix config_file : str, optional path to the configuration", "true if the input vectors will be already bit-packed online:", "equivalent of `fit1d` and `transform` calls. .. warning:: when making", "automatically at init. If another process or kernel has not", "simulated and base kwargs = {\"input_shape\": self.device.input_shape, \"output_max_shape\": self.device.output_shape_max, \"frametime_us\":", "a SimulatedOpuDevice, in order to initiate or resize the random", "n_components(self, value: int): if self._s.simulated: self._resize_rnd_matrix(self.max_n_features, value) else: self.device.output_roi =", "0), ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\", 5), detect_trigger=self.config.get(\"detect_trigger_issue\", False), no_single_transform=self.config.get(\"no_single_transform\", False), stdev=self.config[\"output\"].get(\"stdev\", 1.),", "pickled, will be restored state.pop(\"_acq_stack\") # If acquisition is ongoing,", "deprecated, you must now use fit1d and transform\") def transform2d(self,", "import sqrt import pkg_resources from lightonml.encoding.base import NoEncoding, NoDecoding import", "output, intentionally after the decoding step if self.rescale is OutputRescaling.variance:", "is in bit-packed representation if True, each input vector is", "self.device = SimulatedOpuDevice() else: # Instantiate device directly from lightonopu.internal.device", "Configure OPU transform for 1d vectors The function can be", "X: np.ndarray or torch.Tensor a 1d input vector, or batch", "for the OPU, and performs at a higher speed than", "warning:: when making several transform calls, prefer calling `fit2d` and", "\\\\mathbf{x} \\\\rvert^2 \\\\mbox{ (non-linear transform, the default)} .. math:: \\\\mathbf{y}", "input_roi_strategy: types.InputRoiStrategy = types.InputRoiStrategy.full, open_at_init: bool = None, disable_pbar=False, simulated=False,", "bit-packed online: bool, optional Set to true if the transforms", "or later, needed for linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\") # initialize linear_reconstruction library", "return self.transform(X) def fit_transform2d(self, X, packed: bool = False, n_2d_features=None,", "like there's no OPU on this host as we didn't", "space. opu_device : OpuDevice or SimulatedOpuDevice, optional optical processing unit", "self.transform(X) def __fit(self, X, n_features: IntOrTuple, packed: bool, online: bool,", "for `linear_transform`. Ignored by `transform`. max_n_features: int maximum number of", "function can be either called with input vector, for fitting", "lightonml.get_trace_fn() self._print = lightonml.get_print_fn() no_config_msg = \"No configuration files for", ".. seealso:: `lightonml.types.OutputRescaling` Attributes ---------- n_components: int dimensionality of the", "def transform1d(self, *args, **kwargs): raise RuntimeError(\"transform1d is deprecated, you must", "False, n_2d_features=None, **override) -> ContextArray: \"\"\"Performs the nonlinear random projections", "None, disable_pbar=False, simulated=False, rescale: Union[OutputRescaling, str] = OutputRescaling.variance): self.__opu_config =", "only single vectors\" with self.device.acquiring(n_images=self._s.n_samples_by_pass): out = self._runner.transform(user_input) else: out", "\"\"\"Acquires hardware resources used by the OPU device .. seealso::", "self._resize_rnd_matrix(self.max_n_features, value) else: self.device.output_roi = self._output_roi.compute_roi(value) # We used to", "to add metadata \"\"\" assert self._runner, \"Call fit1d or fit2d", "bool, online: bool, is_2d_features: bool, **override): \"\"\"Internal working of the", "can be either called with input vector, for fitting OPU", "rp_opu, result_ctx def __enter__(self): \"\"\"Context manager interface that acquires hardware", "resources used by the OPU device .. seealso:: `close()` or", "# Restore logging functions removed at getstate self._debug = lightonml.get_debug_fn()", "= self.config[\"name\"] self.device = OpuDevice(opu_type, frametime_us, exposure_us, seq_nb_prelim, None, verbose_level,", "start} s\") result_ctx = ContextArray(result, rp_opu.context) return rp_opu, result_ctx def", "use fit2d and transform\") def fit_transform1d(self, X, packed: bool =", "used by the OPU device .. seealso:: `close()` or use", "describes how to display the features on the input device", "init = TransformSettings(self.input_roi_strategy, self.n_components) settings = attr.evolve(init, **override) if no_input", "resource at init. If not provided, follow system's setting (usually", "need to transform one vector after each other, add `online=True`", "False, online=False, **override): \"\"\" Configure OPU transform for 1d vectors", "vector(s). This function is the one-liner equivalent of `fit2d` and", "self.fit1d(X, None, packed, False, **override) return self.transform(X) def fit_transform2d(self, X,", "transform one vector after each other, add `online=True` in the", "if self._s.simulated: result_ctx = rp_opu else: # Decoding forgets about", "return rp_opu, result_ctx def __enter__(self): \"\"\"Context manager interface that acquires", "rescale(self): return self._rescale @rescale.setter def rescale(self, value): # If str", "Make sure lightonopu is at 1.4.1 or later, needed for", "simulated device. If not provided, a device is properly instantiated.", "lightonml.internal.settings import OpuSettings, TransformSettings from lightonml.internal.runner import TransformRunner, FitTransformRunner from", "calls Instantiates a TransformRunner, and start online acq if needs", "sqrt import pkg_resources from lightonml.encoding.base import NoEncoding, NoDecoding import warnings", "must be specified\" # tr_settings has no input_roi, since it", "the transforms will be made one vector after the other", "isn't available with this OPU\") # Start acquisition only if", "not self._s.simulated: state[\"__online_acq\"] = self.device.acq_state.value == AcqState.online.value self._acq_stack.close() # Device", "how to display the features on the input device \"\"\"", "version.append(f\"lightonml version {lightonml.__version__}\") try: # noinspection PyUnresolvedReferences import lightonopu version.append(f\"lightonopu", "to torch if needed output = self._post_transform(result_ctx, user_input, encoder, decoder_cls)", "`open_at_init=False`, these resources are acquired automatically at init. If another", "import numpy as np from contextlib import ExitStack import attr", "OpuDevice\") self.device = opu_device elif simulated: self.device = SimulatedOpuDevice() else:", "self.n_components) settings = attr.evolve(init, **override) if no_input and self.input_roi_strategy is", "numpy 2D, whatever the initial shape and the type (torch", "not provided, a device is properly instantiated. If opu_device is", "in # file 'LICENSE.txt', which is part of this source", "traits=None, user_input=None): \"\"\" Do linear_transform of X, and return both", "lightonml.internal.runner import TransformRunner, FitTransformRunner from lightonml.internal.types import InputRoiStrategy, IntOrTuple, TransformOutput,", "[\"SimulatedOpuDevice\", \"OpuDevice\"]: raise TypeError(\"opu_device must be of type SimulatedOpuDevice or", "photonic cores. Parameters ---------- X: np.ndarray or torch.Tensor input vector,", "dict = None, verbose_level: int = -1, input_roi_strategy: types.InputRoiStrategy =", "assert self._runner.t.input_roi_strategy == InputRoiStrategy.full, \\ \"ROI strategy must be full", "immutable (attrs frozen), so generate it at each call. Performance", "OPU Settings are immutable (attrs frozen), so generate it at", "input data is in bit-packed representation if True, each input", "or simulated device. If not provided, a device is properly", "option. If you need to transform one vector after each", "call device.reserve here, but moved to device.acquiring() self._n_components = value", "RuntimeError(\"transform2d is deprecated, you must now use fit2d and transform\")", "Device itself is closed on pickling return state def __setstate__(self,", "action if needed issue = utils.detect_trigger_issue(self.device) if issue: # noinspection", "None: user_input = OpuUserInput.from_traits(X, traits) if self._s.simulated: prepared_X = X", "InputRoiStrategy, IntOrTuple, TransformOutput, AcqState from lightonml.types import OutputRescaling # Import", "import time from math import sqrt import pkg_resources from lightonml.encoding.base", "block \"\"\" if self.device.active: return self.device.open() # initial reservation for", "OpuUserInput.from_traits(X_enc, traits) _, result_ctx = self._raw_linear_transform(X_enc, traits, user_input) # Decoding,", "initialize linear_reconstruction library from lightonopu import linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi =", "process or kernel has not released the resources, an error", "and opu_device arguments are conflicting\") # Device init, or take", "linear_reconstruction module\") start = time.time() prepared_X = reconstruction.encode_batch(X2) self._trace(f\"Encoding time", "Notice we never query self.config here, in order not to", "Import lightonopu only for typechecking, as it's an optional module", "= value @property def max_n_components(self): return self._output_roi.max_components @property def n_components(self)", "disable_pbar: bool, optional disable display of the progress bar when", "__init__, using max_n_features and n_components rescale: types.OutputRescaling, optional, output rescaling", "by the opu. decoder_cls: encoding.base.BaseTransformer, optional class or instance of", "# Restore the dimension after batch encoding to something suitable", "Detect trigger issue, and take action if needed issue =", "``output.shape[:-1] = X.shape[:-1]`` packed: bool, optional whether the input data", "batch input start acquisition first assert self.device.acq_state.value != AcqState.online.value, \\", "and then `transform`, or you might encounter an inconsistency in", "Performance impact is negligible\"\"\" # Get default value pass_default =", "config(self): \"\"\"Returns the internal configuration object\"\"\" # Load it when", "math:: \\\\mathbf{y} = \\\\mathbf{R}\\\\mathbf{x} \\\\mbox{ (linear transform)} Main methods are", "return self.__fit(X, n_features, packed, online, True, **override) def transform(self, X,", "True at init.\\n\" \\ \"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \" \\ \"for more", "= encoder_cls X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, self._runner.traits) self._debug(str(user_input))", "device resources is done by open/close and a context-manager interface.", "= decoder_cls() else: decoder = decoder_cls output = decoder.transform(output) if", "if self._s.simulated: self._resize_rnd_matrix(self.max_n_features, value) else: self.device.output_roi = self._output_roi.compute_roi(value) # We", "only if opu_device is a SimulatedOpuDevice, in order to initiate", "self._runner.transform(prepared_input, linear=True) self._trace(f\"Transform time {time.time() - start} s\") if self._s.simulated:", "back to torch if needed output = self._post_transform(result_ctx, user_input, encoder,", "config_override self._max_n_features = max_n_features self.disable_pbar = disable_pbar self.rescale = rescale", "bool, **override): \"\"\"Internal working of the fitXd calls Instantiates a", "= self.config[\"input\"][\"frametime_us\"] exposure_us = self.config[\"output\"][\"exposure_us\"] seq_nb_prelim = self.config.get(\"sequence_nb_prelim\", 0) name", "# If encoder has get_params method, it's for transmitting it", "`fit1d` and `fit2d`, and accept NumPy arrays or PyTorch tensors.", "to something suitable for formatting prepared_X = user_input.unravel_features(prepared_X) # Run", "batch transforms a buffer ready to use self.device.reserve(self._s.n_samples_by_pass) if self._s.detect_trigger:", "in case no OPU is available on your machine the", "min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), # min_n_components is linked to the minimum", "lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn() no_config_msg = \"No", "is a SimulatedOpuDevice, in order to initiate or resize the", "attr import inspect import lightonml from lightonml.internal.config import get_host_option, opu_version", "1d input vector, or batch of 1d input_vectors, binary encoded,", "raise RuntimeError(no_config_msg) opu_type = self.config[\"type\"] frametime_us = self.config[\"input\"][\"frametime_us\"] exposure_us =", "higher speed than `linear_transform`. Acquiring/releasing hardware device resources is done", "CPU, in case no OPU is available on your machine", "from lightonml.types import OutputRescaling # Import lightonopu only for typechecking,", "or shutdown the kernel on the OPU object to release", "= output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy, self._s.allowed_roi, self._s.min_n_components) # This also sets the", "is real\") self._resize_rnd_matrix(value, self._n_components) self._max_n_features = value @property def _s(self)", "generated at __init__, using max_n_features and n_components max_n_features: int, optional", "self._base_frametime_us = self.device.frametime_us self._base_exposure_us = self.device.exposure_us if self._s.simulated: # build", "multi-line string containing name and versions of the OPU\"\"\" version", "`fit1d` and then `transform`, or you might encounter an inconsistency", "with a context attribute to add metadata \"\"\" assert self._runner,", "batch encoding to something suitable for formatting prepared_X = user_input.unravel_features(prepared_X)", "raised, call `close()` or shutdown the kernel on the OPU", "passed as input if opu_device: if type(opu_device).__name__ not in [\"SimulatedOpuDevice\",", "NumPy arrays or PyTorch tensors. The non-linear transform (`transform`) is", "is a native operation for the OPU, and performs at", "the enum value if isinstance(value, str): self._rescale = OutputRescaling[value.lower()] else:", "versions of the OPU\"\"\" version = [] # Build OPU", "convert to tensor if user input was tensor \"\"\" output", "is generated at __init__, using max_n_features and n_components max_n_features: int,", "if open_at_init: self.open() def _tr_settings(self, no_input=False, **override) -> TransformSettings: \"\"\"Returns", "tr_settings = self._tr_settings(no_input=False, **override) self._runner = FitTransformRunner(self._s, tr_settings, user_input, device=self.device,", "of nonlinear random projections of X, of size self.n_components If", "self._runner = TransformRunner(self._s, tr_settings, traits, device=self.device, disable_pbar=self.disable_pbar) self._acq_stack.close() if online:", "import OpuUserInput, InputTraits from lightonml.internal.simulated_device import SimulatedOpuDevice from lightonml.context import", "whatever the initial shape and the type (torch or numpy)", "import NoEncoding, NoDecoding import warnings from typing import Optional, Union,", "if OPU was already active if not self.__active_before_enter: self.close() def", "int = 1000, config_file: str = \"\", config_override: dict =", "This file is subject to the terms and conditions defined", "representation defaults to False override: keyword args for overriding transform", "else: decoder = decoder_cls output = decoder.transform(output) if user_input.is_tensor: #", "X, of size self.n_components If input is an ndarray, type", "- start} s\") # Restore the dimension after batch encoding", "input device \"\"\" def __init__(self, n_components: int = 200000, opu_device:", "fitting OPU parameters to it, or just vector dimensions, with", "all cases ``output.shape[:-1] = X.shape[:-1]`` packed: bool, optional whether the", "return OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default, simulated=True, **kwargs ) return OpuSettings( max_n_features=int(np.prod(self.device.input_shape)), #", "# If acquisition is ongoing, close it if not self._s.simulated:", "projections of 2d input vector(s). This function is the one-liner", "underlying hardware that performs transformation (read-only) input_roi_strategy: types.InputRoiStrategy, optional describes", "when making several transform calls, prefer calling `fit2d` and then", "user_input.is_batch and not self._s.simulated: # With batch input start acquisition", "using max_n_features and n_components rescale: types.OutputRescaling, optional, output rescaling method", "import lightonopu version.append(f\"lightonopu version {lightonopu.__version__}\") except ImportError: pass if devices:", "run the OPU in a simulated manner, by passing the", "self.n_components If input is an ndarray, type is actually ContextArray,", "acquiring hardware resource at init. If not provided, follow system's", "when verbose_level is set to 1 simulated: bool, optional performs", "of 2d input_vectors, binary encoded, packed or not packed: bool,", "tensors. The non-linear transform (`transform`) is a native operation for", "used for progress display Parameters ---------- X: np.ndarray or torch.Tensor", "__getstate__(self): state = self.__dict__.copy() # Remove logging functions, they can't", "features for the input, necessary if X parameter isn't provided,", "optional disable display of the progress bar when verbose_level is", "raise RuntimeError(\"transform2d is deprecated, you must now use fit2d and", "None, max_n_features: int = 1000, config_file: str = \"\", config_override:", "assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't do linear transform when", "OPU transform for 1d vectors The function can be either", "`fit1d` or `fit2d` method must be called before, for setting", "\\ \"for more details.\\n\" \\ \"See also https://lighton.ai/products for getting", "later, needed for linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\") # initialize linear_reconstruction library from", "optional convert back to torch if needed output = self._post_transform(result_ctx,", "self._runner.t.input_roi_strategy == InputRoiStrategy.full, \\ \"ROI strategy must be full for", "self._debug(\"trigger issue detected, workaround applied\") else: self._debug(\"trigger issue not detected\")", "Parameters ---------- n_components : int, dimensionality of the target projection", "is not None: raise ValueError(\"simulated and opu_device arguments are conflicting\")", "Set to true if the transforms will be made one", "value): # If str it's the enum value if isinstance(value,", "the \" \\ \"simulated argument to True at init.\\n\" \\", "if opu_device is a SimulatedOpuDevice, in order to initiate the", "or just vector dimensions, with `n_features`. When input is bit-packed", "to both simulated and base kwargs = {\"input_shape\": self.device.input_shape, \"output_max_shape\":", "lightonml.set_verbose_level() instead .. seealso:: `lightonml.set_verbose_level` input_roi_strategy: types.InputRoiStrategy, optional describes how", "packed: bool = False, online=False, **override): \"\"\" Configure OPU transform", "linked to a physical or simulated device. If not provided,", "device isn't active, use opu.open() or \\\"with opu:\\\"\" if inspect.isclass(encoder_cls):", "typechecking, as it's an optional module and may not be", "class \"\"\" import time from math import sqrt import pkg_resources", "Attributes ---------- n_components: int dimensionality of the target projection space.", "import config, output_roi, utils, types from lightonml.internal.user_input import OpuUserInput, InputTraits", "where ``n_features = 8*X.shape[-1]`` Otherwise ``n_features = X.shape[-1]`` If tqdm", "optional whether the input data is in bit-packed representation if", "needed issue = utils.detect_trigger_issue(self.device) if issue: # noinspection PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim", "just vector dimensions, with `n_features`. When input is bit-packed the", "fit self._acq_stack = ExitStack() self._trace(\"OPU initialized\") # Open at init,", "= output / (self._s.stdev * sqrt(n_features)) elif self.rescale is OutputRescaling.norm:", "**override) -> ContextArray: \"\"\"Performs the nonlinear random projections of 1d", "open_at_init: bool, optional forces the setting of acquiring hardware resource", "for feeding to TransformRunner\"\"\" init = TransformSettings(self.input_roi_strategy, self.n_components) settings =", "= decoder.transform(output) if user_input.is_tensor: # noinspection PyPackageRequirements,PyUnresolvedReferences import torch return", "fitXd calls Instantiates a TransformRunner, and start online acq if", "import warnings from typing import Optional, Union, Tuple, TYPE_CHECKING import", "\\\"with opu:\\\"\" if inspect.isclass(encoder_cls): encoder = encoder_cls() else: encoder =", "version = [] # Build OPU name if not self._s.simulated:", "device acquisition, initialized when entering fit self._acq_stack = ExitStack() self._trace(\"OPU", "verbose_level: int = -1, input_roi_strategy: types.InputRoiStrategy = types.InputRoiStrategy.full, open_at_init: bool", "done already self._resize_rnd_matrix(max_n_features, n_components) else: # Make sure lightonopu is", "after the other defaults to False override: dict, optional keyword", "if TYPE_CHECKING: from lightonopu.internal.device import OpuDevice # noinspection PyPep8Naming class", "of one or several input vectors. The `fit1d` or `fit2d`", "in a simulated manner, by passing the \" \\ \"simulated", "value) else: self.device.output_roi = self._output_roi.compute_roi(value) # We used to call", "the OPU device\"\"\" self._acq_stack.close() self.device.close() self._debug(\"OPU closed\") @property def config(self):", "the shape of each input vector. Not needed if the", "as n_2d_features defaults to False n_2d_features: list, tuple or np.ndarray", "= False, online=False, **override): \"\"\" Configure OPU transform for 2d", "or batch of input vectors. Each vector must have the", "n_components: int): \"\"\"Resize device's random matrix\"\"\" assert isinstance(self.device, SimulatedOpuDevice) rnd_mat", "it's for transmitting it to decoder init if inspect.isclass(decoder_cls): if", "= self._runner.traits if traits.packed: # TODO implement for packed raise", "raise ValueError(\"simulated and opu_device arguments are conflicting\") # Device init,", "[] # Build OPU name if not self._s.simulated: version.append(opu_version(self.__opu_config)) #", "= attr.fields(OpuSettings).n_samples_by_pass.default # Common settings to both simulated and base", "when acquisition is\" \\ \" in online mode, only single", "= attr.evolve(init, **override) if no_input and self.input_roi_strategy is InputRoiStrategy.auto: #", "if not self._s.simulated: state[\"__online_acq\"] = self.device.acq_state.value == AcqState.online.value self._acq_stack.close() #", "have the same dimensions as the one given in `fit1d`", "raise TypeError(\"opu_device must be of type SimulatedOpuDevice or OpuDevice\") self.device", "input start acquisition first assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't", "itself is closed on pickling return state def __setstate__(self, state):", "self.fit2d(X, n_2d_features, packed, False, **override) return self.transform(X) def __fit(self, X,", "attr.evolve(init, **override) if no_input and self.input_roi_strategy is InputRoiStrategy.auto: # If", "or torch.Tensor complete array of nonlinear random projections of X,", "by the OPU device .. seealso:: `close()` or use the", "This also sets the output ROI self.n_components = n_components self.input_roi_strategy", "vector must have the same dimensions as the one given", "the random matrix... \", end='', flush=True) self.device.build_random_matrix(n_features, n_components) self._print(\"OK\") def", "arrays or PyTorch tensors. The non-linear transform (`transform`) is a", "arguments are conflicting\") # Device init, or take the one", "of X, for Nitro (non-linear) photonic cores. Parameters ---------- X:", "open(self): \"\"\"Acquires hardware resources used by the OPU device ..", "n_tries=self.config.get(\"n_transform_tries\", 5), detect_trigger=self.config.get(\"detect_trigger_issue\", False), no_single_transform=self.config.get(\"no_single_transform\", False), stdev=self.config[\"output\"].get(\"stdev\", 1.), **kwargs) def", "1.3, \" \"Use lightonml.set_verbose_level instead\", DeprecationWarning) lightonml.set_verbose_level(verbose_level) else: verbose_level =", "dimensions, with ``n_features``. When input is bit-packed the packed flag", "device=self.device, disable_pbar=self.disable_pbar) self._acq_stack.close() if online: if self._s.no_single_transform: raise RuntimeError(\"Online transform", "not self.__opu_config: self.__opu_config = config.load_config(self.__config_file, self._trace) if self.__config_override is not", "self._s.min_n_components) # This also sets the output ROI self.n_components =", "input is an ndarray, type is actually ContextArray, with a", "traits = self._runner.traits if traits.packed: # TODO implement for packed", "be processed by the opu. decoder_cls: encoder.base.BaseTransformer, optional class or", "OPU class \"\"\" import time from math import sqrt import", "number of features must be provided as n_features defaults to", "Performs the nonlinear random projections of one or several input", "= TransformRunner(self._s, tr_settings, traits, device=self.device, disable_pbar=self.disable_pbar) self._acq_stack.close() if online: if", "the random matrix is then generated at __init__, using max_n_features", "will be raised, call `close()` or shutdown the kernel on", "None: # Input is provided, do the fit with user", "X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Do a linear transform", "`close()` or shutdown the kernel on the OPU object to", "an error will be raised, call `close()` or shutdown the", "assert n_features, \"either input vector or n_features must be specified\"", "the OPU will transform writeable only if opu_device is a", "only if online. Batch transform start their own. self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod", "use opu.open() or \\\"with opu:\\\"\" if inspect.isclass(encoder_cls): encoder = encoder_cls()", "True, each input vector is assumed to be a 1d", "performs transformation (read-only) input_roi_strategy: types.InputRoiStrategy, optional describes how to display", "resources used by the OPU device.\"\"\" self.__active_before_enter = self.device.active self.open()", "each input vector. Not needed if the input isn't bit-packed.", "TransformSettings from lightonml.internal.runner import TransformRunner, FitTransformRunner from lightonml.internal.types import InputRoiStrategy,", "rnd_mat = self.device.random_matrix if rnd_mat is None or rnd_mat.shape !=", "math:: \\\\mathbf{y} = \\\\lvert \\\\mathbf{R} \\\\mathbf{x} \\\\rvert^2 \\\\mbox{ (non-linear transform,", "TransformRunner, and start online acq if needs be. \"\"\" if", "deprecated, use lightonml.set_verbose_level() instead .. seealso:: `lightonml.set_verbose_level` input_roi_strategy: types.InputRoiStrategy, optional", "\"\"\" Do a linear transform of X, for Nitro (non-linear)", "not None: raise ValueError(\"simulated and opu_device arguments are conflicting\") #", "the fitXd calls Instantiates a TransformRunner, and start online acq", "the one-liner equivalent of `fit1d` and `transform` calls. .. warning::", "of `fit1d` and `transform` calls. .. warning:: when making several", "random matrix\"\"\" assert isinstance(self.device, SimulatedOpuDevice) rnd_mat = self.device.random_matrix if rnd_mat", "afterwards start = time.time() result = reconstruction.decode_batch(rp_opu) self._trace(f\"Decoding time {time.time()", "binary vectors to be processed by the opu. decoder_cls: encoder.base.BaseTransformer,", "not self._s.simulated: raise AttributeError(\"max_n_feature can't be set if device is", "lightonml.types import OutputRescaling # Import lightonopu only for typechecking, as", "not provided, follow system's setting (usually True) disable_pbar: bool, optional", "`lightonml.types.OutputRescaling` Attributes ---------- n_components: int dimensionality of the target projection", "vectors to be processed by the opu. decoder_cls: encoder.base.BaseTransformer, optional", "name if not self._s.simulated: version.append(opu_version(self.__opu_config)) # module version version.append(f\"lightonml version", "Parameters ---------- X: np.ndarray or torch.Tensor a 1d input vector,", "lightonopu is at 1.4.1 or later, needed for linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\")", "1d array, and the \"real\" number of features must be", "X2 is now numpy 2D, whatever the initial shape and", "of the target projection space. rescale: types.OutputRescaling, output rescaling method", "'LICENSE.txt', which is part of this source code package. \"\"\"", "we didn't find configuration files raise RuntimeError(no_config_msg) opu_type = self.config[\"type\"]", "def _resize_rnd_matrix(self, n_features: int, n_components: int): \"\"\"Resize device's random matrix\"\"\"", "lightonml.get_print_fn() self._acq_stack = ExitStack() # Restore online acquisition if it", "(self._s.stdev * sqrt(self.n_components)) return output def transform1d(self, *args, **kwargs): raise", "types.OutputRescaling, optional, output rescaling method for `linear_transform`. Ignored by `transform`.", "class or instance of class that transforms the output of", "getting access to our technology.\" if simulated and opu_device is", "assert self._runner, \"Call fit1d or fit2d before linear_transform\" traits =", "progress bar when verbose_level is set to 1 simulated: bool,", "unless relevant host.json option is False if open_at_init is None:", "traits is None: assert self._runner, \"Call fit1d or fit2d before", "OPU device.\"\"\" self.__active_before_enter = self.device.active self.open() return self def __exit__(self,", "to it, or just vector dimensions, with `n_features`. When input", "# need a configuration file for simulated device return OpuSettings(max_n_features=self._max_n_features,", "self._acq_stack.close() self.device.close() self._debug(\"OPU closed\") @property def config(self): \"\"\"Returns the internal", "pickling return state def __setstate__(self, state): self.__dict__.update(state) # Restore logging", "int, dimensionality of the target projection space. opu_device : OpuDevice", "appropriate format. Returns ------- Y: np.ndarray or torch.Tensor complete array", "\\\\mathbf{R} \\\\mathbf{x} \\\\rvert^2 \\\\mbox{ (non-linear transform, the default)} .. math::", "import TransformRunner, FitTransformRunner from lightonml.internal.types import InputRoiStrategy, IntOrTuple, TransformOutput, AcqState", "the opu. decoder_cls: encoder.base.BaseTransformer, optional class or instance of class", "for typechecking, as it's an optional module and may not", "---------- n_components: int dimensionality of the target projection space. rescale:", "the nonlinear random projections of 1d input vector(s). This function", "nonlinear random projections of one or several input vectors. The", "if needed issue = utils.detect_trigger_issue(self.device) if issue: # noinspection PyProtectedMember,PyUnresolvedReferences", "same dimensions as the one given in `fit1d` or `fit2d`.", "self.input_roi_strategy = input_roi_strategy # Runner initialized when entering fit self._runner", "`linear_transform`. Ignored by `transform`. max_n_features: int maximum number of binary", "# Decoding forgets about the context, re-add it to result", "about the context, re-add it to result afterwards start =", "fit self._runner = None # type: Optional[TransformRunner] # ExitStack for", "import InputRoiStrategy, IntOrTuple, TransformOutput, AcqState from lightonml.types import OutputRescaling #", "on your machine the random matrix is then generated at", "lightonopu.linear_reconstruction as reconstruction except ImportError: raise RuntimeError(\"Need a lightonopu version", "by the opu. decoder_cls: encoder.base.BaseTransformer, optional class or instance of", "calling `fit2d` and then `transform`, or you might encounter an", "encoding.base.BaseTransformer, optional class or instance of class that transform the", "called with input vector, for fitting OPU parameters to it,", "lightonml.set_verbose_level instead\", DeprecationWarning) lightonml.set_verbose_level(verbose_level) else: verbose_level = lightonml.get_verbose_level() self._debug =", "transforms will be made one vector after the other defaults", "the packed flag must be set to True. Number of", "on pickling return state def __setstate__(self, state): self.__dict__.update(state) # Restore", "# Runner initialized when entering fit self._runner = None #", ":/\") if inspect.isclass(encoder_cls): encoder = encoder_cls() else: encoder = encoder_cls", "intentionally after the decoding step if self.rescale is OutputRescaling.variance: n_features", "package. \"\"\" This module contains the OPU class \"\"\" import", "Fit will be made on this vector to optimize transform", "progress display Parameters ---------- X: np.ndarray or torch.Tensor a 2d", "now use fit1d and transform\") def transform2d(self, *args, **kwargs): raise", "than `linear_transform`. Acquiring/releasing hardware device resources is done by open/close", "n_features = user_input.n_features_s output = output / (self._s.stdev * sqrt(n_features))", "acquisition only if online. Batch transform start their own. self._acq_stack.enter_context(self.device.acquiring(online=True))", "to True. Parameters ---------- X: np.ndarray or torch.Tensor Fit will", "will transform writeable only if opu_device is a SimulatedOpuDevice, in", "= self.device.acq_state.value == AcqState.online.value self._acq_stack.close() # Device itself is closed", "self._post_transform(out, user_input, encoder, decoder_cls) def linear_transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) ->", "decoder = decoder_cls(**encoder.get_params()) else: decoder = decoder_cls() else: decoder =", "add metadata \"\"\" assert self._runner, \"Call fit1d or fit2d before", "other defaults to False override: dict, optional keyword args for", "matrix config_file : str, optional path to the configuration file", "is False if open_at_init is None: open_at_init = get_host_option(\"lightonml_open_at_init\", True)", "of class that transform the input into binary vectors to", "{\"input_shape\": self.device.input_shape, \"output_max_shape\": self.device.output_shape_max, \"frametime_us\": self._base_frametime_us, \"exposure_us\": self._base_exposure_us} if isinstance(self.device,", "if traits is None: assert self._runner, \"Call fit1d or fit2d", "int] = None, packed: bool = False, online=False, **override): \"\"\"", "the OPU transform prepared_input = OpuUserInput.from_traits(prepared_X, traits) start = time.time()", "of 1d input_vectors, binary encoded, packed or not batch can", "torch return torch.from_numpy(output) else: return output def _raw_linear_transform(self, X, traits=None,", "or not batch can be 1d or 2d. In all", "provided as n_2d_features defaults to False n_2d_features: list, tuple or", "traits = self._runner.traits if user_input is None: user_input = OpuUserInput.from_traits(X,", "vector after each other, add `online=True` in the fit function.", "flag set to True. Parameters ---------- X: np.ndarray or torch.Tensor", "LightOn, All Rights Reserved. # This file is subject to", "if self.rescale is OutputRescaling.variance: n_features = user_input.n_features_s output = output", "encoder, decoder_cls): \"\"\"Final steps after transform 1. reshape 2. decode", "and transform\") def fit_transform1d(self, X, packed: bool = False, **override)", "# Don't close if OPU was already active if not", "= self.config.get(\"sequence_nb_prelim\", 0) name = self.config[\"name\"] self.device = OpuDevice(opu_type, frametime_us,", "Tuple[int, int] = None, packed: bool = False, online=False, **override):", "OPU: \"\"\"Interface to the OPU. .. math:: \\\\mathbf{y} = \\\\lvert", "how to display the features on the input device ..", "is the one-liner equivalent of `fit2d` and `transform` calls. ..", "whether the input data is in bit-packed representation defaults to", "`fit2d`. encoder_cls: encoding.base.BaseTransformer, optional class or instance of class that", "or online option. If you need to transform one vector", "it to decoder init if inspect.isclass(decoder_cls): if hasattr(encoder, \"get_params\"): decoder", "be processed by the opu. decoder_cls: encoding.base.BaseTransformer, optional class or", "= encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, self._runner.traits) self._debug(str(user_input)) if user_input.is_batch and", "metadata \"\"\" assert self._runner, \"Call fit1d or fit2d before transform\"", "a context attribute to add metadata \"\"\" self.fit2d(X, n_2d_features, packed,", "OPU was found on this machine.\\n\" \\ \"You may want", "Get default value pass_default = attr.fields(OpuSettings).n_samples_by_pass.default # Common settings to", "type is actually ContextArray, with a context attribute to add", "acquires hardware resources used by the OPU device.\"\"\" self.__active_before_enter =", "= None # type: Optional[TransformRunner] # ExitStack for device acquisition,", "# Only dimensions are provided, no fitting happens on input", "binary encoded, packed or not packed: bool, optional whether the", "input was tensor \"\"\" output = user_input.reshape_output(output) # If encoder", "to initiate or resize the random matrix device: OpuDevice or", "hardware resource at init. If not provided, follow system's setting", "\"No configuration files for the OPU was found on this", "the OPU in a simulated manner, by passing the \"", "of size self.n_components If input is an ndarray, type is", "acq if needs be. \"\"\" if X is not None:", "fit function. Parameters ---------- X: np.ndarray or torch.Tensor input vector,", "type (torch or numpy) X2 = user_input.reshape_input(raveled_features=True, leave_single_dim=True) try: import", "\"\"\" This module contains the OPU class \"\"\" import time", "display of the progress bar when verbose_level is set to", "must be provided as n_2d_features defaults to False n_2d_features: list,", "is now numpy 2D, whatever the initial shape and the", "display the features on the input device \"\"\" def __init__(self,", "= OpuDevice(opu_type, frametime_us, exposure_us, seq_nb_prelim, None, verbose_level, name) self._base_frametime_us =", "n_features, packed, online, False, **override) def fit2d(self, X=None, n_features: Tuple[int,", "matrix... \", end='', flush=True) self.device.build_random_matrix(n_features, n_components) self._print(\"OK\") def version(self, devices=False):", "return self._n_components @n_components.setter def n_components(self, value: int): if self._s.simulated: self._resize_rnd_matrix(self.max_n_features,", "fit_transform1d(self, X, packed: bool = False, **override) -> ContextArray: \"\"\"Performs", "\\ \"See also https://lighton.ai/products for getting access to our technology.\"", "packed or not batch can be 1d or 2d. In", "user_input.reshape_input(raveled_features=True, leave_single_dim=True) try: import lightonopu.linear_reconstruction as reconstruction except ImportError: raise", "it's the enum value if isinstance(value, str): self._rescale = OutputRescaling[value.lower()]", "PyUnresolvedReferences import lightonopu version.append(f\"lightonopu version {lightonopu.__version__}\") except ImportError: pass if", "before linear_transform\" traits = self._runner.traits if traits.packed: # TODO implement", "= rp_opu else: # Decoding forgets about the context, re-add", "packed: bool = False, n_2d_features=None, **override) -> ContextArray: \"\"\"Performs the", "settings.input_roi is None return settings def fit1d(self, X=None, n_features: int", "None: assert self._runner, \"Call fit1d or fit2d before linear_transform\" traits", "opu_device: Optional[Union[\"OpuDevice\", SimulatedOpuDevice]] = None, max_n_features: int = 1000, config_file:", "encoder, decoder_cls) def linear_transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\"", "if online. Batch transform start their own. self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod def", "online, False, **override) def fit2d(self, X=None, n_features: Tuple[int, int] =", "to be a 1d array, and the \"real\" number of", "device return OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default, simulated=True, **kwargs ) return OpuSettings( max_n_features=int(np.prod(self.device.input_shape)),", "user_input) # Decoding, add context, and optional convert back to", "config_file: str = \"\", config_override: dict = None, verbose_level: int", "optional forces the setting of acquiring hardware resource at init.", "numpy as np from contextlib import ExitStack import attr import", "If not provided, a device is properly instantiated. If opu_device", "return output def _raw_linear_transform(self, X, traits=None, user_input=None): \"\"\" Do linear_transform", "Only dimensions are provided, no fitting happens on input assert", "you might encounter an inconsistency in the transformation matrix. If", "the input vectors will be already bit-packed online: bool, optional", "is None: assert self._runner, \"Call fit1d or fit2d before linear_transform\"", "that transform the input into binary vectors to be processed", "OPU\"\"\" version = [] # Build OPU name if not", "self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod def _post_transform(output, user_input, encoder, decoder_cls): \"\"\"Final steps after", "initialized when entering fit self._runner = None # type: Optional[TransformRunner]", "lightonopu version.append(f\"lightonopu version {lightonopu.__version__}\") except ImportError: pass if devices: version.append(self.device.versions())", "print functions if verbose_level != -1: warnings.warn(\"Verbose level arg will", "SimulatedOpuDevice, the random matrix is generated at __init__, using max_n_features", "!= AcqState.online.value, \\ \"Can't do linear transform when acquisition is\"", "simulated: bool, optional performs the random projection using CPU, in", "noinspection PyUnresolvedReferences import lightonopu version.append(f\"lightonopu version {lightonopu.__version__}\") except ImportError: pass", "Device init, or take the one passed as input if", "simulated=True, **kwargs ) return OpuSettings( max_n_features=int(np.prod(self.device.input_shape)), # Will use defaults", "-> TransformSettings: \"\"\"Returns transform settings for feeding to TransformRunner\"\"\" init", "to True. When input vectors must be transformed one by", "PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim = 1 self._debug(\"trigger issue detected, workaround applied\") else:", "here, in order not to # need a configuration file", "steps after transform 1. reshape 2. decode the output 3.", "TypeError(\"opu_device must be of type SimulatedOpuDevice or OpuDevice\") self.device =", "may not be present if TYPE_CHECKING: from lightonopu.internal.device import OpuDevice", "several transform calls, prefer calling `fit1d` and then `transform`, or", "lightonml.context import ContextArray from lightonml.internal.settings import OpuSettings, TransformSettings from lightonml.internal.runner", "projections of 1d input vector(s). This function is the one-liner", "self.__dict__.update(state) # Restore logging functions removed at getstate self._debug =", "acquisition is\" \\ \" in online mode, only single vectors\"", "output = output / (self._s.stdev * sqrt(self.n_components)) return output def", "to the terms and conditions defined in # file 'LICENSE.txt',", "the OPU Settings are immutable (attrs frozen), so generate it", "Input is provided, do the fit with user input user_input", "for linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\") # initialize linear_reconstruction library from lightonopu import", "ContextArray from lightonml.internal.settings import OpuSettings, TransformSettings from lightonml.internal.runner import TransformRunner,", "disable_pbar=self.disable_pbar) else: # Only dimensions are provided, no fitting happens", "the input device \"\"\" def __init__(self, n_components: int = 200000,", "OPU parameters to it, or just vector dimensions, with ``n_features``.", "method for `linear_transform`. Ignored by `transform`. .. seealso:: `lightonml.types.OutputRescaling` Attributes", "\" \\ \"for more details.\\n\" \\ \"See also https://lighton.ai/products for", "@staticmethod def _post_transform(output, user_input, encoder, decoder_cls): \"\"\"Final steps after transform", "assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't transform a batch of", "with the online flag set to True. Parameters ---------- X:", "assert self._runner, \"Call fit1d or fit2d before transform\" assert self.device.active,", "performs the random projection using CPU, in case no OPU", "https://lighton.ai/products for getting access to our technology.\" if simulated and", "SimulatedOpuDevice, in order to initiate the random matrix config_file :", "encoder_cls X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, self._runner.traits) self._debug(str(user_input)) if", "allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), # min_n_components is linked to the minimum output size", "= OpuUserInput.from_traits(X_enc, self._runner.traits) self._debug(str(user_input)) if user_input.is_batch and not self._s.simulated: #", "= ExitStack() self._trace(\"OPU initialized\") # Open at init, unless relevant", "torch.Tensor a 2d input vector, or batch of 2d input_vectors,", "if isinstance(self.device, SimulatedOpuDevice): # Notice we never query self.config here,", "setting of acquiring hardware resource at init. If not provided,", "transform\") def transform2d(self, *args, **kwargs): raise RuntimeError(\"transform2d is deprecated, you", "re-add it to result afterwards start = time.time() result =", "is OutputRescaling.norm: output = output / (self._s.stdev * sqrt(self.n_components)) return", "fit2d before linear_transform\" traits = self._runner.traits if traits.packed: # TODO", "optional path to the configuration file (for dev purpose) config_override:", "device .. seealso:: `lightonml.internal.types.InputRoiStrategy` open_at_init: bool, optional forces the setting", "array of nonlinear random projections of X, of size self.n_components", "online acquisition if it was the case if state.get(\"__online_acq\", False):", "\\ \" in online mode, only single vectors\" assert self._runner.t.input_roi_strategy", "else: decoder = decoder_cls() else: decoder = decoder_cls output =", "isn't provided, or if input is bit-packed packed: bool, optional", "decoding step if self.rescale is OutputRescaling.variance: n_features = user_input.n_features_s output", "# TODO implement for packed raise RuntimeError(\"Linear transform isn't yet", "binary encoded, packed or not batch can be 1d or", "\"See also https://lighton.ai/products for getting access to our technology.\" if", "is ongoing, close it if not self._s.simulated: state[\"__online_acq\"] = self.device.acq_state.value", "False override: keyword args for overriding transform settings (advanced parameters)", "both raw OPU output and decoded output in a tuple", "the same dimensions as the one given in `fit1d` or", "\\\\mathbf{y} = \\\\lvert \\\\mathbf{R} \\\\mathbf{x} \\\\rvert^2 \\\\mbox{ (non-linear transform, the", "from lightonml.encoding.base import NoEncoding, NoDecoding import warnings from typing import", "n_features defaults to False online: bool, optional Set to true", "SimulatedOpuDevice, optional optical processing unit instance linked to a physical", "features must be then provided with `n_features` When input vectors", "self.device.acquiring(n_images=self._s.n_samples_by_pass): out = self._runner.transform(user_input) else: out = self._runner.transform(user_input) return self._post_transform(out,", "the configuration file (for dev purpose) config_override: dict, optional for", "max_n_features self.disable_pbar = disable_pbar self.rescale = rescale # Get trace", "self._debug(\"OPU closed\") @property def config(self): \"\"\"Returns the internal configuration object\"\"\"", "method must be called before, for setting vector dimensions or", "packed flag must be set to True. When input vectors", "of input vectors. Each vector must have the same dimensions", "for linear_transform to be correct.\\n\" \\ \"Set input_roi_strategy attribute to", "the progress bar when verbose_level is set to 1 simulated:", "8*X.shape[-1]`` Otherwise ``n_features = X.shape[-1]`` If tqdm module is available,", "OPU name if not self._s.simulated: version.append(opu_version(self.__opu_config)) # module version version.append(f\"lightonml", "Do linear_transform of X, and return both raw OPU output", "lightonopu version with linear_reconstruction module\") start = time.time() prepared_X =", "= self.config[\"type\"] frametime_us = self.config[\"input\"][\"frametime_us\"] exposure_us = self.config[\"output\"][\"exposure_us\"] seq_nb_prelim =", "user_input.is_tensor: # noinspection PyPackageRequirements,PyUnresolvedReferences import torch return torch.from_numpy(output) else: return", "if isinstance(value, str): self._rescale = OutputRescaling[value.lower()] else: assert isinstance(value, OutputRescaling)", "config.load_config(self.__config_file, self._trace) if self.__config_override is not None: utils.recurse_update(self.__opu_config, self.__config_override) return", "utils, types from lightonml.internal.user_input import OpuUserInput, InputTraits from lightonml.internal.simulated_device import", "self.__config_file = config_file self.__config_override = config_override self._max_n_features = max_n_features self.disable_pbar", "seealso:: `lightonml.internal.types.InputRoiStrategy` open_at_init: bool, optional forces the setting of acquiring", "must now use fit2d and transform\") def fit_transform1d(self, X, packed:", "must be full for linear_transform to be correct.\\n\" \\ \"Set", "parameters to it, or just vector dimensions, with ``n_features``. When", "= self.config[\"output\"][\"exposure_us\"] seq_nb_prelim = self.config.get(\"sequence_nb_prelim\", 0) name = self.config[\"name\"] self.device", "bool, optional Set to true if the transforms will be", "True. Parameters ---------- X: np.ndarray or torch.Tensor a 2d input", "must be of type SimulatedOpuDevice or OpuDevice\") self.device = opu_device", "``n_features``. When input is bit-packed the packed flag must be", "np from contextlib import ExitStack import attr import inspect import", "vectors must be transformed one by one, performance will be", "to add metadata \"\"\" self.fit2d(X, n_2d_features, packed, False, **override) return", "settings associated with the OPU Settings are immutable (attrs frozen),", "binary features that the OPU will transform used only if", "output / (self._s.stdev * sqrt(self.n_components)) return output def transform1d(self, *args,", "state.pop(\"_debug\") state.pop(\"_trace\") state.pop(\"_print\") # acq stack can't be pickled, will", "self._n_components) self._max_n_features = value @property def _s(self) -> OpuSettings: \"\"\"Returns", "else: # Only dimensions are provided, no fitting happens on", "linear_transform of X, and return both raw OPU output and", "getstate self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn()", "bit-packed the packed flag must be set to True. Number", "state.pop(\"_print\") # acq stack can't be pickled, will be restored", "is None: open_at_init = get_host_option(\"lightonml_open_at_init\", True) if open_at_init: self.open() def", "the output 3. convert to tensor if user input was", "self.device = OpuDevice(opu_type, frametime_us, exposure_us, seq_nb_prelim, None, verbose_level, name) self._base_frametime_us", "projection space. rescale: types.OutputRescaling, output rescaling method for `linear_transform`. Ignored", "return both raw OPU output and decoded output in a", "OPU transform prepared_input = OpuUserInput.from_traits(prepared_X, traits) start = time.time() with", "found on this machine.\\n\" \\ \"You may want to run", "traits, device=self.device, disable_pbar=self.disable_pbar) self._acq_stack.close() if online: if self._s.no_single_transform: raise RuntimeError(\"Online", "vector, for fitting OPU parameters to it, or just vector", "this OPU\") # Start acquisition only if online. Batch transform", "user_input=None): \"\"\" Do linear_transform of X, and return both raw", "= OpuUserInput.from_traits(X_enc, traits) _, result_ctx = self._raw_linear_transform(X_enc, traits, user_input) #", "needed if the input isn't bit-packed. override: keyword args for", "one passed as input if opu_device: if type(opu_device).__name__ not in", "made one vector after the other defaults to False override:", "it's an optional module and may not be present if", "the OPU was found on this machine.\\n\" \\ \"You may", "Remove logging functions, they can't be pickled state.pop(\"_debug\") state.pop(\"_trace\") state.pop(\"_print\")", "dimensions or online option. If you need to transform one", "to the OPU. .. math:: \\\\mathbf{y} = \\\\lvert \\\\mathbf{R} \\\\mathbf{x}", "of binary features that the OPU will transform used only", "\"\"\" Do linear_transform of X, and return both raw OPU", "removed at getstate self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print", "encoding to something suitable for formatting prepared_X = user_input.unravel_features(prepared_X) #", "transform a batch of vectors when acquisition is\" \\ \"", "= reconstruction.encode_batch(X2) self._trace(f\"Encoding time {time.time() - start} s\") # Restore", "resources is done by open/close and a context-manager interface. Unless", "since it uses X to compute it tr_settings = self._tr_settings(no_input=True,", "False online: bool, optional Set to true if the transforms", "= encoder_cls() else: encoder = encoder_cls X_enc = encoder.transform(X) user_input", "user_input, encoder, decoder_cls) def linear_transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput:", "= 8*X.shape[-1]`` Otherwise ``n_features = X.shape[-1]`` If tqdm module is", "the OPU device.\"\"\" self.__active_before_enter = self.device.active self.open() return self def", "workaround applied\") else: self._debug(\"trigger issue not detected\") self._debug(\"OPU opened\") def", "(advanced parameters) \"\"\" return self.__fit(X, n_features, packed, online, True, **override)", "n_components max_n_features: int, optional maximum number of binary features that", "transform settings for feeding to TransformRunner\"\"\" init = TransformSettings(self.input_roi_strategy, self.n_components)", "to it, or just vector dimensions, with ``n_features``. When input", "the random matrix if not done already self._resize_rnd_matrix(max_n_features, n_components) else:", "opu_device is a SimulatedOpuDevice, in order to initiate the random", "encoded, packed or not packed: bool, optional whether the input", "`fit2d`. encoder_cls: encoder.base.BaseTransformer, optional class or instance of class that", "a 1d array, and the \"real\" number of features must", "context manager interface for closing at the end af an", "tensor if user input was tensor \"\"\" output = user_input.reshape_output(output)", "Get trace and print functions if verbose_level != -1: warnings.warn(\"Verbose", "opu.open() or \\\"with opu:\\\"\" if inspect.isclass(encoder_cls): encoder = encoder_cls() else:", "and accept NumPy arrays or PyTorch tensors. The non-linear transform", "*args): # Don't close if OPU was already active if", "Optional, Union, Tuple, TYPE_CHECKING import numpy as np from contextlib", "input data can be bit-packed, where ``n_features = 8*X.shape[-1]`` Otherwise", "import SimulatedOpuDevice from lightonml.context import ContextArray from lightonml.internal.settings import OpuSettings,", "\\\\rvert^2 \\\\mbox{ (non-linear transform, the default)} .. math:: \\\\mathbf{y} =", "is None return settings def fit1d(self, X=None, n_features: int =", "When input is bit-packed the packed flag must be set", "self.open() def _tr_settings(self, no_input=False, **override) -> TransformSettings: \"\"\"Returns transform settings", "= time.time() with self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu = self._runner.transform(prepared_input, linear=True) self._trace(f\"Transform time", "value @property def max_n_features(self) -> int: return self._s.max_n_features @max_n_features.setter def", "start} s\") if self._s.simulated: result_ctx = rp_opu else: # Decoding", "= self._runner.transform(prepared_input, linear=True) self._trace(f\"Transform time {time.time() - start} s\") if", "overriding transform settings (advanced parameters) Returns ------- Y: np.ndarray or", "may want to run the OPU in a simulated manner,", "else: # Make sure lightonopu is at 1.4.1 or later,", "on this host as we didn't find configuration files raise", "seq_nb_prelim = self.config.get(\"sequence_nb_prelim\", 0) name = self.config[\"name\"] self.device = OpuDevice(opu_type,", "self.open() return self def __exit__(self, *args): # Don't close if", "return self._rescale @rescale.setter def rescale(self, value): # If str it's", "flag must be set to True. When input vectors must", "n_2d_features defaults to False n_2d_features: list, tuple or np.ndarray of", "= \\\\lvert \\\\mathbf{R} \\\\mathbf{x} \\\\rvert^2 \\\\mbox{ (non-linear transform, the default)}", "the config_file (for dev purpose) verbose_level: int, optional deprecated, use", "TransformSettings(self.input_roi_strategy, self.n_components) settings = attr.evolve(init, **override) if no_input and self.input_roi_strategy", "2D, whatever the initial shape and the type (torch or", "types.InputRoiStrategy = types.InputRoiStrategy.full, open_at_init: bool = None, disable_pbar=False, simulated=False, rescale:", "with ``n_features``. When input is bit-packed the packed flag must", "user_input = OpuUserInput.from_traits(X, traits) if self._s.simulated: prepared_X = X else:", "frozen), so generate it at each call. Performance impact is", "of the target projection space. opu_device : OpuDevice or SimulatedOpuDevice,", "not batch can be 1d or 2d. In all cases", "dimensions are provided, no fitting happens on input assert n_features,", "writeable only if opu_device is a SimulatedOpuDevice, in order to", "reshape 2. decode the output 3. convert to tensor if", "online. Batch transform start their own. self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod def _post_transform(output,", "NoEncoding, NoDecoding import warnings from typing import Optional, Union, Tuple,", "and n_components max_n_features: int, optional maximum number of binary features", "from lightonopu import linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi = output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy, self._s.allowed_roi,", "calls, prefer calling `fit2d` and then `transform`, or you might", "by open/close and a context-manager interface. Unless `open_at_init=False`, these resources", "directly from lightonopu.internal.device import OpuDevice if not self.__config_file and not", "= self.__dict__.copy() # Remove logging functions, they can't be pickled", "the input into binary vectors to be processed by the", "open_at_init = get_host_option(\"lightonml_open_at_init\", True) if open_at_init: self.open() def _tr_settings(self, no_input=False,", "display the features on the input device .. seealso:: `lightonml.internal.types.InputRoiStrategy`", "output 3. convert to tensor if user input was tensor", "= lightonml.get_trace_fn() self._print = lightonml.get_print_fn() no_config_msg = \"No configuration files", "or fit2d before linear_transform\" traits = self._runner.traits if traits.packed: #", "that the OPU will transform used only if opu_device is", "this host as we didn't find configuration files raise RuntimeError(no_config_msg)", "of features must be then provided with `n_features` When input", "one given in `fit1d` or `fit2d`. encoder_cls: encoding.base.BaseTransformer, optional class", "if self._s.no_single_transform: raise RuntimeError(\"Online transform isn't available with this OPU\")", "# With batch input start acquisition first assert self.device.acq_state.value !=", "manner, by passing the \" \\ \"simulated argument to True", "vectors\" with self.device.acquiring(n_images=self._s.n_samples_by_pass): out = self._runner.transform(user_input) else: out = self._runner.transform(user_input)", "if opu_device is a SimulatedOpuDevice, in order to initiate or", "# If no input_roi, replace auto by full strategy settings.input_roi_strategy", "RuntimeError(\"Linear transform isn't yet implemented for packed input :/\") if", "Parameters ---------- X: np.ndarray or torch.Tensor a 2d input vector,", "init. If not provided, follow system's setting (usually True) disable_pbar:", "!= (n_features, n_components): self._print(\"OPU: computing the random matrix... \", end='',", "optical processing unit instance linked to a physical or simulated", "input_roi_strategy attribute to InputRoiStrategy.full.\" # X2 is now numpy 2D,", "self.config[\"type\"] frametime_us = self.config[\"input\"][\"frametime_us\"] exposure_us = self.config[\"output\"][\"exposure_us\"] seq_nb_prelim = self.config.get(\"sequence_nb_prelim\",", "true if the transforms will be made one vector after", "to False n_2d_features: list, tuple or np.ndarray of length 2", "`transform` calls. .. warning:: when making several transform calls, prefer", "vectors when acquisition is\" \\ \" in online mode, only", "the input data is in bit-packed representation if True, each", "unit instance linked to a physical or simulated device. If", "vectors. Each vector must have the same dimensions as the", "The `fit1d` or `fit2d` method must be called before, for", "transform start their own. self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod def _post_transform(output, user_input, encoder,", "int, optional maximum number of binary features that the OPU", "defaults to False override: dict, optional keyword args for overriding", "mode, only single vectors\" with self.device.acquiring(n_images=self._s.n_samples_by_pass): out = self._runner.transform(user_input) else:", "init, unless relevant host.json option is False if open_at_init is", "with the OPU Settings are immutable (attrs frozen), so generate", "Set to true if the input vectors will be already", "input vector, for fitting OPU parameters to it, or just", "override: dict, optional keyword args for overriding transform settings (advanced", "needs be. \"\"\" if X is not None: # Input", "transform\" assert self.device.active, \"OPU device isn't active, use opu.open() or", "if user_input.is_batch and not self._s.simulated: # With batch input start", "bit-packed, where ``n_features = 8*X.shape[-1]`` Otherwise ``n_features = X.shape[-1]`` If", "int, n_components: int): \"\"\"Resize device's random matrix\"\"\" assert isinstance(self.device, SimulatedOpuDevice)", "*args, **kwargs): raise RuntimeError(\"transform2d is deprecated, you must now use", "None return settings def fit1d(self, X=None, n_features: int = None,", "2d vectors The function can be either called with input", "of the fitXd calls Instantiates a TransformRunner, and start online", "and n_components rescale: types.OutputRescaling, optional, output rescaling method for `linear_transform`.", "lightonml.get_verbose_level() self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn()", "frametime_us = self.config[\"input\"][\"frametime_us\"] exposure_us = self.config[\"output\"][\"exposure_us\"] seq_nb_prelim = self.config.get(\"sequence_nb_prelim\", 0)", "for the input, necessary if X parameter isn't provided, or", "__init__(self, n_components: int = 200000, opu_device: Optional[Union[\"OpuDevice\", SimulatedOpuDevice]] = None,", "issue detected, workaround applied\") else: self._debug(\"trigger issue not detected\") self._debug(\"OPU", "input, necessary if X parameter isn't provided packed: bool Set", "= 1000, config_file: str = \"\", config_override: dict = None,", "AttributeError(\"max_n_feature can't be set if device is real\") self._resize_rnd_matrix(value, self._n_components)", "__setstate__(self, state): self.__dict__.update(state) # Restore logging functions removed at getstate", "**kwargs): raise RuntimeError(\"transform1d is deprecated, you must now use fit1d", "the context manager interface for closing at the end af", "s\") if self._s.simulated: result_ctx = rp_opu else: # Decoding forgets", "bool, optional disable display of the progress bar when verbose_level", "state.pop(\"_acq_stack\") # If acquisition is ongoing, close it if not", "instance of class that transform the input into binary vectors", "transform settings (advanced parameters) Returns ------- Y: np.ndarray or torch.Tensor", "not self.__active_before_enter: self.close() def open(self): \"\"\"Acquires hardware resources used by", "the transformation matrix. If tqdm module is available, it is", "\"\"\"Context manager interface that acquires hardware resources used by the", "is None: user_input = OpuUserInput.from_traits(X, traits) if self._s.simulated: prepared_X =", "If acquisition is ongoing, close it if not self._s.simulated: state[\"__online_acq\"]", "Union, Tuple, TYPE_CHECKING import numpy as np from contextlib import", "opu_device elif simulated: self.device = SimulatedOpuDevice() else: # Instantiate device", "it uses X to compute it tr_settings = self._tr_settings(no_input=True, **override)", "optional, output rescaling method for `linear_transform`. Ignored by `transform`. ..", "use fit1d and transform\") def transform2d(self, *args, **kwargs): raise RuntimeError(\"transform2d", "provided with `n_features` When input vectors must be transformed one", "linear_transform\" traits = self._runner.traits if user_input is None: user_input =", "output in a tuple \"\"\" if traits is None: assert", "of 2d input vector(s). This function is the one-liner equivalent", "time if not self.__opu_config: self.__opu_config = config.load_config(self.__config_file, self._trace) if self.__config_override", "or numpy) X2 = user_input.reshape_input(raveled_features=True, leave_single_dim=True) try: import lightonopu.linear_reconstruction as", "OpuDevice # noinspection PyPep8Naming class OPU: \"\"\"Interface to the OPU.", "or n_features must be specified\" # tr_settings has no input_roi,", "\"\"\" def __init__(self, n_components: int = 200000, opu_device: Optional[Union[\"OpuDevice\", SimulatedOpuDevice]]", "functions removed at getstate self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn()", "{time.time() - start} s\") # Restore the dimension after batch", "active if not self.__active_before_enter: self.close() def open(self): \"\"\"Acquires hardware resources", "will be improved with the online flag set to True.", "is not None: # Input is provided, do the fit", "seealso:: `lightonml.set_verbose_level` input_roi_strategy: types.InputRoiStrategy, optional describes how to display the", "# Device itself is closed on pickling return state def", "opu_device is not None: raise ValueError(\"simulated and opu_device arguments are", "linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\") # initialize linear_reconstruction library from lightonopu import linear_reconstruction", "also https://lighton.ai/products for getting access to our technology.\" if simulated", "not detected\") self._debug(\"OPU opened\") def close(self): \"\"\"Releases hardware resources used", "Returns ------- Y: np.ndarray or torch.Tensor complete array of nonlinear", "OPU will transform writeable only if opu_device is a SimulatedOpuDevice,", "input_vectors, binary encoded, packed or not n_features: tuple(int) Number of", "add `online=True` in the fit function. Parameters ---------- X: np.ndarray", "This function is the one-liner equivalent of `fit2d` and `transform`", "and take action if needed issue = utils.detect_trigger_issue(self.device) if issue:", "if self.__config_override is not None: utils.recurse_update(self.__opu_config, self.__config_override) return self.__opu_config @property", "context attribute to add metadata \"\"\" assert self._runner, \"Call fit1d", "vector dimensions or online option. If you need to transform", "def max_n_features(self, value: int): if not self._s.simulated: raise AttributeError(\"max_n_feature can't", "in the fit function. Parameters ---------- X: np.ndarray or torch.Tensor", "# Decoding, add context, and optional convert back to torch", "\"Can't do linear transform when acquisition is\" \\ \" in", "-> ContextArray: \"\"\"Performs the nonlinear random projections of 2d input", "= None, disable_pbar=False, simulated=False, rescale: Union[OutputRescaling, str] = OutputRescaling.variance): self.__opu_config", "or instance of class that transforms the output of the", "or batch of 2d input_vectors, binary encoded, packed or not", "context, re-add it to result afterwards start = time.time() result", "hardware that performs transformation (read-only) input_roi_strategy: types.InputRoiStrategy, optional describes how", "the OPU\"\"\" version = [] # Build OPU name if", "not in [\"SimulatedOpuDevice\", \"OpuDevice\"]: raise TypeError(\"opu_device must be of type", "features that the OPU will transform writeable only if opu_device", "(usually True) disable_pbar: bool, optional disable display of the progress", "\"\"\" assert self._runner, \"Call fit1d or fit2d before transform\" assert", "indent block \"\"\" if self.device.active: return self.device.open() # initial reservation", "if not done already self._resize_rnd_matrix(max_n_features, n_components) else: # Make sure", "(linear transform)} Main methods are `transform`, `linear_transform`, `fit1d` and `fit2d`,", "logging functions removed at getstate self._debug = lightonml.get_debug_fn() self._trace =", "be set to True. Number of features must be then", "display Parameters ---------- X: np.ndarray or torch.Tensor a 1d input", "device.\"\"\" self.__active_before_enter = self.device.active self.open() return self def __exit__(self, *args):", "after each other, add `online=True` in the fit function. Parameters", "import torch return torch.from_numpy(output) else: return output def _raw_linear_transform(self, X,", "---------- X: np.ndarray or torch.Tensor a 1d input vector, or", "state[\"__online_acq\"] = self.device.acq_state.value == AcqState.online.value self._acq_stack.close() # Device itself is", "generate it at each call. Performance impact is negligible\"\"\" #", "optional Set to true if the transforms will be made", "linear_reconstruction library from lightonopu import linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi = output_roi.OutputRoi(self.device.output_shape_max,", "False, **override) -> ContextArray: \"\"\"Performs the nonlinear random projections of", "Parameters ---------- X: np.ndarray or torch.Tensor input vector, or batch", "\"\"\"Returns immutable settings associated with the OPU Settings are immutable", "self.__config_file and not config.host_has_opu_config(): # Looks like there's no OPU", "sqrt(n_features)) elif self.rescale is OutputRescaling.norm: output = output / (self._s.stdev", "(advanced parameters) Returns ------- Y: np.ndarray or torch.Tensor complete array", "X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Performs the nonlinear random", "both simulated and base kwargs = {\"input_shape\": self.device.input_shape, \"output_max_shape\": self.device.output_shape_max,", "operation for the OPU, and performs at a higher speed", "parameter isn't provided, or if input is bit-packed packed: bool,", "2020 LightOn, All Rights Reserved. # This file is subject", "device=self.device, disable_pbar=self.disable_pbar) else: # Only dimensions are provided, no fitting", "leave_single_dim=True) try: import lightonopu.linear_reconstruction as reconstruction except ImportError: raise RuntimeError(\"Need", "version.append(opu_version(self.__opu_config)) # module version version.append(f\"lightonml version {lightonml.__version__}\") try: # noinspection", "device\"\"\" self._acq_stack.close() self.device.close() self._debug(\"OPU closed\") @property def config(self): \"\"\"Returns the", "acquisition if it was the case if state.get(\"__online_acq\", False): self._acq_stack.enter_context(self.device.acquiring(online=True))", "random projections of one or several input vectors. The `fit1d`", "sqrt(self.n_components)) return output def transform1d(self, *args, **kwargs): raise RuntimeError(\"transform1d is", "or instance of class that transform the input into binary", "self.transform(X) def fit_transform2d(self, X, packed: bool = False, n_2d_features=None, **override)", "the \"real\" number of features must be provided as n_features", "np.ndarray of length 2 If the input is bit-packed, specifies", "**override) traits = InputTraits(n_features, packed) self._runner = TransformRunner(self._s, tr_settings, traits,", "---------- n_components : int, dimensionality of the target projection space.", "kwargs = {\"input_shape\": self.device.input_shape, \"output_max_shape\": self.device.output_shape_max, \"frametime_us\": self._base_frametime_us, \"exposure_us\": self._base_exposure_us}", "OpuDevice or SimulatedOpuDevice underlying hardware that performs transformation (read-only) input_roi_strategy:", "pickled state.pop(\"_debug\") state.pop(\"_trace\") state.pop(\"_print\") # acq stack can't be pickled,", "is bit-packed the packed flag must be set to True.", "Parameters ---------- X: np.ndarray or torch.Tensor Fit will be made", "self._raw_linear_transform(X_enc, traits, user_input) # Decoding, add context, and optional convert", "encoder_cls: encoder.base.BaseTransformer, optional class or instance of class that transform", "present if TYPE_CHECKING: from lightonopu.internal.device import OpuDevice # noinspection PyPep8Naming", "start acquisition first assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't transform", "in online mode, only single vectors\" assert self._runner.t.input_roi_strategy == InputRoiStrategy.full,", "NoDecoding import warnings from typing import Optional, Union, Tuple, TYPE_CHECKING", "True, **override) def transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\"", "lightonml.get_trace_fn() self._print = lightonml.get_print_fn() self._acq_stack = ExitStack() # Restore online", "packed: bool, online: bool, is_2d_features: bool, **override): \"\"\"Internal working of", "input_roi_strategy: types.InputRoiStrategy, optional describes how to display the features on", "init.\\n\" \\ \"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \" \\ \"for more details.\\n\" \\", "nonlinear random projections of X, of size self.n_components If input", "to be processed by the opu. decoder_cls: encoding.base.BaseTransformer, optional class", "it, or just vector dimensions, with `n_features`. When input is", "* sqrt(n_features)) elif self.rescale is OutputRescaling.norm: output = output /", "the opu back into the appropriate format. Returns ------- Y:", "is not None: utils.recurse_update(self.__opu_config, self.__config_override) return self.__opu_config @property def rescale(self):", "was found on this machine.\\n\" \\ \"You may want to", "= self._raw_linear_transform(X_enc, traits, user_input) # Decoding, add context, and optional", "__exit__(self, *args): # Don't close if OPU was already active", "deprecated, you must now use fit2d and transform\") def fit_transform1d(self,", "of this source code package. \"\"\" This module contains the", "into the appropriate format. Returns ------- Y: np.ndarray or torch.Tensor", "an indent block \"\"\" if self.device.active: return self.device.open() # initial", "Main methods are `transform`, `linear_transform`, `fit1d` and `fit2d`, and accept", "the context, re-add it to result afterwards start = time.time()", "lightonml.internal.config import get_host_option, opu_version from lightonml.internal import config, output_roi, utils,", "or rnd_mat.shape != (n_features, n_components): self._print(\"OPU: computing the random matrix...", "is part of this source code package. \"\"\" This module", "display Parameters ---------- X: np.ndarray or torch.Tensor a 2d input", "transform (`transform`) is a native operation for the OPU, and", "version.append(f\"lightonopu version {lightonopu.__version__}\") except ImportError: pass if devices: version.append(self.device.versions()) return", "= n_components self.input_roi_strategy = input_roi_strategy # Runner initialized when entering", "def __exit__(self, *args): # Don't close if OPU was already", "bar when verbose_level is set to 1 simulated: bool, optional", "self.config[\"input\"][\"frametime_us\"] exposure_us = self.config[\"output\"][\"exposure_us\"] seq_nb_prelim = self.config.get(\"sequence_nb_prelim\", 0) name =", "elif self.rescale is OutputRescaling.norm: output = output / (self._s.stdev *", "initiate or resize the random matrix device: OpuDevice or SimulatedOpuDevice", "n_2d_features=None, **override) -> ContextArray: \"\"\"Performs the nonlinear random projections of", "metadata \"\"\" assert self._runner, \"Call fit1d or fit2d before linear_transform\"", "\"\"\"Performs the nonlinear random projections of 1d input vector(s). This", "input user_input = OpuUserInput.from_input(X, packed, is_2d_features, n_features) tr_settings = self._tr_settings(no_input=False,", "X, packed: bool = False, **override) -> ContextArray: \"\"\"Performs the", "int): if self._s.simulated: self._resize_rnd_matrix(self.max_n_features, value) else: self.device.output_roi = self._output_roi.compute_roi(value) #", "set to True. When input vectors must be transformed one", "seealso:: `lightonml.types.OutputRescaling` Attributes ---------- n_components: int dimensionality of the target", "ContextArray: \"\"\"Performs the nonlinear random projections of 2d input vector(s).", "s\") # Restore the dimension after batch encoding to something", "vectors. The `fit1d` or `fit2d` method must be called before,", "If opu_device is of type SimulatedOpuDevice, the random matrix is", "the input, necessary if X parameter isn't provided, or if", "self.rescale = rescale # Get trace and print functions if", "by the OPU device.\"\"\" self.__active_before_enter = self.device.active self.open() return self", "entering fit self._runner = None # type: Optional[TransformRunner] # ExitStack", "the target projection space. opu_device : OpuDevice or SimulatedOpuDevice, optional", "of the config_file (for dev purpose) verbose_level: int, optional deprecated,", "types from lightonml.internal.user_input import OpuUserInput, InputTraits from lightonml.internal.simulated_device import SimulatedOpuDevice", "can't be set if device is real\") self._resize_rnd_matrix(value, self._n_components) self._max_n_features", "decoder_cls() else: decoder = decoder_cls output = decoder.transform(output) if user_input.is_tensor:", "self._tr_settings(no_input=False, **override) self._runner = FitTransformRunner(self._s, tr_settings, user_input, device=self.device, disable_pbar=self.disable_pbar) else:", "config_file : str, optional path to the configuration file (for", "random matrix if not done already self._resize_rnd_matrix(max_n_features, n_components) else: #", "X else: assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't do linear", "self.__config_override = config_override self._max_n_features = max_n_features self.disable_pbar = disable_pbar self.rescale", "# Instantiate device directly from lightonopu.internal.device import OpuDevice if not", "inspect.isclass(decoder_cls): if hasattr(encoder, \"get_params\"): decoder = decoder_cls(**encoder.get_params()) else: decoder =", "opu_device: if type(opu_device).__name__ not in [\"SimulatedOpuDevice\", \"OpuDevice\"]: raise TypeError(\"opu_device must", "numpy) X2 = user_input.reshape_input(raveled_features=True, leave_single_dim=True) try: import lightonopu.linear_reconstruction as reconstruction", "be either called with input vector, for fitting OPU parameters", "for 1d vectors The function can be either called with", "at each call. Performance impact is negligible\"\"\" # Get default", "self.device.frametime_us self._base_exposure_us = self.device.exposure_us if self._s.simulated: # build the random", "opened\") def close(self): \"\"\"Releases hardware resources used by the OPU", "of the progress bar when verbose_level is set to 1", "and start online acq if needs be. \"\"\" if X", "from lightonml.internal.settings import OpuSettings, TransformSettings from lightonml.internal.runner import TransformRunner, FitTransformRunner", "the internal configuration object\"\"\" # Load it when asked first", "seq_nb_prelim, None, verbose_level, name) self._base_frametime_us = self.device.frametime_us self._base_exposure_us = self.device.exposure_us", "lightonopu.internal.device import OpuDevice # noinspection PyPep8Naming class OPU: \"\"\"Interface to", "name) self._base_frametime_us = self.device.frametime_us self._base_exposure_us = self.device.exposure_us if self._s.simulated: #", "the features on the input device .. seealso:: `lightonml.internal.types.InputRoiStrategy` open_at_init:", "processing unit instance linked to a physical or simulated device.", "X=None, n_features: Tuple[int, int] = None, packed: bool = False,", "n_2d_features: list, tuple or np.ndarray of length 2 If the", "RuntimeError(\"Online transform isn't available with this OPU\") # Start acquisition", "closing at the end af an indent block \"\"\" if", "Restore logging functions removed at getstate self._debug = lightonml.get_debug_fn() self._trace", "int: return self._s.max_n_features @max_n_features.setter def max_n_features(self, value: int): if not", "transform isn't yet implemented for packed input :/\") if inspect.isclass(encoder_cls):", "in the transformation matrix. If tqdm module is available, it", "min_n_components is linked to the minimum output size min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0),", "verbose_level != -1: warnings.warn(\"Verbose level arg will removed in 1.3,", "`lightonml.internal.types.InputRoiStrategy` open_at_init: bool, optional forces the setting of acquiring hardware", "if traits.packed: # TODO implement for packed raise RuntimeError(\"Linear transform", "the features on the input device \"\"\" def __init__(self, n_components:", "time.time() prepared_X = reconstruction.encode_batch(X2) self._trace(f\"Encoding time {time.time() - start} s\")", "simulated and opu_device is not None: raise ValueError(\"simulated and opu_device", "return OpuSettings( max_n_features=int(np.prod(self.device.input_shape)), # Will use defaults of OpuSettings if", "fit_transform2d(self, X, packed: bool = False, n_2d_features=None, **override) -> ContextArray:", "if self._s.simulated: prepared_X = X else: assert self.device.acq_state.value != AcqState.online.value,", "self._trace(f\"Decoding time {time.time() - start} s\") result_ctx = ContextArray(result, rp_opu.context)", "issue, and take action if needed issue = utils.detect_trigger_issue(self.device) if", "be called before, for setting vector dimensions or online option.", "__fit(self, X, n_features: IntOrTuple, packed: bool, online: bool, is_2d_features: bool,", "output ROI self.n_components = n_components self.input_roi_strategy = input_roi_strategy # Runner", "TYPE_CHECKING import numpy as np from contextlib import ExitStack import", "end af an indent block \"\"\" if self.device.active: return self.device.open()", "None, verbose_level: int = -1, input_roi_strategy: types.InputRoiStrategy = types.InputRoiStrategy.full, open_at_init:", "**kwargs) def _resize_rnd_matrix(self, n_features: int, n_components: int): \"\"\"Resize device's random", "raise AttributeError(\"max_n_feature can't be set if device is real\") self._resize_rnd_matrix(value,", "tr_settings = self._tr_settings(no_input=True, **override) traits = InputTraits(n_features, packed) self._runner =", "OutputRescaling.variance: n_features = user_input.n_features_s output = output / (self._s.stdev *", "random matrix... \", end='', flush=True) self.device.build_random_matrix(n_features, n_components) self._print(\"OK\") def version(self,", "ContextArray, with a context attribute to add metadata \"\"\" assert", "OpuDevice(opu_type, frametime_us, exposure_us, seq_nb_prelim, None, verbose_level, name) self._base_frametime_us = self.device.frametime_us", "None: open_at_init = get_host_option(\"lightonml_open_at_init\", True) if open_at_init: self.open() def _tr_settings(self,", "full for linear_transform to be correct.\\n\" \\ \"Set input_roi_strategy attribute", "for setting vector dimensions or online option. If you need", "self._n_components = value @property def max_n_features(self) -> int: return self._s.max_n_features", "device's random matrix\"\"\" assert isinstance(self.device, SimulatedOpuDevice) rnd_mat = self.device.random_matrix if", "\\ \"Can't transform a batch of vectors when acquisition is\"", "can be 1d or 2d. In all cases ``output.shape[:-1] =", "user_input.unravel_features(prepared_X) # Run the OPU transform prepared_input = OpuUserInput.from_traits(prepared_X, traits)", "0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), # min_n_components is linked to the minimum output", "minimum output size min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0), ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\", 5), detect_trigger=self.config.get(\"detect_trigger_issue\", False),", "in online mode, only single vectors\" with self.device.acquiring(n_images=self._s.n_samples_by_pass): out =", "lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn() self._acq_stack = ExitStack()", "self.device.acq_state.value == AcqState.online.value self._acq_stack.close() # Device itself is closed on", "n_components rescale: types.OutputRescaling, optional, output rescaling method for `linear_transform`. Ignored", "# noinspection PyPep8Naming class OPU: \"\"\"Interface to the OPU. ..", "self.__opu_config: self.__opu_config = config.load_config(self.__config_file, self._trace) if self.__config_override is not None:", "Common settings to both simulated and base kwargs = {\"input_shape\":", "find configuration files raise RuntimeError(no_config_msg) opu_type = self.config[\"type\"] frametime_us =", "to True. Number of features must be then provided with", "auto by full strategy settings.input_roi_strategy = InputRoiStrategy.full assert settings.input_roi is", "= self._post_transform(result_ctx, user_input, encoder, decoder_cls) # Rescale the output, intentionally", "reconstruction.encode_batch(X2) self._trace(f\"Encoding time {time.time() - start} s\") # Restore the", "not self._s.simulated: # With batch input start acquisition first assert", "linear_transform\" traits = self._runner.traits if traits.packed: # TODO implement for", "OpuUserInput.from_input(X, packed, is_2d_features, n_features) tr_settings = self._tr_settings(no_input=False, **override) self._runner =", "verbose_level is set to 1 simulated: bool, optional performs the", "device \"\"\" def __init__(self, n_components: int = 200000, opu_device: Optional[Union[\"OpuDevice\",", "a context-manager interface. Unless `open_at_init=False`, these resources are acquired automatically", "version version.append(f\"lightonml version {lightonml.__version__}\") try: # noinspection PyUnresolvedReferences import lightonopu", "matrix. The input data can be bit-packed, where ``n_features =", "is None or rnd_mat.shape != (n_features, n_components): self._print(\"OPU: computing the", "uses X to compute it tr_settings = self._tr_settings(no_input=True, **override) traits", "utils.recurse_update(self.__opu_config, self.__config_override) return self.__opu_config @property def rescale(self): return self._rescale @rescale.setter", "encoder_cls() else: encoder = encoder_cls X_enc = encoder.transform(X) user_input =", "rescale: Union[OutputRescaling, str] = OutputRescaling.variance): self.__opu_config = None self.__config_file =", "self.rescale is OutputRescaling.norm: output = output / (self._s.stdev * sqrt(self.n_components))", "isn't provided packed: bool Set to true if the input", "for Nitro (non-linear) photonic cores. Parameters ---------- X: np.ndarray or", "lightonml.internal.types import InputRoiStrategy, IntOrTuple, TransformOutput, AcqState from lightonml.types import OutputRescaling", "200000, opu_device: Optional[Union[\"OpuDevice\", SimulatedOpuDevice]] = None, max_n_features: int = 1000,", "has not released the resources, an error will be raised,", "lightonml.encoding.base import NoEncoding, NoDecoding import warnings from typing import Optional,", "result_ctx def __enter__(self): \"\"\"Context manager interface that acquires hardware resources", "trigger issue, and take action if needed issue = utils.detect_trigger_issue(self.device)", "Rescale the output, intentionally after the decoding step if self.rescale", "at init. If not provided, follow system's setting (usually True)", "is_2d_features: bool, **override): \"\"\"Internal working of the fitXd calls Instantiates", "\"\"\" self.fit1d(X, None, packed, False, **override) return self.transform(X) def fit_transform2d(self,", "now numpy 2D, whatever the initial shape and the type", "self._output_roi.max_components @property def n_components(self) -> int: return self._n_components @n_components.setter def", "OPU, and performs at a higher speed than `linear_transform`. Acquiring/releasing", "own. self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod def _post_transform(output, user_input, encoder, decoder_cls): \"\"\"Final steps", "self.device.open() # initial reservation for giving batch transforms a buffer", "of features must be provided as n_2d_features defaults to False", "time from math import sqrt import pkg_resources from lightonml.encoding.base import", "never query self.config here, in order not to # need", "object to release it. Parameters ---------- n_components : int, dimensionality", "else: self._debug(\"trigger issue not detected\") self._debug(\"OPU opened\") def close(self): \"\"\"Releases", "random matrix is then generated at __init__, using max_n_features and", "# type: Optional[TransformRunner] # ExitStack for device acquisition, initialized when", "self._s.max_n_features @max_n_features.setter def max_n_features(self, value: int): if not self._s.simulated: raise", "# Build OPU name if not self._s.simulated: version.append(opu_version(self.__opu_config)) # module", "to # need a configuration file for simulated device return", "= False, **override) -> ContextArray: \"\"\"Performs the nonlinear random projections", "not to # need a configuration file for simulated device", "the output of the opu back into the appropriate format.", "at init, unless relevant host.json option is False if open_at_init", "# ExitStack for device acquisition, initialized when entering fit self._acq_stack", "= opu_device elif simulated: self.device = SimulatedOpuDevice() else: # Instantiate", "settings (advanced parameters) \"\"\" return self.__fit(X, n_features, packed, online, False,", "for packed raise RuntimeError(\"Linear transform isn't yet implemented for packed", "if needs be. \"\"\" if X is not None: #", "applied\") else: self._debug(\"trigger issue not detected\") self._debug(\"OPU opened\") def close(self):", "system's setting (usually True) disable_pbar: bool, optional disable display of", "self._runner, \"Call fit1d or fit2d before linear_transform\" traits = self._runner.traits", "online: if self._s.no_single_transform: raise RuntimeError(\"Online transform isn't available with this", "If input is an ndarray, type is actually ContextArray, with", "or take the one passed as input if opu_device: if", "If the input is bit-packed, specifies the shape of each", "math import sqrt import pkg_resources from lightonml.encoding.base import NoEncoding, NoDecoding", "disable_pbar=False, simulated=False, rescale: Union[OutputRescaling, str] = OutputRescaling.variance): self.__opu_config = None", "issue = utils.detect_trigger_issue(self.device) if issue: # noinspection PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim =", "file (for dev purpose) config_override: dict, optional for override of", "OutputRescaling.norm: output = output / (self._s.stdev * sqrt(self.n_components)) return output", "TransformOutput, AcqState from lightonml.types import OutputRescaling # Import lightonopu only", "s\") result_ctx = ContextArray(result, rp_opu.context) return rp_opu, result_ctx def __enter__(self):", "dev purpose) verbose_level: int, optional deprecated, use lightonml.set_verbose_level() instead ..", "of length 2 If the input is bit-packed, specifies the", "if not self.__active_before_enter: self.close() def open(self): \"\"\"Acquires hardware resources used", "= \"\", config_override: dict = None, verbose_level: int = -1,", "settings (advanced parameters) \"\"\" return self.__fit(X, n_features, packed, online, True,", "in order not to # need a configuration file for", "size self.n_components If input is an ndarray, type is actually", "devices=False): \"\"\"Returns a multi-line string containing name and versions of", "be made on this vector to optimize transform parameters n_features:", "raise RuntimeError(\"transform1d is deprecated, you must now use fit1d and", ".. warning:: when making several transform calls, prefer calling `fit2d`", "TransformOutput: \"\"\" Do a linear transform of X, for Nitro", "In all cases ``output.shape[:-1] = X.shape[:-1]`` packed: bool, optional whether", "type: Optional[TransformRunner] # ExitStack for device acquisition, initialized when entering", "vector dimensions, with `n_features`. When input is bit-packed the packed", "X, n_features: IntOrTuple, packed: bool, online: bool, is_2d_features: bool, **override):", "random projections of 2d input vector(s). This function is the", "need a configuration file for simulated device return OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default,", "by `transform`. .. seealso:: `lightonml.types.OutputRescaling` Attributes ---------- n_components: int dimensionality", "opu_device is a SimulatedOpuDevice, in order to initiate or resize", "data is in bit-packed representation if True, each input vector", "False, **override) return self.transform(X) def fit_transform2d(self, X, packed: bool =", "as input if opu_device: if type(opu_device).__name__ not in [\"SimulatedOpuDevice\", \"OpuDevice\"]:", "be. \"\"\" if X is not None: # Input is", "needed output = self._post_transform(result_ctx, user_input, encoder, decoder_cls) # Rescale the", "in a tuple \"\"\" if traits is None: assert self._runner,", "fit1d and transform\") def transform2d(self, *args, **kwargs): raise RuntimeError(\"transform2d is", "= input_roi_strategy # Runner initialized when entering fit self._runner =", "performance will be improved with the online flag set to", "packed, False, **override) return self.transform(X) def __fit(self, X, n_features: IntOrTuple,", "if not self.__config_file and not config.host_has_opu_config(): # Looks like there's", "init if inspect.isclass(decoder_cls): if hasattr(encoder, \"get_params\"): decoder = decoder_cls(**encoder.get_params()) else:", "ExitStack import attr import inspect import lightonml from lightonml.internal.config import", "decoder = decoder_cls() else: decoder = decoder_cls output = decoder.transform(output)", "def max_n_features(self) -> int: return self._s.max_n_features @max_n_features.setter def max_n_features(self, value:", "vectors The function can be either called with input vector,", "the packed flag must be set to True. When input", "use self.device.reserve(self._s.n_samples_by_pass) if self._s.detect_trigger: # Detect trigger issue, and take", "a higher speed than `linear_transform`. Acquiring/releasing hardware device resources is", "value pass_default = attr.fields(OpuSettings).n_samples_by_pass.default # Common settings to both simulated", "self._s.simulated: state[\"__online_acq\"] = self.device.acq_state.value == AcqState.online.value self._acq_stack.close() # Device itself", "self.device.output_roi_strategy, self._s.allowed_roi, self._s.min_n_components) # This also sets the output ROI", "# Will use defaults of OpuSettings if not found n_samples_by_pass=self.config.get(\"n_samples_by_pass\",", "self.n_components = n_components self.input_roi_strategy = input_roi_strategy # Runner initialized when", "a TransformRunner, and start online acq if needs be. \"\"\"", "name = self.config[\"name\"] self.device = OpuDevice(opu_type, frametime_us, exposure_us, seq_nb_prelim, None,", "__enter__(self): \"\"\"Context manager interface that acquires hardware resources used by", "pass if devices: version.append(self.device.versions()) return '\\n'.join(version) def __getstate__(self): state =", "= self.device.active self.open() return self def __exit__(self, *args): # Don't", "resources are acquired automatically at init. If another process or", "format. Returns ------- Y: np.ndarray or torch.Tensor complete array of", "False n_2d_features: list, tuple or np.ndarray of length 2 If", "input vector, or batch of 2d input_vectors, binary encoded, packed", "(advanced parameters) \"\"\" return self.__fit(X, n_features, packed, online, False, **override)", "import OpuSettings, TransformSettings from lightonml.internal.runner import TransformRunner, FitTransformRunner from lightonml.internal.types", "an optional module and may not be present if TYPE_CHECKING:", "of type SimulatedOpuDevice or OpuDevice\") self.device = opu_device elif simulated:", "online: bool, optional Set to true if the transforms will", "warning:: when making several transform calls, prefer calling `fit1d` and", "features that the OPU will transform used only if opu_device", "= encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, traits) _, result_ctx = self._raw_linear_transform(X_enc,", "If no input_roi, replace auto by full strategy settings.input_roi_strategy =", "n_features: IntOrTuple, packed: bool, online: bool, is_2d_features: bool, **override): \"\"\"Internal", "disable_pbar=self.disable_pbar) self._acq_stack.close() if online: if self._s.no_single_transform: raise RuntimeError(\"Online transform isn't", "time {time.time() - start} s\") result_ctx = ContextArray(result, rp_opu.context) return", "provided as n_features defaults to False online: bool, optional Set", "None, verbose_level, name) self._base_frametime_us = self.device.frametime_us self._base_exposure_us = self.device.exposure_us if", "\"ROI strategy must be full for linear_transform to be correct.\\n\"", "OPU was already active if not self.__active_before_enter: self.close() def open(self):", "reconstruction except ImportError: raise RuntimeError(\"Need a lightonopu version with linear_reconstruction", "end='', flush=True) self.device.build_random_matrix(n_features, n_components) self._print(\"OK\") def version(self, devices=False): \"\"\"Returns a", "instead\", DeprecationWarning) lightonml.set_verbose_level(verbose_level) else: verbose_level = lightonml.get_verbose_level() self._debug = lightonml.get_debug_fn()", "max_n_features=int(np.prod(self.device.input_shape)), # Will use defaults of OpuSettings if not found", ".. warning:: when making several transform calls, prefer calling `fit1d`", "Settings are immutable (attrs frozen), so generate it at each", "---------- X: np.ndarray or torch.Tensor Fit will be made on", "self._rescale @rescale.setter def rescale(self, value): # If str it's the", "target projection space. rescale: types.OutputRescaling, output rescaling method for `linear_transform`.", "Otherwise ``n_features = X.shape[-1]`` If tqdm module is available, it", "pkg_resources from lightonml.encoding.base import NoEncoding, NoDecoding import warnings from typing", "# Get trace and print functions if verbose_level != -1:", "-> ContextArray: \"\"\"Performs the nonlinear random projections of 1d input", "each call. Performance impact is negligible\"\"\" # Get default value", "`close()` or use the context manager interface for closing at", "transform isn't available with this OPU\") # Start acquisition only", "n_2d_features, packed, False, **override) return self.transform(X) def __fit(self, X, n_features:", "seealso:: `close()` or use the context manager interface for closing", "= OpuUserInput.from_input(X, packed, is_2d_features, n_features) tr_settings = self._tr_settings(no_input=False, **override) self._runner", "from lightonml.internal.simulated_device import SimulatedOpuDevice from lightonml.context import ContextArray from lightonml.internal.settings", "**override) return self.transform(X) def __fit(self, X, n_features: IntOrTuple, packed: bool,", "None self.__config_file = config_file self.__config_override = config_override self._max_n_features = max_n_features", "the dimension after batch encoding to something suitable for formatting", "Instantiates a TransformRunner, and start online acq if needs be.", "PyPep8Naming class OPU: \"\"\"Interface to the OPU. .. math:: \\\\mathbf{y}", "def _tr_settings(self, no_input=False, **override) -> TransformSettings: \"\"\"Returns transform settings for", "close if OPU was already active if not self.__active_before_enter: self.close()", "version {lightonml.__version__}\") try: # noinspection PyUnresolvedReferences import lightonopu version.append(f\"lightonopu version", "np.ndarray or torch.Tensor a 2d input vector, or batch of", "as the one given in `fit1d` or `fit2d`. encoder_cls: encoder.base.BaseTransformer,", "_s(self) -> OpuSettings: \"\"\"Returns immutable settings associated with the OPU", "matrix is then generated at __init__, using max_n_features and n_components", "hardware resources used by the OPU device\"\"\" self._acq_stack.close() self.device.close() self._debug(\"OPU", "tqdm module is available, it is used for progress display", "InputRoiStrategy.full.\" # X2 is now numpy 2D, whatever the initial", "online=False, **override): \"\"\" Configure OPU transform for 1d vectors The", "OpuDevice if not self.__config_file and not config.host_has_opu_config(): # Looks like", "function is the one-liner equivalent of `fit2d` and `transform` calls.", "flag must be set to True. Number of features must", "to compute it tr_settings = self._tr_settings(no_input=True, **override) traits = InputTraits(n_features,", "hardware resources used by the OPU device .. seealso:: `close()`", "fit2d(self, X=None, n_features: Tuple[int, int] = None, packed: bool =", "purpose) verbose_level: int, optional deprecated, use lightonml.set_verbose_level() instead .. seealso::", "packed: bool, optional whether the input data is in bit-packed", "packed: bool = False, **override) -> ContextArray: \"\"\"Performs the nonlinear", "to False override: keyword args for overriding transform settings (advanced", "torch.from_numpy(output) else: return output def _raw_linear_transform(self, X, traits=None, user_input=None): \"\"\"", "if not self.__opu_config: self.__opu_config = config.load_config(self.__config_file, self._trace) if self.__config_override is", "input_roi_strategy # Runner initialized when entering fit self._runner = None", "a batch of vectors when acquisition is\" \\ \" in", "no fitting happens on input assert n_features, \"either input vector", "# X2 is now numpy 2D, whatever the initial shape", "self._tr_settings(no_input=True, **override) traits = InputTraits(n_features, packed) self._runner = TransformRunner(self._s, tr_settings,", "def transform2d(self, *args, **kwargs): raise RuntimeError(\"transform2d is deprecated, you must", "transform settings (advanced parameters) \"\"\" return self.__fit(X, n_features, packed, online,", "space. rescale: types.OutputRescaling, output rescaling method for `linear_transform`. Ignored by", "device: OpuDevice or SimulatedOpuDevice underlying hardware that performs transformation (read-only)", "random projections of 1d input vector(s). This function is the", "OPU transform for 2d vectors The function can be either", "------- Y: np.ndarray or torch.Tensor complete array of nonlinear random", "opu_device is of type SimulatedOpuDevice, the random matrix is generated", "= ExitStack() # Restore online acquisition if it was the", "case no OPU is available on your machine the random", "input vector or n_features must be specified\" # tr_settings has", "parameter isn't provided packed: bool Set to true if the", "can be bit-packed, where ``n_features = 8*X.shape[-1]`` Otherwise ``n_features =", "self._s.simulated: prepared_X = X else: assert self.device.acq_state.value != AcqState.online.value, \\", "or fit2d before linear_transform\" traits = self._runner.traits if user_input is", "is_2d_features, n_features) tr_settings = self._tr_settings(no_input=False, **override) self._runner = FitTransformRunner(self._s, tr_settings,", "transform when acquisition is\" \\ \" in online mode, only", "self._debug(\"OPU opened\") def close(self): \"\"\"Releases hardware resources used by the", "n_components) else: # Make sure lightonopu is at 1.4.1 or", "we never query self.config here, in order not to #", "noinspection PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim = 1 self._debug(\"trigger issue detected, workaround applied\")", "input_vectors, binary encoded, packed or not batch can be 1d", "X, and return both raw OPU output and decoded output", "inconsistency in the transformation matrix. The input data can be", "moved to device.acquiring() self._n_components = value @property def max_n_features(self) ->", "or `fit2d`. encoder_cls: encoder.base.BaseTransformer, optional class or instance of class", "X, for Nitro (non-linear) photonic cores. Parameters ---------- X: np.ndarray", "# Rescale the output, intentionally after the decoding step if", "internal configuration object\"\"\" # Load it when asked first time", "full strategy settings.input_roi_strategy = InputRoiStrategy.full assert settings.input_roi is None return", "a simulated manner, by passing the \" \\ \"simulated argument", "= InputRoiStrategy.full assert settings.input_roi is None return settings def fit1d(self,", "be then provided with `n_features` When input vectors must be", "size min_n_components=self.config[\"output\"].get(\"minimum_output_size\", 0), ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\", 5), detect_trigger=self.config.get(\"detect_trigger_issue\", False), no_single_transform=self.config.get(\"no_single_transform\", False),", "return settings def fit1d(self, X=None, n_features: int = None, packed:", "Batch transform start their own. self._acq_stack.enter_context(self.device.acquiring(online=True)) @staticmethod def _post_transform(output, user_input,", "conflicting\") # Device init, or take the one passed as", "the output ROI self.n_components = n_components self.input_roi_strategy = input_roi_strategy #", "bool, is_2d_features: bool, **override): \"\"\"Internal working of the fitXd calls", "# tr_settings has no input_roi, since it uses X to", "for giving batch transforms a buffer ready to use self.device.reserve(self._s.n_samples_by_pass)", "input into binary vectors to be processed by the opu.", "X to compute it tr_settings = self._tr_settings(no_input=True, **override) traits =", "or PyTorch tensors. The non-linear transform (`transform`) is a native", "`fit2d` method must be called before, for setting vector dimensions", "device. If not provided, a device is properly instantiated. If", "encoder.base.BaseTransformer, optional class or instance of class that transform the", "as reconstruction except ImportError: raise RuntimeError(\"Need a lightonopu version with", "not self.__config_file and not config.host_has_opu_config(): # Looks like there's no", "= lightonml.get_print_fn() no_config_msg = \"No configuration files for the OPU", "matrix device: OpuDevice or SimulatedOpuDevice underlying hardware that performs transformation", "provided, do the fit with user input user_input = OpuUserInput.from_input(X,", "only single vectors\" assert self._runner.t.input_roi_strategy == InputRoiStrategy.full, \\ \"ROI strategy", "if user_input.is_tensor: # noinspection PyPackageRequirements,PyUnresolvedReferences import torch return torch.from_numpy(output) else:", "n_components : int, dimensionality of the target projection space. opu_device", "option is False if open_at_init is None: open_at_init = get_host_option(\"lightonml_open_at_init\",", "transmitting it to decoder init if inspect.isclass(decoder_cls): if hasattr(encoder, \"get_params\"):", "if simulated and opu_device is not None: raise ValueError(\"simulated and", "np.ndarray or torch.Tensor Fit will be made on this vector", "(for dev purpose) verbose_level: int, optional deprecated, use lightonml.set_verbose_level() instead", "Y: np.ndarray or torch.Tensor complete array of nonlinear random projections", "class OPU: \"\"\"Interface to the OPU. .. math:: \\\\mathbf{y} =", "X parameter isn't provided packed: bool Set to true if", "@property def n_components(self) -> int: return self._n_components @n_components.setter def n_components(self,", "= user_input.reshape_input(raveled_features=True, leave_single_dim=True) try: import lightonopu.linear_reconstruction as reconstruction except ImportError:", "bit-packed representation if True, each input vector is assumed to", ") return OpuSettings( max_n_features=int(np.prod(self.device.input_shape)), # Will use defaults of OpuSettings", "a native operation for the OPU, and performs at a", "be present if TYPE_CHECKING: from lightonopu.internal.device import OpuDevice # noinspection", "None: raise ValueError(\"simulated and opu_device arguments are conflicting\") # Device", "output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy, self._s.allowed_roi, self._s.min_n_components) # This also sets the output", "self._runner, \"Call fit1d or fit2d before transform\" assert self.device.active, \"OPU", "elif simulated: self.device = SimulatedOpuDevice() else: # Instantiate device directly", "physical or simulated device. If not provided, a device is", "get_host_option, opu_version from lightonml.internal import config, output_roi, utils, types from", "is the one-liner equivalent of `fit1d` and `transform` calls. ..", ": int, dimensionality of the target projection space. opu_device :", "`online=True` in the fit function. Parameters ---------- X: np.ndarray or", "released the resources, an error will be raised, call `close()`", "out = self._runner.transform(user_input) return self._post_transform(out, user_input, encoder, decoder_cls) def linear_transform(self,", "call. Performance impact is negligible\"\"\" # Get default value pass_default", "actually ContextArray, with a context attribute to add metadata \"\"\"", "with a context attribute to add metadata \"\"\" self.fit2d(X, n_2d_features,", "`linear_transform`. Acquiring/releasing hardware device resources is done by open/close and", "is available, it is used for progress display Parameters ----------", "that the OPU will transform writeable only if opu_device is", "= self.device.exposure_us if self._s.simulated: # build the random matrix if", "build the random matrix if not done already self._resize_rnd_matrix(max_n_features, n_components)", "= lightonml.get_trace_fn() self._print = lightonml.get_print_fn() self._acq_stack = ExitStack() # Restore", "FitTransformRunner(self._s, tr_settings, user_input, device=self.device, disable_pbar=self.disable_pbar) else: # Only dimensions are", "traits = InputTraits(n_features, packed) self._runner = TransformRunner(self._s, tr_settings, traits, device=self.device,", "as n_features defaults to False online: bool, optional Set to", "self def __exit__(self, *args): # Don't close if OPU was", "self._trace(\"OPU initialized\") # Open at init, unless relevant host.json option", "projections of one or several input vectors. The `fit1d` or", "be of type SimulatedOpuDevice or OpuDevice\") self.device = opu_device elif", "nonlinear random projections of 1d input vector(s). This function is", "int = 200000, opu_device: Optional[Union[\"OpuDevice\", SimulatedOpuDevice]] = None, max_n_features: int", "= None, max_n_features: int = 1000, config_file: str = \"\",", "another process or kernel has not released the resources, an", "the random projection using CPU, in case no OPU is", "raise RuntimeError(\"Online transform isn't available with this OPU\") # Start", "host.json option is False if open_at_init is None: open_at_init =", "traits) start = time.time() with self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu = self._runner.transform(prepared_input, linear=True)", "\"\"\" Performs the nonlinear random projections of one or several", "module version version.append(f\"lightonml version {lightonml.__version__}\") try: # noinspection PyUnresolvedReferences import", "and `fit2d`, and accept NumPy arrays or PyTorch tensors. The", "config_override: dict = None, verbose_level: int = -1, input_roi_strategy: types.InputRoiStrategy", "the online flag set to True. Parameters ---------- X: np.ndarray", "set to 1 simulated: bool, optional performs the random projection", "set to True. Parameters ---------- X: np.ndarray or torch.Tensor Fit", "no input_roi, since it uses X to compute it tr_settings", "RuntimeError(\"Need a lightonopu version with linear_reconstruction module\") start = time.time()", "= FitTransformRunner(self._s, tr_settings, user_input, device=self.device, disable_pbar=self.disable_pbar) else: # Only dimensions", "= [] # Build OPU name if not self._s.simulated: version.append(opu_version(self.__opu_config))", "closed\") @property def config(self): \"\"\"Returns the internal configuration object\"\"\" #", "\"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU \" \\ \"for more details.\\n\" \\ \"See also", "output and decoded output in a tuple \"\"\" if traits", "Rights Reserved. # This file is subject to the terms", "= max_n_features self.disable_pbar = disable_pbar self.rescale = rescale # Get", "lightonml.internal.simulated_device import SimulatedOpuDevice from lightonml.context import ContextArray from lightonml.internal.settings import", "InputRoiStrategy.full assert settings.input_roi is None return settings def fit1d(self, X=None,", "\"\", config_override: dict = None, verbose_level: int = -1, input_roi_strategy:", "features must be provided as n_2d_features defaults to False n_2d_features:", "self._base_frametime_us, \"exposure_us\": self._base_exposure_us} if isinstance(self.device, SimulatedOpuDevice): # Notice we never", "# Device init, or take the one passed as input", "the fit with user input user_input = OpuUserInput.from_input(X, packed, is_2d_features,", "def close(self): \"\"\"Releases hardware resources used by the OPU device\"\"\"", "SimulatedOpuDevice): # Notice we never query self.config here, in order", "n_features: int Number of features for the input, necessary if", "\"get_params\"): decoder = decoder_cls(**encoder.get_params()) else: decoder = decoder_cls() else: decoder", "encoded, packed or not n_features: tuple(int) Number of features for", "processed by the opu. decoder_cls: encoding.base.BaseTransformer, optional class or instance", "2d input vector(s). This function is the one-liner equivalent of", "override of the config_file (for dev purpose) verbose_level: int, optional", "rescale: types.OutputRescaling, output rescaling method for `linear_transform`. Ignored by `transform`.", "defaults to False override: keyword args for overriding transform settings", "init. If another process or kernel has not released the", "encoder = encoder_cls() else: encoder = encoder_cls X_enc = encoder.transform(X)", "else: assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't do linear transform", "else: encoder = encoder_cls X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc,", "first assert self.device.acq_state.value != AcqState.online.value, \\ \"Can't transform a batch", "purpose) config_override: dict, optional for override of the config_file (for", "\"\"\"Internal working of the fitXd calls Instantiates a TransformRunner, and", "Will use defaults of OpuSettings if not found n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default),", "-> TransformOutput: \"\"\" Do a linear transform of X, for", "True. When input vectors must be transformed one by one,", "interface for closing at the end af an indent block", "When input vectors must be transformed one by one, performance", "vectors will be already bit-packed online: bool, optional Set to", "that performs transformation (read-only) input_roi_strategy: types.InputRoiStrategy, optional describes how to", "def __setstate__(self, state): self.__dict__.update(state) # Restore logging functions removed at", "be restored state.pop(\"_acq_stack\") # If acquisition is ongoing, close it", "transformation matrix. The input data can be bit-packed, where ``n_features", "**kwargs ) return OpuSettings( max_n_features=int(np.prod(self.device.input_shape)), # Will use defaults of", "feeding to TransformRunner\"\"\" init = TransformSettings(self.input_roi_strategy, self.n_components) settings = attr.evolve(init,", "list, tuple or np.ndarray of length 2 If the input", "def _raw_linear_transform(self, X, traits=None, user_input=None): \"\"\" Do linear_transform of X,", "opu back into the appropriate format. Returns ------- Y: np.ndarray", "then generated at __init__, using max_n_features and n_components rescale: types.OutputRescaling,", "acquisition is ongoing, close it if not self._s.simulated: state[\"__online_acq\"] =", "\\ \"simulated argument to True at init.\\n\" \\ \"See https://docs.lighton.ai/notes/get_started.html#Simulating-an-OPU", "set to True. Number of features must be then provided", "return self def __exit__(self, *args): # Don't close if OPU", "(`transform`) is a native operation for the OPU, and performs", "= config_override self._max_n_features = max_n_features self.disable_pbar = disable_pbar self.rescale =", "and return both raw OPU output and decoded output in", "AcqState from lightonml.types import OutputRescaling # Import lightonopu only for", "max_n_features: int, optional maximum number of binary features that the", "projection using CPU, in case no OPU is available on", "-1: warnings.warn(\"Verbose level arg will removed in 1.3, \" \"Use", "self._debug(str(user_input)) if user_input.is_batch and not self._s.simulated: # With batch input", "fit with user input user_input = OpuUserInput.from_input(X, packed, is_2d_features, n_features)", "bit-packed the packed flag must be set to True. When", "= None, packed: bool = False, online=False, **override): \"\"\" Configure", "to tensor if user input was tensor \"\"\" output =", "version {lightonopu.__version__}\") except ImportError: pass if devices: version.append(self.device.versions()) return '\\n'.join(version)", "isn't active, use opu.open() or \\\"with opu:\\\"\" if inspect.isclass(encoder_cls): encoder", "input vector(s). This function is the one-liner equivalent of `fit2d`", "correct.\\n\" \\ \"Set input_roi_strategy attribute to InputRoiStrategy.full.\" # X2 is", "`fit1d` or `fit2d`. encoder_cls: encoding.base.BaseTransformer, optional class or instance of", "to False online: bool, optional Set to true if the", "acquired automatically at init. If another process or kernel has", "at a higher speed than `linear_transform`. Acquiring/releasing hardware device resources", "# module version version.append(f\"lightonml version {lightonml.__version__}\") try: # noinspection PyUnresolvedReferences", "None: utils.recurse_update(self.__opu_config, self.__config_override) return self.__opu_config @property def rescale(self): return self._rescale", "user_input, encoder, decoder_cls): \"\"\"Final steps after transform 1. reshape 2.", "state.pop(\"_trace\") state.pop(\"_print\") # acq stack can't be pickled, will be", "class that transform the input into binary vectors to be", "import attr import inspect import lightonml from lightonml.internal.config import get_host_option,", "return self._output_roi.max_components @property def n_components(self) -> int: return self._n_components @n_components.setter", "# build the random matrix if not done already self._resize_rnd_matrix(max_n_features,", ".. seealso:: `lightonml.internal.types.InputRoiStrategy` open_at_init: bool, optional forces the setting of", "not self._s.simulated: version.append(opu_version(self.__opu_config)) # module version version.append(f\"lightonml version {lightonml.__version__}\") try:", "decode the output 3. convert to tensor if user input", "TYPE_CHECKING: from lightonopu.internal.device import OpuDevice # noinspection PyPep8Naming class OPU:", "version.append(self.device.versions()) return '\\n'.join(version) def __getstate__(self): state = self.__dict__.copy() # Remove", "the random matrix device: OpuDevice or SimulatedOpuDevice underlying hardware that", "initial shape and the type (torch or numpy) X2 =", "method, it's for transmitting it to decoder init if inspect.isclass(decoder_cls):", "active, use opu.open() or \\\"with opu:\\\"\" if inspect.isclass(encoder_cls): encoder =", "found n_samples_by_pass=self.config.get(\"n_samples_by_pass\", pass_default), min_batch_size=self.config[\"input\"].get(\"minimum_batch_size\", 0), allowed_roi=self.config[\"output\"].get(\"allowed_roi\"), # min_n_components is linked", "or OpuDevice\") self.device = opu_device elif simulated: self.device = SimulatedOpuDevice()", "batch of 1d input_vectors, binary encoded, packed or not batch", "do the fit with user input user_input = OpuUserInput.from_input(X, packed,", "SimulatedOpuDevice() else: # Instantiate device directly from lightonopu.internal.device import OpuDevice", "self._print = lightonml.get_print_fn() no_config_msg = \"No configuration files for the", "\\ \"You may want to run the OPU in a", "`lightonml.set_verbose_level` input_roi_strategy: types.InputRoiStrategy, optional describes how to display the features", "be set to True. When input vectors must be transformed", "raw OPU output and decoded output in a tuple \"\"\"", "raise RuntimeError(\"Need a lightonopu version with linear_reconstruction module\") start =", "type SimulatedOpuDevice, the random matrix is generated at __init__, using", "if open_at_init is None: open_at_init = get_host_option(\"lightonml_open_at_init\", True) if open_at_init:", "tr_settings has no input_roi, since it uses X to compute", "try: # noinspection PyUnresolvedReferences import lightonopu version.append(f\"lightonopu version {lightonopu.__version__}\") except", "result_ctx = ContextArray(result, rp_opu.context) return rp_opu, result_ctx def __enter__(self): \"\"\"Context", "assert settings.input_roi is None return settings def fit1d(self, X=None, n_features:", "transforms a buffer ready to use self.device.reserve(self._s.n_samples_by_pass) if self._s.detect_trigger: #", "module\") start = time.time() prepared_X = reconstruction.encode_batch(X2) self._trace(f\"Encoding time {time.time()", "Build OPU name if not self._s.simulated: version.append(opu_version(self.__opu_config)) # module version", "DeprecationWarning) lightonml.set_verbose_level(verbose_level) else: verbose_level = lightonml.get_verbose_level() self._debug = lightonml.get_debug_fn() self._trace", "If str it's the enum value if isinstance(value, str): self._rescale", "= lightonml.get_verbose_level() self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print =", "type(opu_device).__name__ not in [\"SimulatedOpuDevice\", \"OpuDevice\"]: raise TypeError(\"opu_device must be of", "random projection using CPU, in case no OPU is available", "or not packed: bool, optional whether the input data is", "several transform calls, prefer calling `fit2d` and then `transform`, or", "is InputRoiStrategy.auto: # If no input_roi, replace auto by full", "output rescaling method for `linear_transform`. Ignored by `transform`. .. seealso::", "to optimize transform parameters n_features: int Number of features for", "= False, online=False, **override): \"\"\" Configure OPU transform for 1d", "= decoder_cls output = decoder.transform(output) if user_input.is_tensor: # noinspection PyPackageRequirements,PyUnresolvedReferences", "True. Number of features must be then provided with `n_features`", "lightonopu import linear_reconstruction linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi = output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy, self._s.allowed_roi, self._s.min_n_components)", "simulated device return OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default, simulated=True, **kwargs ) return OpuSettings(", "optional deprecated, use lightonml.set_verbose_level() instead .. seealso:: `lightonml.set_verbose_level` input_roi_strategy: types.InputRoiStrategy,", "\"\"\" assert self._runner, \"Call fit1d or fit2d before linear_transform\" traits", "if the input isn't bit-packed. override: keyword args for overriding", "linear_reconstruction.init(np.prod(self.device.input_shape)) self._output_roi = output_roi.OutputRoi(self.device.output_shape_max, self.device.output_roi_strategy, self._s.allowed_roi, self._s.min_n_components) # This also", "def transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Performs the", "(for dev purpose) config_override: dict, optional for override of the", "the OPU, and performs at a higher speed than `linear_transform`.", "the type (torch or numpy) X2 = user_input.reshape_input(raveled_features=True, leave_single_dim=True) try:", "acquisition, initialized when entering fit self._acq_stack = ExitStack() self._trace(\"OPU initialized\")", "functions if verbose_level != -1: warnings.warn(\"Verbose level arg will removed", "buffer ready to use self.device.reserve(self._s.n_samples_by_pass) if self._s.detect_trigger: # Detect trigger", "at getstate self._debug = lightonml.get_debug_fn() self._trace = lightonml.get_trace_fn() self._print =", "opu_device arguments are conflicting\") # Device init, or take the", "@property def rescale(self): return self._rescale @rescale.setter def rescale(self, value): #", "one-liner equivalent of `fit2d` and `transform` calls. .. warning:: when", "AcqState.online.value self._acq_stack.close() # Device itself is closed on pickling return", "use the context manager interface for closing at the end", "so generate it at each call. Performance impact is negligible\"\"\"", "from lightonopu.internal.device import OpuDevice if not self.__config_file and not config.host_has_opu_config():", "`linear_transform`. Ignored by `transform`. .. seealso:: `lightonml.types.OutputRescaling` Attributes ---------- n_components:", "hardware resources used by the OPU device.\"\"\" self.__active_before_enter = self.device.active", "int): \"\"\"Resize device's random matrix\"\"\" assert isinstance(self.device, SimulatedOpuDevice) rnd_mat =", "is a SimulatedOpuDevice, in order to initiate the random matrix", "level arg will removed in 1.3, \" \"Use lightonml.set_verbose_level instead\",", "online mode, only single vectors\" with self.device.acquiring(n_images=self._s.n_samples_by_pass): out = self._runner.transform(user_input)", "making several transform calls, prefer calling `fit1d` and then `transform`,", "(n_features, n_components): self._print(\"OPU: computing the random matrix... \", end='', flush=True)", "ValueError(\"simulated and opu_device arguments are conflicting\") # Device init, or", "of vectors when acquisition is\" \\ \" in online mode,", "will be made one vector after the other defaults to", "be transformed one by one, performance will be improved with", "settings = attr.evolve(init, **override) if no_input and self.input_roi_strategy is InputRoiStrategy.auto:", "opu_version from lightonml.internal import config, output_roi, utils, types from lightonml.internal.user_input", "as we didn't find configuration files raise RuntimeError(no_config_msg) opu_type =", "def n_components(self, value: int): if self._s.simulated: self._resize_rnd_matrix(self.max_n_features, value) else: self.device.output_roi", "bit-packed packed: bool, optional whether the input data is in", "initial reservation for giving batch transforms a buffer ready to", "torch.Tensor complete array of nonlinear random projections of X, of", "SimulatedOpuDevice or OpuDevice\") self.device = opu_device elif simulated: self.device =", "decoder.transform(output) if user_input.is_tensor: # noinspection PyPackageRequirements,PyUnresolvedReferences import torch return torch.from_numpy(output)", "with self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu = self._runner.transform(prepared_input, linear=True) self._trace(f\"Transform time {time.time() -", "to release it. Parameters ---------- n_components : int, dimensionality of", "dimensionality of the target projection space. opu_device : OpuDevice or", "settings (advanced parameters) Returns ------- Y: np.ndarray or torch.Tensor complete", "in order to initiate the random matrix config_file : str,", "self.device = opu_device elif simulated: self.device = SimulatedOpuDevice() else: #", "self.device.random_matrix if rnd_mat is None or rnd_mat.shape != (n_features, n_components):", "3. convert to tensor if user input was tensor \"\"\"", "self._s.simulated: version.append(opu_version(self.__opu_config)) # module version version.append(f\"lightonml version {lightonml.__version__}\") try: #", "transform(self, X, encoder_cls=NoEncoding, decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Performs the nonlinear", "1d input vector(s). This function is the one-liner equivalent of", "when entering fit self._acq_stack = ExitStack() self._trace(\"OPU initialized\") # Open", "if input is bit-packed packed: bool, optional whether the input", "The input data can be bit-packed, where ``n_features = 8*X.shape[-1]``", "in `fit1d` or `fit2d`. encoder_cls: encoding.base.BaseTransformer, optional class or instance", "initialized when entering fit self._acq_stack = ExitStack() self._trace(\"OPU initialized\") #", "matrix is generated at __init__, using max_n_features and n_components max_n_features:", "\"\"\"Resize device's random matrix\"\"\" assert isinstance(self.device, SimulatedOpuDevice) rnd_mat = self.device.random_matrix", "self._acq_stack.close() if online: if self._s.no_single_transform: raise RuntimeError(\"Online transform isn't available", "assumed to be a 1d array, and the \"real\" number", "into binary vectors to be processed by the opu. decoder_cls:", "transform calls, prefer calling `fit2d` and then `transform`, or you", "trace and print functions if verbose_level != -1: warnings.warn(\"Verbose level", "OpuUserInput.from_traits(prepared_X, traits) start = time.time() with self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu = self._runner.transform(prepared_input,", "something suitable for formatting prepared_X = user_input.unravel_features(prepared_X) # Run the", "not packed: bool, optional whether the input data is in", "def fit1d(self, X=None, n_features: int = None, packed: bool =", "= self._tr_settings(no_input=False, **override) self._runner = FitTransformRunner(self._s, tr_settings, user_input, device=self.device, disable_pbar=self.disable_pbar)", "a device is properly instantiated. If opu_device is of type", "instance of class that transforms the output of the opu", "= \\\\mathbf{R}\\\\mathbf{x} \\\\mbox{ (linear transform)} Main methods are `transform`, `linear_transform`,", "2d input_vectors, binary encoded, packed or not packed: bool, optional", "X: np.ndarray or torch.Tensor a 2d input vector, or batch", "output / (self._s.stdev * sqrt(n_features)) elif self.rescale is OutputRescaling.norm: output", "= time.time() prepared_X = reconstruction.encode_batch(X2) self._trace(f\"Encoding time {time.time() - start}", "by one, performance will be improved with the online flag", "self.device.close() self._debug(\"OPU closed\") @property def config(self): \"\"\"Returns the internal configuration", "= value @property def _s(self) -> OpuSettings: \"\"\"Returns immutable settings", "Open at init, unless relevant host.json option is False if", "if issue: # noinspection PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim = 1 self._debug(\"trigger issue", "provided, follow system's setting (usually True) disable_pbar: bool, optional disable", "\"Use lightonml.set_verbose_level instead\", DeprecationWarning) lightonml.set_verbose_level(verbose_level) else: verbose_level = lightonml.get_verbose_level() self._debug", "# noinspection PyProtectedMember,PyUnresolvedReferences self.device._OpuDevice__opu.nb_prelim = 1 self._debug(\"trigger issue detected, workaround", "<gh_stars>10-100 # Copyright (c) 2020 LightOn, All Rights Reserved. #", "or torch.Tensor Fit will be made on this vector to", "fit2d before linear_transform\" traits = self._runner.traits if user_input is None:", "dimensionality of the target projection space. rescale: types.OutputRescaling, output rescaling", "and print functions if verbose_level != -1: warnings.warn(\"Verbose level arg", "rnd_mat is None or rnd_mat.shape != (n_features, n_components): self._print(\"OPU: computing", "transform2d(self, *args, **kwargs): raise RuntimeError(\"transform2d is deprecated, you must now", "the kernel on the OPU object to release it. Parameters", "decoder_cls=NoDecoding) -> TransformOutput: \"\"\" Performs the nonlinear random projections of", "from lightonml.internal.config import get_host_option, opu_version from lightonml.internal import config, output_roi,", "as it's an optional module and may not be present", "2. decode the output 3. convert to tensor if user", "If encoder has get_params method, it's for transmitting it to", "start = time.time() with self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu = self._runner.transform(prepared_input, linear=True) self._trace(f\"Transform", "transform, the default)} .. math:: \\\\mathbf{y} = \\\\mathbf{R}\\\\mathbf{x} \\\\mbox{ (linear", "issue not detected\") self._debug(\"OPU opened\") def close(self): \"\"\"Releases hardware resources", "to 1 simulated: bool, optional performs the random projection using", "frametime_us, exposure_us, seq_nb_prelim, None, verbose_level, name) self._base_frametime_us = self.device.frametime_us self._base_exposure_us", "OPU device .. seealso:: `close()` or use the context manager", "defined in # file 'LICENSE.txt', which is part of this", "AcqState.online.value, \\ \"Can't do linear transform when acquisition is\" \\", "number of binary features that the OPU will transform writeable", "# min_n_components is linked to the minimum output size min_n_components=self.config[\"output\"].get(\"minimum_output_size\",", "more details.\\n\" \\ \"See also https://lighton.ai/products for getting access to", "self._acq_stack.close() # Device itself is closed on pickling return state", "linear transform of X, for Nitro (non-linear) photonic cores. Parameters", "acq stack can't be pickled, will be restored state.pop(\"_acq_stack\") #", "False), no_single_transform=self.config.get(\"no_single_transform\", False), stdev=self.config[\"output\"].get(\"stdev\", 1.), **kwargs) def _resize_rnd_matrix(self, n_features: int,", "self._acq_stack = ExitStack() # Restore online acquisition if it was", "str] = OutputRescaling.variance): self.__opu_config = None self.__config_file = config_file self.__config_override", "opu. decoder_cls: encoding.base.BaseTransformer, optional class or instance of class that", "context attribute to add metadata \"\"\" self.fit2d(X, n_2d_features, packed, False,", "init, or take the one passed as input if opu_device:", "Unless `open_at_init=False`, these resources are acquired automatically at init. If", "traits.packed: # TODO implement for packed raise RuntimeError(\"Linear transform isn't", "was tensor \"\"\" output = user_input.reshape_output(output) # If encoder has", "which is part of this source code package. \"\"\" This", "is done by open/close and a context-manager interface. Unless `open_at_init=False`,", "= 200000, opu_device: Optional[Union[\"OpuDevice\", SimulatedOpuDevice]] = None, max_n_features: int =", "back into the appropriate format. Returns ------- Y: np.ndarray or", "(self._s.stdev * sqrt(n_features)) elif self.rescale is OutputRescaling.norm: output = output", "= self.device.frametime_us self._base_exposure_us = self.device.exposure_us if self._s.simulated: # build the", "one given in `fit1d` or `fit2d`. encoder_cls: encoder.base.BaseTransformer, optional class", "tuple(int) Number of features for the input, necessary if X", "for getting access to our technology.\" if simulated and opu_device", "assert self.device.active, \"OPU device isn't active, use opu.open() or \\\"with", "TransformSettings: \"\"\"Returns transform settings for feeding to TransformRunner\"\"\" init =", "a physical or simulated device. If not provided, a device", "is used for progress display Parameters ---------- X: np.ndarray or", "def rescale(self): return self._rescale @rescale.setter def rescale(self, value): # If", "call `close()` or shutdown the kernel on the OPU object", "convert back to torch if needed output = self._post_transform(result_ctx, user_input,", ".. math:: \\\\mathbf{y} = \\\\lvert \\\\mathbf{R} \\\\mathbf{x} \\\\rvert^2 \\\\mbox{ (non-linear", "or kernel has not released the resources, an error will", "length 2 If the input is bit-packed, specifies the shape", "target projection space. opu_device : OpuDevice or SimulatedOpuDevice, optional optical", "self._s.detect_trigger: # Detect trigger issue, and take action if needed", "def fit2d(self, X=None, n_features: Tuple[int, int] = None, packed: bool", "OpuSettings(max_n_features=self._max_n_features, n_samples_by_pass=pass_default, simulated=True, **kwargs ) return OpuSettings( max_n_features=int(np.prod(self.device.input_shape)), # Will", "def max_n_components(self): return self._output_roi.max_components @property def n_components(self) -> int: return", "With batch input start acquisition first assert self.device.acq_state.value != AcqState.online.value,", "max_n_features: int maximum number of binary features that the OPU", "_raw_linear_transform(self, X, traits=None, user_input=None): \"\"\" Do linear_transform of X, and", "pass_default = attr.fields(OpuSettings).n_samples_by_pass.default # Common settings to both simulated and", "= False, n_2d_features=None, **override) -> ContextArray: \"\"\"Performs the nonlinear random", "optional maximum number of binary features that the OPU will", "bool = None, disable_pbar=False, simulated=False, rescale: Union[OutputRescaling, str] = OutputRescaling.variance):", "might encounter an inconsistency in the transformation matrix. The input", "= types.InputRoiStrategy.full, open_at_init: bool = None, disable_pbar=False, simulated=False, rescale: Union[OutputRescaling,", "opu_type = self.config[\"type\"] frametime_us = self.config[\"input\"][\"frametime_us\"] exposure_us = self.config[\"output\"][\"exposure_us\"] seq_nb_prelim", "is at 1.4.1 or later, needed for linear_reconstruction pkg_resources.require(\"lightonopu>=1.4.1\") #", "self.device.acquiring(n_images=self._s.n_samples_by_pass): rp_opu = self._runner.transform(prepared_input, linear=True) self._trace(f\"Transform time {time.time() - start}", "vector(s). This function is the one-liner equivalent of `fit1d` and", "after batch encoding to something suitable for formatting prepared_X =", "each other, add `online=True` in the fit function. Parameters ----------", "encoder_cls X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, traits) _, result_ctx", "attribute to add metadata \"\"\" self.fit1d(X, None, packed, False, **override)", "transform)} Main methods are `transform`, `linear_transform`, `fit1d` and `fit2d`, and", "bool, optional forces the setting of acquiring hardware resource at", "AcqState.online.value, \\ \"Can't transform a batch of vectors when acquisition", "used only if opu_device is a SimulatedOpuDevice, in order to", "\" in online mode, only single vectors\" with self.device.acquiring(n_images=self._s.n_samples_by_pass): out", "to call device.reserve here, but moved to device.acquiring() self._n_components =", "input vectors will be already bit-packed online: bool, optional Set", "import get_host_option, opu_version from lightonml.internal import config, output_roi, utils, types", "config_file (for dev purpose) verbose_level: int, optional deprecated, use lightonml.set_verbose_level()", "torch.Tensor input vector, or batch of input vectors. Each vector", "def __getstate__(self): state = self.__dict__.copy() # Remove logging functions, they", "self._trace = lightonml.get_trace_fn() self._print = lightonml.get_print_fn() self._acq_stack = ExitStack() #", "of the opu back into the appropriate format. Returns -------", "self._runner = None # type: Optional[TransformRunner] # ExitStack for device", "is in bit-packed representation defaults to False override: keyword args", "ExitStack for device acquisition, initialized when entering fit self._acq_stack =", "are conflicting\") # Device init, or take the one passed", "function. Parameters ---------- X: np.ndarray or torch.Tensor input vector, or", "types.InputRoiStrategy, optional describes how to display the features on the", "ones_range=self.config[\"ones_range\"], n_tries=self.config.get(\"n_transform_tries\", 5), detect_trigger=self.config.get(\"detect_trigger_issue\", False), no_single_transform=self.config.get(\"no_single_transform\", False), stdev=self.config[\"output\"].get(\"stdev\", 1.), **kwargs)", "here, but moved to device.acquiring() self._n_components = value @property def", "state = self.__dict__.copy() # Remove logging functions, they can't be", "1. reshape 2. decode the output 3. convert to tensor", "np.ndarray or torch.Tensor input vector, or batch of input vectors.", "== AcqState.online.value self._acq_stack.close() # Device itself is closed on pickling", "rescaling method for `linear_transform`. Ignored by `transform`. max_n_features: int maximum", "self.__active_before_enter: self.close() def open(self): \"\"\"Acquires hardware resources used by the", "close(self): \"\"\"Releases hardware resources used by the OPU device\"\"\" self._acq_stack.close()", "string containing name and versions of the OPU\"\"\" version =", "batch of 2d input_vectors, binary encoded, packed or not n_features:", "\" in online mode, only single vectors\" assert self._runner.t.input_roi_strategy ==", "relevant host.json option is False if open_at_init is None: open_at_init", "settings.input_roi_strategy = InputRoiStrategy.full assert settings.input_roi is None return settings def", "class that transforms the output of the opu back into", "must have the same dimensions as the one given in", "batch can be 1d or 2d. In all cases ``output.shape[:-1]", "n_features: int, n_components: int): \"\"\"Resize device's random matrix\"\"\" assert isinstance(self.device,", "self._runner = FitTransformRunner(self._s, tr_settings, user_input, device=self.device, disable_pbar=self.disable_pbar) else: # Only", "device .. seealso:: `close()` or use the context manager interface", "2d. In all cases ``output.shape[:-1] = X.shape[:-1]`` packed: bool, optional", "The function can be either called with input vector, for", "attribute to InputRoiStrategy.full.\" # X2 is now numpy 2D, whatever", "the one-liner equivalent of `fit2d` and `transform` calls. .. warning::", "if opu_device: if type(opu_device).__name__ not in [\"SimulatedOpuDevice\", \"OpuDevice\"]: raise TypeError(\"opu_device", "implemented for packed input :/\") if inspect.isclass(encoder_cls): encoder = encoder_cls()", "input vector. Not needed if the input isn't bit-packed. override:", "packed, is_2d_features, n_features) tr_settings = self._tr_settings(no_input=False, **override) self._runner = FitTransformRunner(self._s,", "a tuple \"\"\" if traits is None: assert self._runner, \"Call", "other, add `online=True` in the fit function. Parameters ---------- X:", "if online: if self._s.no_single_transform: raise RuntimeError(\"Online transform isn't available with", "as np from contextlib import ExitStack import attr import inspect", "be improved with the online flag set to True. Parameters", "**override) def fit2d(self, X=None, n_features: Tuple[int, int] = None, packed:", "an inconsistency in the transformation matrix. The input data can", "int Number of features for the input, necessary if X", "args for overriding transform settings (advanced parameters) Returns ------- Y:", "or `fit2d`. encoder_cls: encoding.base.BaseTransformer, optional class or instance of class", "typing import Optional, Union, Tuple, TYPE_CHECKING import numpy as np", "restored state.pop(\"_acq_stack\") # If acquisition is ongoing, close it if", "IntOrTuple, packed: bool, online: bool, is_2d_features: bool, **override): \"\"\"Internal working", "= encoder_cls X_enc = encoder.transform(X) user_input = OpuUserInput.from_traits(X_enc, traits) _,", "of X, and return both raw OPU output and decoded", "strategy settings.input_roi_strategy = InputRoiStrategy.full assert settings.input_roi is None return settings", "used by the OPU device\"\"\" self._acq_stack.close() self.device.close() self._debug(\"OPU closed\") @property", "n_components self.input_roi_strategy = input_roi_strategy # Runner initialized when entering fit", "{lightonml.__version__}\") try: # noinspection PyUnresolvedReferences import lightonopu version.append(f\"lightonopu version {lightonopu.__version__}\")", "lightonml from lightonml.internal.config import get_host_option, opu_version from lightonml.internal import config," ]
[ "'''Prints \"Hello, \" followed by the provided name. Examples: shovel", "kwargs you give it. This exists mostly to demonstrate that", "exists mostly to demonstrate that shovel is compatible with the", "you give it. This exists mostly to demonstrate the fact", "2 3 4 http://localhost:3000/bar.args?1&2&3&4''' for arg in args: print('You said", "args you give it. This exists mostly to demonstrate the", "--howdy hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for key, val in kwargs.items(): print('You said", "that shovel is compatible with the keyword argument functions. Examples:", "demonstrate that shovel is compatible with the keyword argument functions.", "fact that shovel is compatible with variable argument functions. Examples:", "key, val in kwargs.items(): print('You said \"%s\" => \"%s\"' %", "exists mostly to demonstrate the fact that shovel is compatible", "print('You said \"%s\"' % arg) @task def kwargs(**kwargs): '''Echos back", "1 2 3 4 http://localhost:3000/bar.args?1&2&3&4''' for arg in args: print('You", "demonstrate the fact that shovel is compatible with variable argument", "shovel bar.hello shovel bar.hello --name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello, %s' % name)", "with the keyword argument functions. Examples: shovel bar.kwargs --foo=5 --bar", "all the args you give it. This exists mostly to", "\"Hello, \" followed by the provided name. Examples: shovel bar.hello", "'''Echos back all the args you give it. This exists", "bar.kwargs --foo=5 --bar 5 --howdy hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for key, val", "mostly to demonstrate that shovel is compatible with the keyword", "import task @task def hello(name='Foo'): '''Prints \"Hello, \" followed by", "shovel bar.args 1 2 3 4 http://localhost:3000/bar.args?1&2&3&4''' for arg in", "that shovel is compatible with variable argument functions. Examples: shovel", "arg in args: print('You said \"%s\"' % arg) @task def", "compatible with the keyword argument functions. Examples: shovel bar.kwargs --foo=5", "is compatible with the keyword argument functions. Examples: shovel bar.kwargs", "--bar 5 --howdy hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for key, val in kwargs.items():", "give it. This exists mostly to demonstrate the fact that", "@task def kwargs(**kwargs): '''Echos back all the kwargs you give", "@task def hello(name='Foo'): '''Prints \"Hello, \" followed by the provided", "def hello(name='Foo'): '''Prints \"Hello, \" followed by the provided name.", "followed by the provided name. Examples: shovel bar.hello shovel bar.hello", "back all the kwargs you give it. This exists mostly", "3 4 http://localhost:3000/bar.args?1&2&3&4''' for arg in args: print('You said \"%s\"'", "shovel bar.kwargs --foo=5 --bar 5 --howdy hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for key,", "argument functions. Examples: shovel bar.args 1 2 3 4 http://localhost:3000/bar.args?1&2&3&4'''", "to demonstrate that shovel is compatible with the keyword argument", "bar.hello --name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello, %s' % name) @task def args(*args):", "'''Echos back all the kwargs you give it. This exists", "shovel import task @task def hello(name='Foo'): '''Prints \"Hello, \" followed", "the keyword argument functions. Examples: shovel bar.kwargs --foo=5 --bar 5", "the fact that shovel is compatible with variable argument functions.", "args(*args): '''Echos back all the args you give it. This", "give it. This exists mostly to demonstrate that shovel is", "--foo=5 --bar 5 --howdy hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for key, val in", "Examples: shovel bar.args 1 2 3 4 http://localhost:3000/bar.args?1&2&3&4''' for arg", "argument functions. Examples: shovel bar.kwargs --foo=5 --bar 5 --howdy hey", "it. This exists mostly to demonstrate the fact that shovel", "shovel bar.hello --name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello, %s' % name) @task def", "keyword argument functions. Examples: shovel bar.kwargs --foo=5 --bar 5 --howdy", "by the provided name. Examples: shovel bar.hello shovel bar.hello --name=Erin", "functions. Examples: shovel bar.kwargs --foo=5 --bar 5 --howdy hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey'''", "@task def args(*args): '''Echos back all the args you give", "to demonstrate the fact that shovel is compatible with variable", "provided name. Examples: shovel bar.hello shovel bar.hello --name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello,", "mostly to demonstrate the fact that shovel is compatible with", "is compatible with variable argument functions. Examples: shovel bar.args 1", "the args you give it. This exists mostly to demonstrate", "with variable argument functions. Examples: shovel bar.args 1 2 3", "the provided name. Examples: shovel bar.hello shovel bar.hello --name=Erin http://localhost:3000/bar.hello?Erin'''", "args: print('You said \"%s\"' % arg) @task def kwargs(**kwargs): '''Echos", "print('Hello, %s' % name) @task def args(*args): '''Echos back all", "shovel is compatible with variable argument functions. Examples: shovel bar.args", "\"%s\"' % arg) @task def kwargs(**kwargs): '''Echos back all the", "This exists mostly to demonstrate that shovel is compatible with", "name. Examples: shovel bar.hello shovel bar.hello --name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello, %s'", "--name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello, %s' % name) @task def args(*args): '''Echos", "compatible with variable argument functions. Examples: shovel bar.args 1 2", "This exists mostly to demonstrate the fact that shovel is", "\" followed by the provided name. Examples: shovel bar.hello shovel", "%s' % name) @task def args(*args): '''Echos back all the", "% name) @task def args(*args): '''Echos back all the args", "def kwargs(**kwargs): '''Echos back all the kwargs you give it.", "http://localhost:3000/bar.hello?Erin''' print('Hello, %s' % name) @task def args(*args): '''Echos back", "http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for key, val in kwargs.items(): print('You said \"%s\" =>", "for key, val in kwargs.items(): print('You said \"%s\" => \"%s\"'", "Examples: shovel bar.kwargs --foo=5 --bar 5 --howdy hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for", "hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for key, val in kwargs.items(): print('You said \"%s\"", "bar.hello shovel bar.hello --name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello, %s' % name) @task", "val in kwargs.items(): print('You said \"%s\" => \"%s\"' % (key,", "hello(name='Foo'): '''Prints \"Hello, \" followed by the provided name. Examples:", "bar.args 1 2 3 4 http://localhost:3000/bar.args?1&2&3&4''' for arg in args:", "said \"%s\"' % arg) @task def kwargs(**kwargs): '''Echos back all", "in args: print('You said \"%s\"' % arg) @task def kwargs(**kwargs):", "kwargs(**kwargs): '''Echos back all the kwargs you give it. This", "def args(*args): '''Echos back all the args you give it.", "http://localhost:3000/bar.args?1&2&3&4''' for arg in args: print('You said \"%s\"' % arg)", "for arg in args: print('You said \"%s\"' % arg) @task", "it. This exists mostly to demonstrate that shovel is compatible", "5 --howdy hey http://localhost:3000/bar.kwargs?foo=5&bar=5&howdy=hey''' for key, val in kwargs.items(): print('You", "4 http://localhost:3000/bar.args?1&2&3&4''' for arg in args: print('You said \"%s\"' %", "arg) @task def kwargs(**kwargs): '''Echos back all the kwargs you", "back all the args you give it. This exists mostly", "shovel is compatible with the keyword argument functions. Examples: shovel", "the kwargs you give it. This exists mostly to demonstrate", "% arg) @task def kwargs(**kwargs): '''Echos back all the kwargs", "Examples: shovel bar.hello shovel bar.hello --name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello, %s' %", "task @task def hello(name='Foo'): '''Prints \"Hello, \" followed by the", "variable argument functions. Examples: shovel bar.args 1 2 3 4", "functions. Examples: shovel bar.args 1 2 3 4 http://localhost:3000/bar.args?1&2&3&4''' for", "name) @task def args(*args): '''Echos back all the args you", "you give it. This exists mostly to demonstrate that shovel", "from shovel import task @task def hello(name='Foo'): '''Prints \"Hello, \"", "all the kwargs you give it. This exists mostly to", "in kwargs.items(): print('You said \"%s\" => \"%s\"' % (key, val))" ]
[ "r) return s[:-1] class Interceptor(object): def __init__(self, name=None, default=None, hook=None,", "that module has a higher version that minver. params: -", "< other._timetable[key]: dict.__setitem__(self, key, value) self._timetable[key] = other._timetable[key] def iteritems(self):", "= [] if self: mk = max(len(k) for k in", "= L3RawSocket conf.L3socket6 = L3RawSocket6 def _socket_changer(attr, val): if not", "crypto_valid_recent and isCryptographyAdvanced() fancy_prompt = True auto_crop_tables = True recv_poll_rate", "r = \" \".join(r.split()) wlen = 76 - max(len(i), 10)", "exist in `self` or if the entry in `self` is", "return MANUFDB if attr == \"ethertypes\": from scapy.data import ETHER_TYPES", "dir = \" ->\" lst.append((num, \"%#6x %s %-20s (%s)\" %", "time import socket import sys from scapy import VERSION, base_classes", "# ############ class ConfClass(object): def configure(self, cnf): self.__dict__ = cnf.__dict__.copy()", "for x, y in lst) class LayersList(list): def __init__(self): list.__init__(self)", "eval(lay).__doc__ result.append((lay, doc.strip().split(\"\\n\")[0] if doc else lay)) return result class", "timetable check try: return self[item] except KeyError: return default def", "UDP_SERVICES return UDP_SERVICES if attr == \"services_tcp\": from scapy.data import", "== \"services_tcp\": from scapy.data import TCP_SERVICES return TCP_SERVICES return object.__getattr__(self,", "raise ScapyInvalidPlatformException( \"Scapy only supports libpcap on Solaris !\" )", "self._caches_list: c.flush() def __repr__(self): return \"\\n\".join(c.summary() for c in self._caches_list)", "L3PacketSocket, L2Socket, L2ListenSocket conf.L3socket = L3PacketSocket conf.L3socket6 = functools.partial(L3PacketSocket, filter=\"ip6\")", "any unwanted packet to go out (ARP, DNS, ...) checkIPID:", "BTsocket = None USBsocket = None min_pkt_size = 60 bufsize", "val): int_name = \"_intercepted_%s\" % name setattr(obj, int_name, val) def", "= socket.has_ipv6 extensions_paths = \".\" stats_classic_protocols = [] stats_dot11_protocols =", "def __repr__(self): lst = [] for num, layer in six.iteritems(self.num2layer):", "\"\"\" This a decorator to be used for any method", "ReadOnlyAttribute = functools.partial( Interceptor, hook=(lambda name, *args, **kwargs: _readonly(name)) )", "self._timetable[key] = other._timetable[key] def iteritems(self): if self.timeout is None: return", "computed. recv_poll_rate: how often to check for new packets. Defaults", "stealth : if 1, prevents any unwanted packet to go", "= True checkIPaddr = True checkIPinIP = True check_TCPerror_seqack =", "except (ScapyInvalidPlatformException, ImportError) as e: for key, value in restore.items():", "Interceptor(\"prompt\", \">>> \", _prompt_changer) promisc = True sniff_promisc = 1", "*BSD...) only !\") if not conf.use_pcap and SOLARIS: Interceptor.set_from_hook(conf, \"use_pcap\",", "< self.timeout) # noqa: E501 def iterkeys(self): if self.timeout is", "summary(self): return \"%s: %i valid items. Timeout=%rs\" % (self.name, len(self),", "if self.timeout is None: return dict.keys(self) t0 = time.time() return", "from the same place ASN1_default_codec: Codec used by default for", "be done noenum : holds list of enum fields for", "out (ARP, DNS, ...) checkIPID: if 0, doesn't check that", "direct access dictionary resolve : holds list of fields for", "return cmd so that method can be used as a", "= l.__doc__.split(\"\\n\")[0] if l.__doc__ else \"--\" s.append(\"%-20s: %s\" % (l.__name__,", "item) if self.timeout is not None: t = self._timetable[item] if", "self.append(cmd) return cmd # return cmd so that method can", "recent (2.0 and later) \"\"\" try: import cryptography except ImportError:", "conf.L3socket = L3pcapSocket conf.L3socket6 = functools.partial(L3pcapSocket, filter=\"ip6\") conf.L2socket = L2pcapSocket", "attr): raise AttributeError(\"Cannot delete attributes\") def update(self, other): for co", "This program is published under a GPLv2 license \"\"\" Implementation", "= L2pcapSocket conf.L2listen = L2pcapListenSocket # Update globals _load(\"scapy.arch.pcapdnet\") return", "geoip_city = None # can, tls, http are not loaded", "\"%s: %i valid items. Timeout=%rs\" % (self.name, len(self), self.timeout) #", "object. \"\"\" from __future__ import absolute_import from __future__ import print_function", "= time.time() return ((k, v) for (k, v) in six.iteritems(self.__dict__)", "depends on the 'crypto_valid' attribute of the global 'conf'. \"\"\"", "= 0.05 def __getattr__(self, attr): # Those are loaded on", "# This file is part of Scapy # See http://www.secdev.org/projects/scapy", "l3types = Num2Layer() L3socket = None L3socket6 = None L2socket", "L3pcapSocket except (OSError, ImportError): warning(\"No libpcap provider available ! pcap", "i[0] != \"_\": r = repr(getattr(self, i)) r = \"", "self.__slots__: return object.__setattr__(self, item, v) self._timetable[item] = time.time() dict.__setitem__(self, item,", "if DARWIN else \"xdg-open\" pdfreader = universal_open psreader = universal_open", "return len(self.keys()) def summary(self): return \"%s: %i valid items. Timeout=%rs\"", "# XXX use_dnet is deprecated use_dnet = os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\") use_bpf", "e: for key, value in restore.items(): Interceptor.set_from_hook(conf, key, value) if", "= default self.hook = hook self.args = args if args", "self._recalc_layer_list() def __contains__(self, elt): if isinstance(elt, base_classes.Packet_metaclass): return elt in", "\"Please install python-cryptography v1.7 or later.\") # noqa: E501 return", "from `other` either if it does # not exist in", "class Num2Layer: def __init__(self): self.num2layer = {} self.layer2num = {}", "for c in self._caches_list) def _version_checker(module, minver): \"\"\"Checks that module", "item) val = dict.__getitem__(self, item) if self.timeout is not None:", "val def get(self, item, default=None): # overloading this method is", "except (OSError, ImportError): warning(\"No libpcap provider available ! pcap won't", "warning_threshold = 5 prog = ProgPath() resolve = Resolve() noenum", "'mgcp', 'mobileip', 'netbios', 'netflow', 'ntp', 'ppi', 'ppp', 'pptp', 'radius', 'rip',", "self[item] if item in self else default def __repr__(self): lst", "# the timetable check try: return self[item] except KeyError: return", "else: dir = \" ->\" lst.append((num, \"%#6x %s %-20s (%s)\"", "use_* parameters \"\"\" from scapy.main import _load if conf.use_bpf and", "E501 def __iter__(self): return six.iterkeys(self.__dict__) def itervalues(self): if self.timeout is", "TLS session secrets when they are computed. recv_poll_rate: how often", "int_name = \"_intercepted_%s\" % name setattr(obj, int_name, val) def __set__(self,", "they either are equal or byte swapped equals (bug in", "return [k for k in six.iterkeys(self.__dict__) if t0 - self._timetable[k]", "is not None: t = self._timetable[item] if time.time() - t", "= self._timetable[item] if time.time() - t > self.timeout: raise KeyError(item)", "conf.L2listen = L2ListenSocket # Update globals _load(\"scapy.arch.linux\") return if WINDOWS:", "attr == \"services_tcp\": from scapy.data import TCP_SERVICES return TCP_SERVICES return", "valid items. Timeout=%rs\" % (self.name, len(self), self.timeout) # noqa: E501", "= L3WinSocket6 conf.L2socket = _NotAvailableSocket conf.L2listen = _NotAvailableSocket # No", "the dict to go through # the timetable check try:", "library is present, and if it supports X25519, ChaCha20Poly1305 and", "os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"), \".scapy_history\")) padding = 1 except_filter = \"\" debug_match", "much time between warnings from the same place ASN1_default_codec: Codec", "scapy (v1.7 or later). \"\"\" try: import cryptography except ImportError:", "# noqa: E501 AS_resolver: choose the AS resolver class to", "the timetable check try: return self[item] except KeyError: return default", "TCP_SERVICES return object.__getattr__(self, attr) if not Conf.ipv6_enabled: log_scapy.warning(\"IPv6 support disabled", "behaviour depends on the 'crypto_valid' attribute of the global 'conf'.", "configure(self, cnf): self.__dict__ = cnf.__dict__.copy() def __repr__(self): return str(self) def", "Resolve(ConfigFieldList): pass class Num2Layer: def __init__(self): self.num2layer = {} self.layer2num", "mode for listening socket (to get answers if you spoof", "not conf.use_pcap and SOLARIS: Interceptor.set_from_hook(conf, \"use_pcap\", True) raise ScapyInvalidPlatformException( \"Scapy", "'vrrp', 'vxlan', 'x509', 'zigbee'] contribs = dict() crypto_valid = isCryptographyValid()", "We only update an element from `other` either if it", "iface = None iface6 = None layers = LayersList() commands", "is not None else [] self.kargs = kargs if kargs", "_load(\"scapy.arch.linux\") return if WINDOWS: from scapy.arch.windows import _NotAvailableSocket from scapy.arch.windows.native", "promisc = True sniff_promisc = 1 raw_layer = None raw_summary", "if the cryptography library is recent (2.0 and later) \"\"\"", "3 (verbose) promisc : default mode for listening socket (to", "or \"auto\". Default: Auto stealth : if 1, prevents any", "\"\" debug_match = False debug_tls = False wepkey = \"\"", "if num not in self.num2layer or self.num2layer[num] != layer: lst.append((num,", "# return cmd so that method can be used as", "l.__doc__ else \"--\" s.append(\"%-20s: %s\" % (l.__name__, doc)) return \"\\n\".join(s)", "scapy.arch.linux import L3PacketSocket, L2Socket, L2ListenSocket conf.L3socket = L3PacketSocket conf.L3socket6 =", "ConfigFieldList: def __init__(self): self.fields = set() self.layers = set() @staticmethod", "Filed by route6.py auto_fragment = True debug_dissector = False color_theme", "VERSION, base_classes from scapy.consts import DARWIN, WINDOWS, LINUX, BSD, SOLARIS", "= tuple(int(x) for x in version_tags) return version_tags >= minver", "l in sorted(self, key=lambda x: x.__name__): doc = l.__doc__.split(\"\\n\")[0] if", "return self[item] if item in self else default def __repr__(self):", "L2bpfListenSocket # Update globals _load(\"scapy.arch.bpf\") return if LINUX: from scapy.arch.linux", "None L2listen = None BTsocket = None USBsocket = None", "histfile = os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"), \".scapy_history\")) padding = 1 except_filter =", "= False checkIPsrc = True checkIPaddr = True checkIPinIP =", "0, doesn't check that IPID matches between IP sent and", ": BPF filter for packets to ignore debug_match : when", "raise ValueError(\"Read-only value !\") ReadOnlyAttribute = functools.partial( Interceptor, hook=(lambda name,", "is not None else {} def __get__(self, obj, typ=None): if", "stacks) # noqa: E501 checkIPinIP: if True, checks that IP-in-IP", "object.__setattr__(self, item, v) self._timetable[item] = time.time() dict.__setitem__(self, item, v) def", "key not in self or self._timetable[key] < other._timetable[key]: dict.__setitem__(self, key,", "relying on the cryptography library. # noqa: E501 Its behaviour", "args if args is not None else [] self.kargs =", "return \"<%s [%s]>\" % (self.__class__.__name__, \" \".join(str(x) for x in", "[\"timeout\", \"name\", \"_timetable\", \"__dict__\"] def __init__(self, name=\"noname\", timeout=None): self.timeout =", "self._is_field(f)} self._recalc_layer_list() def remove(self, *flds): self.fields -= set(flds) self._recalc_layer_list() def", "def __init__(self): self.fields = set() self.layers = set() @staticmethod def", "if 1, also check that TCP seq and ack match", "self._recalc_layer_list() def remove(self, *flds): self.fields -= set(flds) self._recalc_layer_list() def __contains__(self,", "base_classes.Packet_metaclass): return self.layer2num[item] return self.num2layer[item] def __contains__(self, item): if isinstance(item,", "doc = eval(lay).__doc__ result.append((lay, doc.strip().split(\"\\n\")[0] if doc else lay)) return", "apply_ipython_style ############ # Config # ############ class ConfClass(object): def configure(self,", "access dictionary resolve : holds list of fields for which", "resolver class to use extensions_paths: path or list of paths", "by route6.py auto_fragment = True debug_dissector = False color_theme =", "v1.7 or later.\") # noqa: E501 return func(*args, **kwargs) return", "set_from_hook(obj, name, val): int_name = \"_intercepted_%s\" % name setattr(obj, int_name,", "= [] stats_dot11_protocols = [] temp_files = [] netcache =", "MANUFDB return MANUFDB if attr == \"ethertypes\": from scapy.data import", "L2listen = None BTsocket = None USBsocket = None min_pkt_size", "= name self.intname = \"_intercepted_%s\" % name self.default = default", "later) \"\"\" try: import cryptography except ImportError: return False return", "return version_tags >= minver def isCryptographyValid(): \"\"\" Check if the", "holds list of enum fields for which conversion to string", "self.name = name self._timetable = {} def flush(self): self.__init__(name=self.name, timeout=self.timeout)", "\"\"\" from scapy.main import _load if conf.use_bpf and not BSD:", "False checkIPsrc = True checkIPaddr = True checkIPinIP = True", "**kwargs): if not conf.crypto_valid: raise ImportError(\"Cannot execute crypto-related method! \"", "add_cache(self, cache): self._caches_list.append(cache) setattr(self, cache.name, cache) def new_cache(self, name, timeout=None):", "True checkIPinIP = True check_TCPerror_seqack = False verb = 2", "self._timetable[k] < self.timeout) # noqa: E501 def __iter__(self): return six.iterkeys(self.__dict__)", "in six.iteritems(other): # We only update an element from `other`", "scapy.arch.bpf.supersocket import L2bpfListenSocket, \\ L2bpfSocket, L3bpfSocket conf.L3socket = L3bpfSocket conf.L3socket6", "the same place ASN1_default_codec: Codec used by default for ASN1", "# noqa: E501 def items(self): if self.timeout is None: return", "def get(self, item, default=None): return self[item] if item in self", "= {} def __repr__(self): return \"\\n\".join(\"%-20s: %s\" % (l.__name__, l.name)", "\"\"\"Displays Scapy's default commands\"\"\" print(repr(conf.commands)) class CacheInstance(dict, object): __slots__ =", "self._timetable[k] < self.timeout] # noqa: E501 def values(self): if self.timeout", "- minver: a tuple of versions \"\"\" # We could", "resolve : holds list of fields for which resolution should", "a change of conf.logLevel\"\"\" log_scapy.setLevel(val) class Conf(ConfClass): \"\"\"This object contains", "warning(\"No libpcap provider available ! pcap won't be used\") Interceptor.set_from_hook(conf,", "in six.iteritems(self.layer2num): if num not in self.num2layer or self.num2layer[num] !=", "is published under a GPLv2 license \"\"\" Implementation of the", "not None else [] self.kargs = kargs if kargs is", "item, default=None): return self[item] if item in self else default", "filter=\"ip6\") conf.L2socket = L2pcapSocket conf.L2listen = L2pcapListenSocket # Update globals", "cmd so that method can be used as a decorator", "self.layers = {owner for f in self.fields for owner in", "noqa: F401 for lay in self.ldict: doc = eval(lay).__doc__ result.append((lay,", "E501 if 2, strictly checks that they are equals checkIPsrc:", "that encapsulates another IP layer check_TCPerror_seqack: if 1, also check", "'sctp', 'sixlowpan', 'skinny', 'smb', 'snmp', 'tftp', 'vrrp', 'vxlan', 'x509', 'zigbee']", "return \"\\n\".join(\"%-20s: %s\" % (l.__name__, l.name) for l in self)", "def register_layer2num(self, num, layer): self.layer2num[layer] = num def __getitem__(self, item):", "def __getitem__(self, item): if isinstance(item, base_classes.Packet_metaclass): return self.layer2num[item] return self.num2layer[item]", "list.__init__(self) self.ldict = {} def __repr__(self): return \"\\n\".join(\"%-20s: %s\" %", "in self.fields def __repr__(self): return \"<%s [%s]>\" % (self.__class__.__name__, \"", "route6 = None # Filed by route6.py auto_fragment = True", "import NoTheme, apply_ipython_style ############ # Config # ############ class ConfClass(object):", "x: x.__name__): doc = l.__doc__.split(\"\\n\")[0] if l.__doc__ else \"--\" s.append(\"%-20s:", "execute crypto-related method! \" \"Please install python-cryptography v1.7 or later.\")", "directly by _set_conf_sockets if val: # Only if True for", "= other._timetable[key] def iteritems(self): if self.timeout is None: return six.iteritems(self.__dict__)", "in self.layer2num and self.layer2num[layer] == num: dir = \"<->\" else:", "to go through # the timetable check try: return self[item]", "ValueError(\"Read-only value !\") ReadOnlyAttribute = functools.partial( Interceptor, hook=(lambda name, *args,", "lan) # noqa: E501 sniff_promisc : default mode for sniff()", "layer, num in six.iteritems(self.layer2num): if num not in self.num2layer or", "= \" ->\" lst.append((num, \"%#6x %s %-20s (%s)\" % (num,", "check_TCPerror_seqack: if 1, also check that TCP seq and ack", "# We could use LooseVersion, but distutils imports imp which", "from scapy.arch.bpf.supersocket import L2bpfListenSocket, \\ L2bpfSocket, L3bpfSocket conf.L3socket = L3bpfSocket", "if len(r) > wlen: r = r[:wlen - 3] +", "def register(self, num, layer): self.register_num2layer(num, layer) self.register_layer2num(num, layer) def register_num2layer(self,", "loaded by default load_layers = ['bluetooth', 'bluetooth4LE', 'dhcp', 'dhcp6', 'dns',", "val) def __set__(self, obj, val): setattr(obj, self.intname, val) self.hook(self.name, val,", "else {} def __get__(self, obj, typ=None): if not hasattr(obj, self.intname):", "same place ASN1_default_codec: Codec used by default for ASN1 objects", "absolute_import from __future__ import print_function import functools import os import", "Interceptor, hook=(lambda name, *args, **kwargs: _readonly(name)) ) ReadOnlyAttribute.__doc__ = \"Read-only", "= {k: getattr(conf, k) for k in dependencies} del restore[attr]", "noqa: E501 def keys(self): if self.timeout is None: return dict.keys(self)", "import L2bpfListenSocket, \\ L2bpfSocket, L3bpfSocket conf.L3socket = L3bpfSocket conf.L3socket6 =", "is None: return six.iteritems(self.__dict__) t0 = time.time() return ((k, v)", "(num, layer.__name__, layer._name))) lst.sort() return \"\\n\".join(y for x, y in", "import TCP_SERVICES return TCP_SERVICES return object.__getattr__(self, attr) if not Conf.ipv6_enabled:", "for item in six.iteritems(self.__dict__): s.append(fmt % item) return \"\\n\".join(s) class", "not Conf.ipv6_enabled: log_scapy.warning(\"IPv6 support disabled in Python. Cannot load Scapy", "raise KeyError(item) return val def get(self, item, default=None): # overloading", "(k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout)", "scapy.arch.pcapdnet import L2pcapListenSocket, L2pcapSocket, \\ L3pcapSocket except (OSError, ImportError): warning(\"No", "self.intname) @staticmethod def set_from_hook(obj, name, val): int_name = \"_intercepted_%s\" %", "MANUFDB if attr == \"ethertypes\": from scapy.data import ETHER_TYPES return", "= \"open\" if DARWIN else \"xdg-open\" pdfreader = universal_open psreader", "cmd # return cmd so that method can be used", "num, layer): self.num2layer[num] = layer def register_layer2num(self, num, layer): self.layer2num[layer]", "\"ipython\", \"python\" or \"auto\". Default: Auto stealth : if 1,", "in sorted(self, key=lambda x: x.__name__): doc = l.__doc__.split(\"\\n\")[0] if l.__doc__", "L2ListenSocket # Update globals _load(\"scapy.arch.linux\") return if WINDOWS: from scapy.arch.windows", "for more information # Copyright (C) <NAME> <<EMAIL>> # This", "L3RawSocket from scapy.layers.inet6 import L3RawSocket6 conf.L3socket = L3RawSocket conf.L3socket6 =", "the Scapy routing table and provides methods to manipulate it", "\".scapy_history\")) padding = 1 except_filter = \"\" debug_match = False", "*self.args, **self.kargs) def _readonly(name): default = Conf.__dict__[name].default Interceptor.set_from_hook(conf, name, default)", "crypto_valid_recent = isCryptographyRecent() crypto_valid_advanced = crypto_valid_recent and isCryptographyAdvanced() fancy_prompt =", "= hook self.args = args if args is not None", "_load(\"scapy.arch.bpf\") return if LINUX: from scapy.arch.linux import L3PacketSocket, L2Socket, L2ListenSocket", "= 76 - max(len(i), 10) if len(r) > wlen: r", "None: return six.iteritems(self.__dict__) t0 = time.time() return ((k, v) for", "handled directly by _set_conf_sockets if val: # Only if True", "conf.L2socket = L2pcapSocket conf.L2listen = L2pcapListenSocket # Update globals _load(\"scapy.arch.pcapdnet\")", "Interceptor hook, use Interceptor.set_from_hook if conf.use_pcap or conf.use_dnet: try: from", "print_function import functools import os import re import time import", "in six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout) # noqa:", "L3RawSocket6 conf.L3socket = L3RawSocket conf.L3socket6 = L3RawSocket6 def _socket_changer(attr, val):", "to check for new packets. Defaults to 0.05s. \"\"\" version", "kargs=None): self.name = name self.intname = \"_intercepted_%s\" % name self.default", "= Emphasize() use_pypy = ReadOnlyAttribute(\"use_pypy\", isPyPy()) use_pcap = Interceptor( \"use_pcap\",", "resolution should be done noenum : holds list of enum", "self.timeout = timeout self.name = name self._timetable = {} def", "= isCryptographyValid() crypto_valid_recent = isCryptographyRecent() crypto_valid_advanced = crypto_valid_recent and isCryptographyAdvanced()", "if m in Conf.load_layers: Conf.load_layers.remove(m) conf = Conf() def crypto_validator(func):", "+= \"%-10s = %s\\n\" % (i, r) return s[:-1] class", "debug_tls = False wepkey = \"\" cache_iflist = {} route", "scapy.main import _load if conf.use_bpf and not BSD: Interceptor.set_from_hook(conf, \"use_bpf\",", "ASN1 objects mib : holds MIB direct access dictionary resolve", "warnings from the same place ASN1_default_codec: Codec used by default", "% (self.name, len(self), self.timeout) # noqa: E501 def __repr__(self): s", "Implementation of the configuration object. \"\"\" from __future__ import absolute_import", "(OSX, *BSD...) only !\") if not conf.use_pcap and SOLARIS: Interceptor.set_from_hook(conf,", "do not check IP layers that encapsulates another IP layer", "= args if args is not None else [] self.kargs", "flush(self): self.__init__(name=self.name, timeout=self.timeout) def __getitem__(self, item): if item in self.__slots__:", "# Filed by route.py route6 = None # Filed by", "filename where the session will be saved interactive_shell : can", "six.iteritems(self.__dict__): s.append(fmt % item) return \"\\n\".join(s) class NetCache: def __init__(self):", "s = \"\" keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys)", "commands = CommandsList() dot15d4_protocol = None # Used in dot15d4.py", "import os import re import time import socket import sys", "k in six.iterkeys(self.__dict__)) fmt = \"%%-%is %%s\" % (mk +", "of conf.logLevel\"\"\" log_scapy.setLevel(val) class Conf(ConfClass): \"\"\"This object contains the configuration", "which resolution should be done noenum : holds list of", "the session will be saved interactive_shell : can be \"ipython\",", "return \"\\n\".join(c.summary() for c in self._caches_list) def _version_checker(module, minver): \"\"\"Checks", "noqa: E501 Its behaviour depends on the 'crypto_valid' attribute of", "'isakmp', 'l2', 'l2tp', 'llmnr', 'lltd', 'mgcp', 'mobileip', 'netbios', 'netflow', 'ntp',", "t0 - self._timetable[k] < self.timeout] # noqa: E501 def __len__(self):", "higher version that minver. params: - module: a module to", "'lltd', 'mgcp', 'mobileip', 'netbios', 'netflow', 'ntp', 'ppi', 'ppp', 'pptp', 'radius',", "Conf(ConfClass): \"\"\"This object contains the configuration of Scapy. session :", "L3pcapSocket conf.L3socket6 = functools.partial(L3pcapSocket, filter=\"ip6\") conf.L2socket = L2pcapSocket conf.L2listen =", "if 1, checks that they either are equal or byte", "None: t = self._timetable[item] if time.time() - t > self.timeout:", "for num, layer in six.iteritems(self.num2layer): if layer in self.layer2num and", "def add(self, *flds): self.fields |= {f for f in flds", "globals _load(\"scapy.arch.linux\") return if WINDOWS: from scapy.arch.windows import _NotAvailableSocket from", "by default for ASN1 objects mib : holds MIB direct", "self.layer2num = {} def register(self, num, layer): self.register_num2layer(num, layer) self.register_layer2num(num,", "if LINUX: from scapy.arch.linux import L3PacketSocket, L2Socket, L2ListenSocket conf.L3socket =", "default=None): # overloading this method is needed to force the", "and ICMP IP citation match (bug in some NAT stacks)", "use Interceptor.set_from_hook if conf.use_pcap or conf.use_dnet: try: from scapy.arch.pcapdnet import", "def isCryptographyValid(): \"\"\" Check if the cryptography library is present,", "isinstance(e, ScapyInvalidPlatformException): raise def _loglevel_changer(attr, val): \"\"\"Handle a change of", "a boolean\") dependencies = { # Things that will be", "def _socket_changer(attr, val): if not isinstance(val, bool): raise TypeError(\"This argument", "hasattr(obj, self.intname): setattr(obj, self.intname, self.default) return getattr(obj, self.intname) @staticmethod def", "getattr(self, co.name).update(co) else: self.add_cache(co.copy()) def flush(self): for c in self._caches_list:", ">= minver def isCryptographyValid(): \"\"\" Check if the cryptography library", "IP-in-IP layers match. If False, do not check IP layers", "answers if you spoof on a lan) # noqa: E501", "packet that are not matched into debug.recv # noqa: E501", "t0 - self._timetable[k] < self.timeout) # noqa: E501 def __iter__(self):", "in six.iterkeys(self.__dict__)) fmt = \"%%-%is %%s\" % (mk + 1)", "return \"\\n\".join(y for x, y in lst) class LayersList(list): def", "dir, layer.__name__, layer._name))) for layer, num in six.iteritems(self.layer2num): if num", "are already in an Interceptor hook, use Interceptor.set_from_hook if conf.use_pcap", "in self.layer2num return item in self.num2layer def get(self, item, default=None):", "(bug in some IP stacks) # noqa: E501 if 2,", "conf.color_theme.prompt(conf.prompt) except Exception: pass try: apply_ipython_style(get_ipython()) except NameError: pass def", "item) return \"\\n\".join(s) class NetCache: def __init__(self): self._caches_list = []", "mib : holds MIB direct access dictionary resolve : holds", "result class CommandsList(list): def __repr__(self): s = [] for l", "= Num2Layer() L3socket = None L3socket6 = None L2socket =", "\"\"\"Returns either scapy is running under PyPy or not\"\"\" try:", ": history file padding : includes padding in disassembled packets", "either are equal or byte swapped equals (bug in some", "dot = \"dot\" display = \"display\" tcpdump = \"tcpdump\" tcpreplay", "\"\\n\".join(s) def register(self, cmd): self.append(cmd) return cmd # return cmd", "dot15d4.py logLevel = Interceptor(\"logLevel\", log_scapy.level, _loglevel_changer) checkIPID = False checkIPsrc", "*flds): self.fields |= {f for f in flds if self._is_field(f)}", "'l2', 'l2tp', 'llmnr', 'lltd', 'mgcp', 'mobileip', 'netbios', 'netflow', 'ntp', 'ppi',", "if 1, checks IP src in IP and ICMP IP", "None L3socket6 = None L2socket = None L2listen = None", "False) raise ScapyInvalidPlatformException(\"BSD-like (OSX, *BSD...) only !\") if not conf.use_pcap", "item, default=None): # overloading this method is needed to force", "'inet6', 'ipsec', 'ir', 'isakmp', 'l2', 'l2tp', 'llmnr', 'lltd', 'mgcp', 'mobileip',", "used\") Interceptor.set_from_hook(conf, \"use_pcap\", False) else: conf.L3socket = L3pcapSocket conf.L3socket6 =", "isCryptographyRecent(): \"\"\" Check if the cryptography library is recent (2.0", "dependencies = { # Things that will be turned off", "minver. params: - module: a module to test - minver:", "noqa: E501 X25519PrivateKey.generate() except Exception: return False else: return True", "= False wepkey = \"\" cache_iflist = {} route =", "owner in f.owners} def add(self, *flds): self.fields |= {f for", "Update globals _load(\"scapy.arch.linux\") return if WINDOWS: from scapy.arch.windows import _NotAvailableSocket", "byte swapped equals (bug in some IP stacks) # noqa:", "\"\" interactive = False interactive_shell = \"\" stealth = \"not", "m in Conf.load_layers: Conf.load_layers.remove(m) conf = Conf() def crypto_validator(func): \"\"\"", "default mode for listening socket (to get answers if you", "os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\") use_bpf = Interceptor(\"use_bpf\", False, _socket_changer) use_npcap = False", "False, do not check IP layers that encapsulates another IP", "is None: return dict.keys(self) t0 = time.time() return [k for", "False return _version_checker(cryptography, (2, 0)) def isCryptographyAdvanced(): \"\"\" Check if", "**kwargs: _readonly(name)) ) ReadOnlyAttribute.__doc__ = \"Read-only class attribute\" class ProgPath(ConfClass):", "value in restore.items(): Interceptor.set_from_hook(conf, key, value) if isinstance(e, ScapyInvalidPlatformException): raise", "= os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\") use_bpf = Interceptor(\"use_bpf\", False, _socket_changer) use_npcap =", "but distutils imports imp which is deprecated version_regexp = r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?'", "hexedit = \"hexer\" tshark = \"tshark\" wireshark = \"wireshark\" ifconfig", "c in self._caches_list: c.flush() def __repr__(self): return \"\\n\".join(c.summary() for c", "if conf.use_bpf: from scapy.arch.bpf.supersocket import L2bpfListenSocket, \\ L2bpfSocket, L3bpfSocket conf.L3socket", "Conf.ipv6_enabled: log_scapy.warning(\"IPv6 support disabled in Python. Cannot load Scapy IPv6", "r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags = re.match(version_regexp, module.__version__) if not version_tags: return False", "running under PyPy or not\"\"\" try: import __pypy__ # noqa:", "provides methods to manipulate it warning_threshold : how much time", "noqa: E501 histfile : history file padding : includes padding", "IP citation match (bug in some NAT stacks) # noqa:", "in self.__slots__: return object.__setattr__(self, item, v) self._timetable[item] = time.time() dict.__setitem__(self,", "s[:-1] class Interceptor(object): def __init__(self, name=None, default=None, hook=None, args=None, kargs=None):", "and such (v2.0 or later). \"\"\" try: from cryptography.hazmat.primitives.asymmetric.x25519 import", "return elt in self.fields def __repr__(self): return \"<%s [%s]>\" %", "\"\\n\".join(s) class NetCache: def __init__(self): self._caches_list = [] def add_cache(self,", "len(r) > wlen: r = r[:wlen - 3] + \"...\"", "hook, use Interceptor.set_from_hook if conf.use_pcap or conf.use_dnet: try: from scapy.arch.pcapdnet", "% name setattr(obj, int_name, val) def __set__(self, obj, val): setattr(obj,", "if self._is_field(f)} self._recalc_layer_list() def remove(self, *flds): self.fields -= set(flds) self._recalc_layer_list()", "provider available ! pcap won't be used\") Interceptor.set_from_hook(conf, \"use_pcap\", False)", "func_in(*args, **kwargs): if not conf.crypto_valid: raise ImportError(\"Cannot execute crypto-related method!", "tshark = \"tshark\" wireshark = \"wireshark\" ifconfig = \"ifconfig\" class", "LooseVersion, but distutils imports imp which is deprecated version_regexp =", "min_pkt_size = 60 bufsize = 2**16 histfile = os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"),", "\"open\" if DARWIN else \"xdg-open\" pdfreader = universal_open psreader =", "that are not matched into debug.recv # noqa: E501 route", "six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout) # noqa: E501", "we are already in an Interceptor hook, use Interceptor.set_from_hook if", "layer.__name__, layer._name))) for layer, num in six.iteritems(self.layer2num): if num not", "pass class Resolve(ConfigFieldList): pass class Num2Layer: def __init__(self): self.num2layer =", "if conf.use_pcap or conf.use_dnet: try: from scapy.arch.pcapdnet import L2pcapListenSocket, L2pcapSocket,", "_prompt_changer) promisc = True sniff_promisc = 1 raw_layer = None", "from scapy.arch.windows import _NotAvailableSocket from scapy.arch.windows.native import L3WinSocket, L3WinSocket6 conf.L3socket", "layer._name))) for layer, num in six.iteritems(self.layer2num): if num not in", "stealth = \"not implemented\" iface = None iface6 = None", "= \"display\" tcpdump = \"tcpdump\" tcpreplay = \"tcpreplay\" hexedit =", "__repr__(self): return \"\\n\".join(\"%-20s: %s\" % (l.__name__, l.name) for l in", "def values(self): if self.timeout is None: return list(six.itervalues(self)) t0 =", "def add_cache(self, cache): self._caches_list.append(cache) setattr(self, cache.name, cache) def new_cache(self, name,", "key=lambda x: x.__name__): doc = l.__doc__.split(\"\\n\")[0] if l.__doc__ else \"--\"", "if 0, doesn't check that IPID matches between IP sent", "[k for k in six.iterkeys(self.__dict__) if t0 - self._timetable[k] <", "class to use extensions_paths: path or list of paths where", "\" \"Please install python-cryptography v1.7 or later.\") # noqa: E501", "= sorted(keys) for i in keys: if i[0] != \"_\":", "isinstance(elt, base_classes.Packet_metaclass): return elt in self.layers return elt in self.fields", "\"%#6x <- %-20s (%s)\" % (num, layer.__name__, layer._name))) lst.sort() return", "def summary(self): return \"%s: %i valid items. Timeout=%rs\" % (self.name,", "methods to manipulate it warning_threshold : how much time between", "\"use_pcap\": [\"use_bpf\"], \"use_bpf\": [\"use_pcap\"], } restore = {k: getattr(conf, k)", "Emphasize() use_pypy = ReadOnlyAttribute(\"use_pypy\", isPyPy()) use_pcap = Interceptor( \"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\",", "time.time() return [v for (k, v) in six.iteritems(self.__dict__) if t0", "under a GPLv2 license \"\"\" Implementation of the configuration object.", "self._caches_list) def _version_checker(module, minver): \"\"\"Checks that module has a higher", "tuple of versions \"\"\" # We could use LooseVersion, but", "noqa: E501 def items(self): if self.timeout is None: return dict.items(self)", "'rtp', 'sctp', 'sixlowpan', 'skinny', 'smb', 'snmp', 'tftp', 'vrrp', 'vxlan', 'x509',", ") # XXX use_dnet is deprecated use_dnet = os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\")", "return object.__getattr__(self, attr) if not Conf.ipv6_enabled: log_scapy.warning(\"IPv6 support disabled in", "dict.keys(self) t0 = time.time() return [k for k in six.iterkeys(self.__dict__)", "__str__(self): s = \"\" keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys =", "svgreader = universal_open dot = \"dot\" display = \"display\" tcpdump", "part of Scapy # See http://www.secdev.org/projects/scapy for more information #", "self.timeout is None: return dict.items(self) t0 = time.time() return [(k,", "not version_tags: return False version_tags = version_tags.group(1).split(\".\") version_tags = tuple(int(x)", "Those are loaded on runtime to avoid import loops if", "obj, typ=None): if not hasattr(obj, self.intname): setattr(obj, self.intname, self.default) return", "dict.__len__(self) return len(self.keys()) def summary(self): return \"%s: %i valid items.", "the cryptography library is recent (2.0 and later) \"\"\" try:", ": can be \"ipython\", \"python\" or \"auto\". Default: Auto stealth", "= dict.__getitem__(self, item) if self.timeout is not None: t =", "check that IPID matches between IP sent and ICMP IP", "or later.\") # noqa: E501 return func(*args, **kwargs) return func_in", "module: a module to test - minver: a tuple of", "packet to go out (ARP, DNS, ...) checkIPID: if 0,", "- self._timetable[k] < self.timeout] # noqa: E501 def keys(self): if", "% (i, r) return s[:-1] class Interceptor(object): def __init__(self, name=None,", "= max(len(k) for k in six.iterkeys(self.__dict__)) fmt = \"%%-%is %%s\"", "class ConfigFieldList: def __init__(self): self.fields = set() self.layers = set()", "crypto-related method! \" \"Please install python-cryptography v1.7 or later.\") #", "layer): self.num2layer[num] = layer def register_layer2num(self, num, layer): self.layer2num[layer] =", "if kargs is not None else {} def __get__(self, obj,", "typ=None): if not hasattr(obj, self.intname): setattr(obj, self.intname, self.default) return getattr(obj,", "self.timeout is None: return dict.__len__(self) return len(self.keys()) def summary(self): return", "from scapy.data import IP_PROTOS return IP_PROTOS if attr == \"services_udp\":", "layer) def register_num2layer(self, num, layer): self.num2layer[num] = layer def register_layer2num(self,", "# noqa: E501 checkIPinIP: if True, checks that IP-in-IP layers", "not in self.ldict: self.ldict[layer.__module__] = [] self.ldict[layer.__module__].append(layer) def layers(self): result", "published under a GPLv2 license \"\"\" Implementation of the configuration", "= ['bluetooth', 'bluetooth4LE', 'dhcp', 'dhcp6', 'dns', 'dot11', 'dot15d4', 'eap', 'gprs',", "{ # Things that will be turned off \"use_pcap\": [\"use_bpf\"],", "cryptography library. # noqa: E501 Its behaviour depends on the", "- t > self.timeout: raise KeyError(item) return val def get(self,", "name, val): int_name = \"_intercepted_%s\" % name setattr(obj, int_name, val)", "\"\"\"Checks that module has a higher version that minver. params:", "packets to ignore debug_match : when 1, store received packet", "isPyPy(): \"\"\"Returns either scapy is running under PyPy or not\"\"\"", "+ 1) for item in six.iteritems(self.__dict__): s.append(fmt % item) return", "if self.timeout is None: return six.iteritems(self.__dict__) t0 = time.time() return", "== \"services_udp\": from scapy.data import UDP_SERVICES return UDP_SERVICES if attr", "it is required for the eval below import scapy #", "six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout] # noqa: E501", "return [(k, v) for (k, v) in six.iteritems(self.__dict__) if t0", "Interceptor.set_from_hook(conf, \"use_bpf\", False) raise ScapyInvalidPlatformException(\"BSD-like (OSX, *BSD...) only !\") if", "else lay)) return result class CommandsList(list): def __repr__(self): s =", "\"\"\" Check if the cryptography library is present, and if", "- module: a module to test - minver: a tuple", "return False else: return True def isPyPy(): \"\"\"Returns either scapy", "_recalc_layer_list(self): self.layers = {owner for f in self.fields for owner", "go through # the timetable check try: return self[item] except", "conf.L3socket6 = functools.partial(L3bpfSocket, filter=\"ip6\") conf.L2socket = L2bpfSocket conf.L2listen = L2bpfListenSocket", "= True debug_dissector = False color_theme = Interceptor(\"color_theme\", NoTheme(), _prompt_changer)", "layer check_TCPerror_seqack: if 1, also check that TCP seq and", "register_layer2num(self, num, layer): self.layer2num[layer] = num def __getitem__(self, item): if", "avoid import loops if attr == \"manufdb\": from scapy.data import", "\"\"\" # We could use LooseVersion, but distutils imports imp", "s = [] for l in sorted(self, key=lambda x: x.__name__):", "in dependencies[attr]: Interceptor.set_from_hook(conf, param, False) try: _set_conf_sockets() except (ScapyInvalidPlatformException, ImportError)", "= None # can, tls, http are not loaded by", "for listening socket (to get answers if you spoof on", "return self[item] except KeyError: return default def __setitem__(self, item, v):", "IPID matches between IP sent and ICMP IP citation received", "bufsize = 2**16 histfile = os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"), \".scapy_history\")) padding =", "import VERSION, base_classes from scapy.consts import DARWIN, WINDOWS, LINUX, BSD,", "L2ListenSocket conf.L3socket = L3PacketSocket conf.L3socket6 = functools.partial(L3PacketSocket, filter=\"ip6\") conf.L2socket =", "val) self.hook(self.name, val, *self.args, **self.kargs) def _readonly(name): default = Conf.__dict__[name].default", "False) else: conf.L3socket = L3pcapSocket conf.L3socket6 = functools.partial(L3pcapSocket, filter=\"ip6\") conf.L2socket", "This import may feel useless, but it is required for", "item in self.__slots__: return object.__getattribute__(self, item) val = dict.__getitem__(self, item)", "color_theme = Interceptor(\"color_theme\", NoTheme(), _prompt_changer) warning_threshold = 5 prog =", "import L3RawSocket from scapy.layers.inet6 import L3RawSocket6 conf.L3socket = L3RawSocket conf.L3socket6", "class Resolve(ConfigFieldList): pass class Num2Layer: def __init__(self): self.num2layer = {}", "from scapy.layers.inet6 import L3RawSocket6 conf.L3socket = L3RawSocket conf.L3socket6 = L3RawSocket6", "functools import os import re import time import socket import", "restore.items(): Interceptor.set_from_hook(conf, key, value) if isinstance(e, ScapyInvalidPlatformException): raise def _loglevel_changer(attr,", "def func_in(*args, **kwargs): if not conf.crypto_valid: raise ImportError(\"Cannot execute crypto-related", "extensions are to be looked for contribs : a dict", "enum fields for which conversion to string should NOT be", "key, value) self._timetable[key] = other._timetable[key] def iteritems(self): if self.timeout is", "checks that they either are equal or byte swapped equals", "set(flds) self._recalc_layer_list() def __contains__(self, elt): if isinstance(elt, base_classes.Packet_metaclass): return elt", "raw_summary = False default_l2 = None l2types = Num2Layer() l3types", "!\") ReadOnlyAttribute = functools.partial( Interceptor, hook=(lambda name, *args, **kwargs: _readonly(name))", "more information # Copyright (C) <NAME> <<EMAIL>> # This program", "use_npcap = False ipv6_enabled = socket.has_ipv6 extensions_paths = \".\" stats_classic_protocols", "E501 class Emphasize(ConfigFieldList): pass class Resolve(ConfigFieldList): pass class Num2Layer: def", "dict() crypto_valid = isCryptographyValid() crypto_valid_recent = isCryptographyRecent() crypto_valid_advanced = crypto_valid_recent", "conf.logLevel\"\"\" log_scapy.setLevel(val) class Conf(ConfClass): \"\"\"This object contains the configuration of", "# Config # ############ class ConfClass(object): def configure(self, cnf): self.__dict__", "contribs = dict() crypto_valid = isCryptographyValid() crypto_valid_recent = isCryptographyRecent() crypto_valid_advanced", "in ICMP citation # noqa: E501 iff : selects the", "\"\" stealth = \"not implemented\" iface = None iface6 =", "base_classes.Packet_metaclass): return elt in self.layers return elt in self.fields def", "scapy.supersocket import L3RawSocket from scapy.layers.inet6 import L3RawSocket6 conf.L3socket = L3RawSocket", "log_scapy, warning, ScapyInvalidPlatformException from scapy.modules import six from scapy.themes import", "co in other._caches_list: if hasattr(self, co.name): getattr(self, co.name).update(co) else: self.add_cache(co.copy())", "[] # This import may feel useless, but it is", "load_layers = ['bluetooth', 'bluetooth4LE', 'dhcp', 'dhcp6', 'dns', 'dot11', 'dot15d4', 'eap',", "self.timeout) # noqa: E501 def __iter__(self): return six.iterkeys(self.__dict__) def itervalues(self):", "raise TypeError(\"This argument should be a boolean\") dependencies = {", "to the various use_* parameters \"\"\" from scapy.main import _load", "store local configuration # noqa: E501 debug_tls:When 1, print some", "functools.partial(L3bpfSocket, filter=\"ip6\") conf.L2socket = L2bpfSocket conf.L2listen = L2bpfListenSocket # Update", "contrib layers to store local configuration # noqa: E501 debug_tls:When", "python-cryptography v1.7 or later.\") # noqa: E501 return func(*args, **kwargs)", "None: return dict.__len__(self) return len(self.keys()) def summary(self): return \"%s: %i", "sniff_promisc : default mode for sniff() filter : bpf filter", "get(self, item, default=None): # overloading this method is needed to", "in six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout] # noqa:", "\"\"\"Populate the conf.L2Socket and conf.L3Socket according to the various use_*", "__future__ import print_function import functools import os import re import", "__getitem__(self, item): if isinstance(item, base_classes.Packet_metaclass): return self.layer2num[item] return self.num2layer[item] def", "\"%%-%is %%s\" % (mk + 1) for item in six.iteritems(self.__dict__):", "default self.hook = hook self.args = args if args is", "(i, r) return s[:-1] class Interceptor(object): def __init__(self, name=None, default=None,", "checks that they are equals checkIPsrc: if 1, checks IP", "object contains the configuration of Scapy. session : filename where", "except_filter = \"\" debug_match = False debug_tls = False wepkey", "F401 return True except ImportError: return False def _prompt_changer(attr, val):", "crypto_validator(func): \"\"\" This a decorator to be used for any", "re.match(version_regexp, module.__version__) if not version_tags: return False version_tags = version_tags.group(1).split(\".\")", "def lsc(): \"\"\"Displays Scapy's default commands\"\"\" print(repr(conf.commands)) class CacheInstance(dict, object):", "tuple(int(x) for x in version_tags) return version_tags >= minver def", "in self.ldict: doc = eval(lay).__doc__ result.append((lay, doc.strip().split(\"\\n\")[0] if doc else", "import loops if attr == \"manufdb\": from scapy.data import MANUFDB", "where extensions are to be looked for contribs : a", "supports X25519, ChaCha20Poly1305 and such (v2.0 or later). \"\"\" try:", "not isinstance(val, bool): raise TypeError(\"This argument should be a boolean\")", "return s[:-1] class Interceptor(object): def __init__(self, name=None, default=None, hook=None, args=None,", "%s\\n\" % (i, r) return s[:-1] class Interceptor(object): def __init__(self,", "return six.iteritems(self.__dict__) t0 = time.time() return ((k, v) for (k,", "\"python\" or \"auto\". Default: Auto stealth : if 1, prevents", "prog = ProgPath() resolve = Resolve() noenum = Resolve() emph", "version_tags: return False version_tags = version_tags.group(1).split(\".\") version_tags = tuple(int(x) for", "'mobileip', 'netbios', 'netflow', 'ntp', 'ppi', 'ppp', 'pptp', 'radius', 'rip', 'rtp',", "E501 def __len__(self): if self.timeout is None: return dict.__len__(self) return", "t0 = time.time() return [(k, v) for (k, v) in", "sys.ps1 = conf.color_theme.prompt(conf.prompt) except Exception: pass try: apply_ipython_style(get_ipython()) except NameError:", "a decorator def lsc(): \"\"\"Displays Scapy's default commands\"\"\" print(repr(conf.commands)) class", "by contrib layers to store local configuration # noqa: E501", "try: import cryptography except ImportError: return False return _version_checker(cryptography, (2,", "from scapy import VERSION, base_classes from scapy.consts import DARWIN, WINDOWS,", "if it is recent enough for most usages in scapy", "False, _socket_changer) use_npcap = False ipv6_enabled = socket.has_ipv6 extensions_paths =", "in self.ldict: self.ldict[layer.__module__] = [] self.ldict[layer.__module__].append(layer) def layers(self): result =", "versions \"\"\" # We could use LooseVersion, but distutils imports", "return True except ImportError: return False def _prompt_changer(attr, val): \"\"\"Change", "use_pcap = Interceptor( \"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"), _socket_changer ) # XXX", "keys = sorted(keys) for i in keys: if i[0] !=", "for lay in self.ldict: doc = eval(lay).__doc__ result.append((lay, doc.strip().split(\"\\n\")[0] if", "default for ASN1 objects mib : holds MIB direct access", "for m in [\"inet6\", \"dhcp6\"]: if m in Conf.load_layers: Conf.load_layers.remove(m)", "repr(getattr(self, i)) r = \" \".join(r.split()) wlen = 76 -", "_version_checker(cryptography, (2, 0)) def isCryptographyAdvanced(): \"\"\" Check if the cryptography", "that they either are equal or byte swapped equals (bug", "of the configuration object. \"\"\" from __future__ import absolute_import from", "max(len(k) for k in six.iterkeys(self.__dict__)) fmt = \"%%-%is %%s\" %", "# noqa: E501 if 1, checks that they either are", "if self.timeout is None: return list(six.itervalues(self)) t0 = time.time() return", "...) checkIPID: if 0, doesn't check that IPID matches between", "import X25519PrivateKey # noqa: E501 X25519PrivateKey.generate() except Exception: return False", "a dict which can be used by contrib layers to", "update(self, other): for co in other._caches_list: if hasattr(self, co.name): getattr(self,", "scapy.data import UDP_SERVICES return UDP_SERVICES if attr == \"services_tcp\": from", "self.num2layer or self.num2layer[num] != layer: lst.append((num, \"%#6x <- %-20s (%s)\"", "= \"tcpdump\" tcpreplay = \"tcpreplay\" hexedit = \"hexer\" tshark =", "{owner for f in self.fields for owner in f.owners} def", "_version_checker(module, minver): \"\"\"Checks that module has a higher version that", "return hasattr(f, \"owners\") def _recalc_layer_list(self): self.layers = {owner for f", ": holds MIB direct access dictionary resolve : holds list", "CacheInstance(dict, object): __slots__ = [\"timeout\", \"name\", \"_timetable\", \"__dict__\"] def __init__(self,", "filter for packets to ignore debug_match : when 1, store", "a GPLv2 license \"\"\" Implementation of the configuration object. \"\"\"", "emph = Emphasize() use_pypy = ReadOnlyAttribute(\"use_pypy\", isPyPy()) use_pcap = Interceptor(", "L3RawSocket6 def _socket_changer(attr, val): if not isinstance(val, bool): raise TypeError(\"This", "return \"\\n\".join(s) class NetCache: def __init__(self): self._caches_list = [] def", "in scapy (v1.7 or later). \"\"\" try: import cryptography except", "fancy_prompt = True auto_crop_tables = True recv_poll_rate = 0.05 def", "matched into debug.recv # noqa: E501 route : holds the", "r = repr(getattr(self, i)) r = \" \".join(r.split()) wlen =", "# noqa: E501 def keys(self): if self.timeout is None: return", "print some TLS session secrets when they are computed. recv_poll_rate:", "needed to force the dict to go through # the", "# Things that will be turned off \"use_pcap\": [\"use_bpf\"], \"use_bpf\":", "return IP_PROTOS if attr == \"services_udp\": from scapy.data import UDP_SERVICES", "USBsocket = None min_pkt_size = 60 bufsize = 2**16 histfile", "scapy.consts import DARWIN, WINDOWS, LINUX, BSD, SOLARIS from scapy.error import", "isCryptographyAdvanced(): \"\"\" Check if the cryptography library is present, and", "def _is_field(f): return hasattr(f, \"owners\") def _recalc_layer_list(self): self.layers = {owner", "self.ldict = {} def __repr__(self): return \"\\n\".join(\"%-20s: %s\" % (l.__name__,", "in self.num2layer def get(self, item, default=None): return self[item] if item", "itervalues(self): if self.timeout is None: return six.itervalues(self.__dict__) t0 = time.time()", "is required for the eval below import scapy # noqa:", "present, and if it is recent enough for most usages", "L3WinSocket, L3WinSocket6 conf.L3socket = L3WinSocket conf.L3socket6 = L3WinSocket6 conf.L2socket =", "attribute of the global 'conf'. \"\"\" def func_in(*args, **kwargs): if", "conf.use_dnet: try: from scapy.arch.pcapdnet import L2pcapListenSocket, L2pcapSocket, \\ L3pcapSocket except", "for k in six.iterkeys(self.__dict__)) fmt = \"%%-%is %%s\" % (mk", "\"dhcp6\"]: if m in Conf.load_layers: Conf.load_layers.remove(m) conf = Conf() def", "return (k for k in six.iterkeys(self.__dict__) if t0 - self._timetable[k]", "L2pcapListenSocket, L2pcapSocket, \\ L3pcapSocket except (OSError, ImportError): warning(\"No libpcap provider", "self._timetable[k] < self.timeout] # noqa: E501 def __len__(self): if self.timeout", "from scapy.arch.windows.native import L3WinSocket, L3WinSocket6 conf.L3socket = L3WinSocket conf.L3socket6 =", "import re import time import socket import sys from scapy", "\"_intercepted_%s\" % name setattr(obj, int_name, val) def __set__(self, obj, val):", "\"%-10s = %s\\n\" % (i, r) return s[:-1] class Interceptor(object):", "self.timeout) # noqa: E501 def items(self): if self.timeout is None:", "register(self, num, layer): self.register_num2layer(num, layer) self.register_layer2num(num, layer) def register_num2layer(self, num,", "Timeout=%rs\" % (self.name, len(self), self.timeout) # noqa: E501 def __repr__(self):", "ScapyInvalidPlatformException from scapy.modules import six from scapy.themes import NoTheme, apply_ipython_style", "iff : selects the default output interface for srp() and", "verb : level of verbosity, from 0 (almost mute) to", "self.add_cache(co.copy()) def flush(self): for c in self._caches_list: c.flush() def __repr__(self):", "except NameError: pass def _set_conf_sockets(): \"\"\"Populate the conf.L2Socket and conf.L3Socket", "5 prog = ProgPath() resolve = Resolve() noenum = Resolve()", "(self.name, len(self), self.timeout) # noqa: E501 def __repr__(self): s =", "library is present, and if it is recent enough for", "self.layer2num and self.layer2num[layer] == num: dir = \"<->\" else: dir", ": if 1, prevents any unwanted packet to go out", "DARWIN, WINDOWS, LINUX, BSD, SOLARIS from scapy.error import log_scapy, warning,", "__init__(self): self.fields = set() self.layers = set() @staticmethod def _is_field(f):", "\"\").lower().startswith(\"y\"), _socket_changer ) # XXX use_dnet is deprecated use_dnet =", "(l.__name__, l.name) for l in self) def register(self, layer): self.append(layer)", "under PyPy or not\"\"\" try: import __pypy__ # noqa: F401", "argument should be a boolean\") dependencies = { # Things", "[] netcache = NetCache() geoip_city = None # can, tls,", "six.iterkeys(self.__dict__) def itervalues(self): if self.timeout is None: return six.itervalues(self.__dict__) t0", "return \"%s: %i valid items. Timeout=%rs\" % (self.name, len(self), self.timeout)", "self.num2layer[num] = layer def register_layer2num(self, num, layer): self.layer2num[layer] = num", "name self._timetable = {} def flush(self): self.__init__(name=self.name, timeout=self.timeout) def __getitem__(self,", "_version_checker(cryptography, (1, 7)) def isCryptographyRecent(): \"\"\" Check if the cryptography", "checkIPaddr = True checkIPinIP = True check_TCPerror_seqack = False verb", "IP stacks) # noqa: E501 if 2, strictly checks that", "debug.recv # noqa: E501 route : holds the Scapy routing", "= None # Used in dot15d4.py logLevel = Interceptor(\"logLevel\", log_scapy.level,", "True recv_poll_rate = 0.05 def __getattr__(self, attr): # Those are", "'ntp', 'ppi', 'ppp', 'pptp', 'radius', 'rip', 'rtp', 'sctp', 'sixlowpan', 'skinny',", "(almost mute) to 3 (verbose) promisc : default mode for", "enough for most usages in scapy (v1.7 or later). \"\"\"", "Python. Cannot load Scapy IPv6 layers.\") # noqa: E501 for", "\"_timetable\", \"__dict__\"] def __init__(self, name=\"noname\", timeout=None): self.timeout = timeout self.name", "None l2types = Num2Layer() l3types = Num2Layer() L3socket = None", "def __str__(self): s = \"\" keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys", "six.iterkeys(self.__dict__)) fmt = \"%%-%is %%s\" % (mk + 1) for", "This file is part of Scapy # See http://www.secdev.org/projects/scapy for", "name, *args, **kwargs: _readonly(name)) ) ReadOnlyAttribute.__doc__ = \"Read-only class attribute\"", "to manipulate it warning_threshold : how much time between warnings", "= True auto_crop_tables = True recv_poll_rate = 0.05 def __getattr__(self,", "if not hasattr(obj, self.intname): setattr(obj, self.intname, self.default) return getattr(obj, self.intname)", "the cryptography library is present, and if it is recent", "class attribute\" class ProgPath(ConfClass): universal_open = \"open\" if DARWIN else", "- self._timetable[k] < self.timeout) # noqa: E501 def iterkeys(self): if", "def _set_conf_sockets(): \"\"\"Populate the conf.L2Socket and conf.L3Socket according to the", "check try: return self[item] except KeyError: return default def __setitem__(self,", "from scapy.arch.linux import L3PacketSocket, L2Socket, L2ListenSocket conf.L3socket = L3PacketSocket conf.L3socket6", "extensions_paths: path or list of paths where extensions are to", "holds MIB direct access dictionary resolve : holds list of", "def __get__(self, obj, typ=None): if not hasattr(obj, self.intname): setattr(obj, self.intname,", "c in self._caches_list) def _version_checker(module, minver): \"\"\"Checks that module has", "scapy.arch.windows.native import L3WinSocket, L3WinSocket6 conf.L3socket = L3WinSocket conf.L3socket6 = L3WinSocket6", "is None: return six.itervalues(self.__dict__) t0 = time.time() return (v for", "self.register_layer2num(num, layer) def register_num2layer(self, num, layer): self.num2layer[num] = layer def", "Scapy IPv6 layers.\") # noqa: E501 for m in [\"inet6\",", "noenum : holds list of enum fields for which conversion", "srp() and sendp(). default:\"eth0\") # noqa: E501 verb : level", "i in keys: if i[0] != \"_\": r = repr(getattr(self,", "which can be used by contrib layers to store local", "of enum fields for which conversion to string should NOT", "def __init__(self): self.num2layer = {} self.layer2num = {} def register(self,", "that they are equals checkIPsrc: if 1, checks IP src", "or later). \"\"\" try: from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # noqa:", "_NotAvailableSocket conf.L2listen = _NotAvailableSocket # No need to update globals", "or if the entry in `self` is older. if key", "check_TCPerror_seqack = False verb = 2 prompt = Interceptor(\"prompt\", \">>>", "l in self) def register(self, layer): self.append(layer) if layer.__module__ not", "the configuration object. \"\"\" from __future__ import absolute_import from __future__", "name self.default = default self.hook = hook self.args = args", "self.layers return elt in self.fields def __repr__(self): return \"<%s [%s]>\"", "deprecated use_dnet = os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\") use_bpf = Interceptor(\"use_bpf\", False, _socket_changer)", "`other` either if it does # not exist in `self`", "netcache = NetCache() geoip_city = None # can, tls, http", "def update(self, other): for co in other._caches_list: if hasattr(self, co.name):", "_set_conf_sockets() except (ScapyInvalidPlatformException, ImportError) as e: for key, value in", "when they are computed. recv_poll_rate: how often to check for", "raise def _loglevel_changer(attr, val): \"\"\"Handle a change of conf.logLevel\"\"\" log_scapy.setLevel(val)", "restore = {k: getattr(conf, k) for k in dependencies} del", "Scapy's default commands\"\"\" print(repr(conf.commands)) class CacheInstance(dict, object): __slots__ = [\"timeout\",", "IP and ICMP IP citation match (bug in some NAT", "checkIPID: if 0, doesn't check that IPID matches between IP", "it warning_threshold : how much time between warnings from the", "\"\"\" Implementation of the configuration object. \"\"\" from __future__ import", "default def __setitem__(self, item, v): if item in self.__slots__: return", "\"\"\" try: from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # noqa: E501 X25519PrivateKey.generate()", "= True sniff_promisc = 1 raw_layer = None raw_summary =", "= eval(lay).__doc__ result.append((lay, doc.strip().split(\"\\n\")[0] if doc else lay)) return result", "1, store received packet that are not matched into debug.recv", "@staticmethod def _is_field(f): return hasattr(f, \"owners\") def _recalc_layer_list(self): self.layers =", "loaded on runtime to avoid import loops if attr ==", "Interceptor.set_from_hook(conf, name, default) raise ValueError(\"Read-only value !\") ReadOnlyAttribute = functools.partial(", "def register(self, cmd): self.append(cmd) return cmd # return cmd so", "self.fields -= set(flds) self._recalc_layer_list() def __contains__(self, elt): if isinstance(elt, base_classes.Packet_metaclass):", "module to test - minver: a tuple of versions \"\"\"", "__repr__(self): lst = [] for num, layer in six.iteritems(self.num2layer): if", "self.__init__(name=self.name, timeout=self.timeout) def __getitem__(self, item): if item in self.__slots__: return", "'ir', 'isakmp', 'l2', 'l2tp', 'llmnr', 'lltd', 'mgcp', 'mobileip', 'netbios', 'netflow',", "checkIPinIP: if True, checks that IP-in-IP layers match. If False,", "return self.num2layer[item] def __contains__(self, item): if isinstance(item, base_classes.Packet_metaclass): return item", ": how much time between warnings from the same place", "item, v) def update(self, other): for key, value in six.iteritems(other):", "LINUX, BSD, SOLARIS from scapy.error import log_scapy, warning, ScapyInvalidPlatformException from", "name, default) raise ValueError(\"Read-only value !\") ReadOnlyAttribute = functools.partial( Interceptor,", "Interceptor.set_from_hook(conf, \"use_pcap\", False) else: conf.L3socket = L3pcapSocket conf.L3socket6 = functools.partial(L3pcapSocket,", "TypeError(\"This argument should be a boolean\") dependencies = { #", "1 except_filter = \"\" debug_match = False debug_tls = False", "or self.num2layer[num] != layer: lst.append((num, \"%#6x <- %-20s (%s)\" %", "= \"%%-%is %%s\" % (mk + 1) for item in", "the configuration of Scapy. session : filename where the session", "for x in version_tags) return version_tags >= minver def isCryptographyValid():", "self.fields)) # noqa: E501 class Emphasize(ConfigFieldList): pass class Resolve(ConfigFieldList): pass", "later). \"\"\" try: from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # noqa: E501", "from scapy.supersocket import L3RawSocket from scapy.layers.inet6 import L3RawSocket6 conf.L3socket =", "they are equals checkIPsrc: if 1, checks IP src in", "ICMP IP citation match (bug in some NAT stacks) #", "= None layers = LayersList() commands = CommandsList() dot15d4_protocol =", "dict.__setitem__(self, key, value) self._timetable[key] = other._timetable[key] def iteritems(self): if self.timeout", "f.owners} def add(self, *flds): self.fields |= {f for f in", "# noqa: E501 route : holds the Scapy routing table", "(k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout]", "\"\"\" Check if the cryptography library is recent (2.0 and", "ImportError: return False return _version_checker(cryptography, (1, 7)) def isCryptographyRecent(): \"\"\"", "swapped equals (bug in some IP stacks) # noqa: E501", "max(len(i), 10) if len(r) > wlen: r = r[:wlen -", "except ImportError: return False def _prompt_changer(attr, val): \"\"\"Change the current", "in self.fields for owner in f.owners} def add(self, *flds): self.fields", "= \"not implemented\" iface = None iface6 = None layers", "self.intname): setattr(obj, self.intname, self.default) return getattr(obj, self.intname) @staticmethod def set_from_hook(obj,", "cryptography except ImportError: return False return _version_checker(cryptography, (2, 0)) def", "False interactive_shell = \"\" stealth = \"not implemented\" iface =", "\"ethertypes\": from scapy.data import ETHER_TYPES return ETHER_TYPES if attr ==", "return six.iterkeys(self.__dict__) t0 = time.time() return (k for k in", "holds the Scapy routing table and provides methods to manipulate", "2, strictly checks that they are equals checkIPsrc: if 1,", "ImportError: return False def _prompt_changer(attr, val): \"\"\"Change the current prompt", "None USBsocket = None min_pkt_size = 60 bufsize = 2**16", "Its behaviour depends on the 'crypto_valid' attribute of the global", "that will be turned off \"use_pcap\": [\"use_bpf\"], \"use_bpf\": [\"use_pcap\"], }", "# noqa: E501 def values(self): if self.timeout is None: return", "return \"\\n\".join(s) def register(self, cmd): self.append(cmd) return cmd # return", "method can be used as a decorator def lsc(): \"\"\"Displays", "\".join(r.split()) wlen = 76 - max(len(i), 10) if len(r) >", "local configuration # noqa: E501 debug_tls:When 1, print some TLS", "IP src in IP and ICMP IP citation match (bug", "go out (ARP, DNS, ...) checkIPID: if 0, doesn't check", "! pcap won't be used\") Interceptor.set_from_hook(conf, \"use_pcap\", False) else: conf.L3socket", "v): if item in self.__slots__: return object.__setattr__(self, item, v) self._timetable[item]", "\"use_bpf\", False) raise ScapyInvalidPlatformException(\"BSD-like (OSX, *BSD...) only !\") if not", "Config # ############ class ConfClass(object): def configure(self, cnf): self.__dict__ =", "default = Conf.__dict__[name].default Interceptor.set_from_hook(conf, name, default) raise ValueError(\"Read-only value !\")", "timeout=None): self.timeout = timeout self.name = name self._timetable = {}", "NoTheme(), _prompt_changer) warning_threshold = 5 prog = ProgPath() resolve =", "for key, value in restore.items(): Interceptor.set_from_hook(conf, key, value) if isinstance(e,", "True except ImportError: return False def _prompt_changer(attr, val): \"\"\"Change the", "_loglevel_changer(attr, val): \"\"\"Handle a change of conf.logLevel\"\"\" log_scapy.setLevel(val) class Conf(ConfClass):", "prevents any unwanted packet to go out (ARP, DNS, ...)", "received # noqa: E501 if 1, checks that they either", "IP citation received # noqa: E501 if 1, checks that", "a decorator to be used for any method relying on", "def new_cache(self, name, timeout=None): c = CacheInstance(name=name, timeout=timeout) self.add_cache(c) def", "in Conf.load_layers: Conf.load_layers.remove(m) conf = Conf() def crypto_validator(func): \"\"\" This", "not conf.crypto_valid: raise ImportError(\"Cannot execute crypto-related method! \" \"Please install", "default:\"eth0\") # noqa: E501 verb : level of verbosity, from", "session secrets when they are computed. recv_poll_rate: how often to", "[] for l in sorted(self, key=lambda x: x.__name__): doc =", "scapy.data import IP_PROTOS return IP_PROTOS if attr == \"services_udp\": from", "\"hexer\" tshark = \"tshark\" wireshark = \"wireshark\" ifconfig = \"ifconfig\"", "import scapy # noqa: F401 for lay in self.ldict: doc", "hook self.args = args if args is not None else", "noqa: E501 iff : selects the default output interface for", "in self.num2layer or self.num2layer[num] != layer: lst.append((num, \"%#6x <- %-20s", "filter added to every sniffing socket to exclude traffic from", "def iterkeys(self): if self.timeout is None: return six.iterkeys(self.__dict__) t0 =", "L2pcapSocket conf.L2listen = L2pcapListenSocket # Update globals _load(\"scapy.arch.pcapdnet\") return if", "base_classes.Packet_metaclass): return item in self.layer2num return item in self.num2layer def", "= [] # This import may feel useless, but it", "layer in six.iteritems(self.num2layer): if layer in self.layer2num and self.layer2num[layer] ==", "self.timeout is None: return six.iterkeys(self.__dict__) t0 = time.time() return (k", "\"<%s [%s]>\" % (self.__class__.__name__, \" \".join(str(x) for x in self.fields))", "time.time() return [(k, v) for (k, v) in six.iteritems(self.__dict__) if", "attr == \"ethertypes\": from scapy.data import ETHER_TYPES return ETHER_TYPES if", "print(repr(conf.commands)) class CacheInstance(dict, object): __slots__ = [\"timeout\", \"name\", \"_timetable\", \"__dict__\"]", "x in version_tags) return version_tags >= minver def isCryptographyValid(): \"\"\"", "in Python. Cannot load Scapy IPv6 layers.\") # noqa: E501", "= \"\" interactive = False interactive_shell = \"\" stealth =", "are computed. recv_poll_rate: how often to check for new packets.", "obj, val): setattr(obj, self.intname, val) self.hook(self.name, val, *self.args, **self.kargs) def", "six.itervalues(self.__dict__) t0 = time.time() return (v for (k, v) in", "Copyright (C) <NAME> <<EMAIL>> # This program is published under", "return False version_tags = version_tags.group(1).split(\".\") version_tags = tuple(int(x) for x", "L3PacketSocket conf.L3socket6 = functools.partial(L3PacketSocket, filter=\"ip6\") conf.L2socket = L2Socket conf.L2listen =", "kargs is not None else {} def __get__(self, obj, typ=None):", "version_tags = tuple(int(x) for x in version_tags) return version_tags >=", "of versions \"\"\" # We could use LooseVersion, but distutils", "[v for (k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k]", "None iface6 = None layers = LayersList() commands = CommandsList()", "decorator to be used for any method relying on the", "s += \"%-10s = %s\\n\" % (i, r) return s[:-1]", "version_tags.group(1).split(\".\") version_tags = tuple(int(x) for x in version_tags) return version_tags", "dir = \"<->\" else: dir = \" ->\" lst.append((num, \"%#6x", "ack match the ones in ICMP citation # noqa: E501", "default def __repr__(self): lst = [] for num, layer in", "False color_theme = Interceptor(\"color_theme\", NoTheme(), _prompt_changer) warning_threshold = 5 prog", "for most usages in scapy (v1.7 or later). \"\"\" try:", "%%s\" % (mk + 1) for item in six.iteritems(self.__dict__): s.append(fmt", "kargs if kargs is not None else {} def __get__(self,", "%s %-20s (%s)\" % (num, dir, layer.__name__, layer._name))) for layer,", "import __pypy__ # noqa: F401 return True except ImportError: return", "try: import __pypy__ # noqa: F401 return True except ImportError:", "layers(self): result = [] # This import may feel useless,", "time.time() return (v for (k, v) in six.iteritems(self.__dict__) if t0", "DARWIN else \"xdg-open\" pdfreader = universal_open psreader = universal_open svgreader", "noqa: E501 def iterkeys(self): if self.timeout is None: return six.iterkeys(self.__dict__)", "return default def __setitem__(self, item, v): if item in self.__slots__:", "overloading this method is needed to force the dict to", "1, checks IP src in IP and ICMP IP citation", "noqa: E501 verb : level of verbosity, from 0 (almost", "[\"use_pcap\"], } restore = {k: getattr(conf, k) for k in", "check IP layers that encapsulates another IP layer check_TCPerror_seqack: if", "i)) r = \" \".join(r.split()) wlen = 76 - max(len(i),", "which conversion to string should NOT be done # noqa:", "False return _version_checker(cryptography, (1, 7)) def isCryptographyRecent(): \"\"\" Check if", "conf.L2socket = L2Socket conf.L2listen = L2ListenSocket # Update globals _load(\"scapy.arch.linux\")", "\"tcpreplay\" hexedit = \"hexer\" tshark = \"tshark\" wireshark = \"wireshark\"", "minver: a tuple of versions \"\"\" # We could use", "paths where extensions are to be looked for contribs :", "= \"\" stealth = \"not implemented\" iface = None iface6", "\", _prompt_changer) promisc = True sniff_promisc = 1 raw_layer =", "equals (bug in some IP stacks) # noqa: E501 if", "def __contains__(self, elt): if isinstance(elt, base_classes.Packet_metaclass): return elt in self.layers", "WINDOWS: from scapy.arch.windows import _NotAvailableSocket from scapy.arch.windows.native import L3WinSocket, L3WinSocket6", "promisc : default mode for listening socket (to get answers", "self._timetable[k] < self.timeout] # noqa: E501 def keys(self): if self.timeout", "(2.0 and later) \"\"\" try: import cryptography except ImportError: return", "try: apply_ipython_style(get_ipython()) except NameError: pass def _set_conf_sockets(): \"\"\"Populate the conf.L2Socket", "args is not None else [] self.kargs = kargs if", "value !\") ReadOnlyAttribute = functools.partial( Interceptor, hook=(lambda name, *args, **kwargs:", "for k in six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout]", "\\ L2bpfSocket, L3bpfSocket conf.L3socket = L3bpfSocket conf.L3socket6 = functools.partial(L3bpfSocket, filter=\"ip6\")", "matches between IP sent and ICMP IP citation received #", "(v1.7 or later). \"\"\" try: import cryptography except ImportError: return", "usages in scapy (v1.7 or later). \"\"\" try: import cryptography", "noqa: E501 AS_resolver: choose the AS resolver class to use", "co.name).update(co) else: self.add_cache(co.copy()) def flush(self): for c in self._caches_list: c.flush()", "[] temp_files = [] netcache = NetCache() geoip_city = None", "t0 = time.time() return (v for (k, v) in six.iteritems(self.__dict__)", "s.append(\"%-20s: %s\" % (l.__name__, doc)) return \"\\n\".join(s) def register(self, cmd):", "conf.L3Socket according to the various use_* parameters \"\"\" from scapy.main", "= None L2listen = None BTsocket = None USBsocket =", "self.add_cache(c) def __delattr__(self, attr): raise AttributeError(\"Cannot delete attributes\") def update(self,", "sniff() filter : bpf filter added to every sniffing socket", "for which conversion to string should NOT be done #", "self.timeout: raise KeyError(item) return val def get(self, item, default=None): #", "None L2socket = None L2listen = None BTsocket = None", "<- %-20s (%s)\" % (num, layer.__name__, layer._name))) lst.sort() return \"\\n\".join(y", "stacks) # noqa: E501 if 2, strictly checks that they", "recv_poll_rate: how often to check for new packets. Defaults to", "self.append(layer) if layer.__module__ not in self.ldict: self.ldict[layer.__module__] = [] self.ldict[layer.__module__].append(layer)", "Conf.load_layers.remove(m) conf = Conf() def crypto_validator(func): \"\"\" This a decorator", "not in self or self._timetable[key] < other._timetable[key]: dict.__setitem__(self, key, value)", "[\"inet6\", \"dhcp6\"]: if m in Conf.load_layers: Conf.load_layers.remove(m) conf = Conf()", "scapy.layers.inet6 import L3RawSocket6 conf.L3socket = L3RawSocket conf.L3socket6 = L3RawSocket6 def", "of the global 'conf'. \"\"\" def func_in(*args, **kwargs): if not", "else default def __repr__(self): lst = [] for num, layer", "= universal_open psreader = universal_open svgreader = universal_open dot =", "change of conf.logLevel\"\"\" log_scapy.setLevel(val) class Conf(ConfClass): \"\"\"This object contains the", "import functools import os import re import time import socket", "num in six.iteritems(self.layer2num): if num not in self.num2layer or self.num2layer[num]", "x, y in lst) class LayersList(list): def __init__(self): list.__init__(self) self.ldict", "routing table and provides methods to manipulate it warning_threshold :", "0.05s. \"\"\" version = ReadOnlyAttribute(\"version\", VERSION) session = \"\" interactive", "E501 route : holds the Scapy routing table and provides", "'smb', 'snmp', 'tftp', 'vrrp', 'vxlan', 'x509', 'zigbee'] contribs = dict()", "__contains__(self, item): if isinstance(item, base_classes.Packet_metaclass): return item in self.layer2num return", "E501 histfile : history file padding : includes padding in", "\"\" cache_iflist = {} route = None # Filed by", "keys: if i[0] != \"_\": r = repr(getattr(self, i)) r", "except ImportError: return False return _version_checker(cryptography, (1, 7)) def isCryptographyRecent():", "configuration of Scapy. session : filename where the session will", "False debug_tls = False wepkey = \"\" cache_iflist = {}", "return _version_checker(cryptography, (2, 0)) def isCryptographyAdvanced(): \"\"\" Check if the", "iface6 = None layers = LayersList() commands = CommandsList() dot15d4_protocol", "E501 if 1, checks that they either are equal or", "(bug in some NAT stacks) # noqa: E501 checkIPinIP: if", "__future__ import absolute_import from __future__ import print_function import functools import", "(l.__name__, doc)) return \"\\n\".join(s) def register(self, cmd): self.append(cmd) return cmd", "0.05 def __getattr__(self, attr): # Those are loaded on runtime", "return list(six.itervalues(self)) t0 = time.time() return [v for (k, v)", "= num def __getitem__(self, item): if isinstance(item, base_classes.Packet_metaclass): return self.layer2num[item]", "else: conf.L3socket = L3pcapSocket conf.L3socket6 = functools.partial(L3pcapSocket, filter=\"ip6\") conf.L2socket =", "secrets when they are computed. recv_poll_rate: how often to check", "sorted(self, key=lambda x: x.__name__): doc = l.__doc__.split(\"\\n\")[0] if l.__doc__ else", "raise ScapyInvalidPlatformException(\"BSD-like (OSX, *BSD...) only !\") if not conf.use_pcap and", "if self.timeout is None: return dict.__len__(self) return len(self.keys()) def summary(self):", "socket import sys from scapy import VERSION, base_classes from scapy.consts", "- self._timetable[k] < self.timeout) # noqa: E501 def items(self): if", "noqa: E501 def values(self): if self.timeout is None: return list(six.itervalues(self))", "'inet', 'inet6', 'ipsec', 'ir', 'isakmp', 'l2', 'l2tp', 'llmnr', 'lltd', 'mgcp',", "Resolve() emph = Emphasize() use_pypy = ReadOnlyAttribute(\"use_pypy\", isPyPy()) use_pcap =", "layer): self.register_num2layer(num, layer) self.register_layer2num(num, layer) def register_num2layer(self, num, layer): self.num2layer[num]", "__init__(self, name=\"noname\", timeout=None): self.timeout = timeout self.name = name self._timetable", "Check if the cryptography library is present, and if it", "any method relying on the cryptography library. # noqa: E501", "in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout) # noqa:", "True checkIPaddr = True checkIPinIP = True check_TCPerror_seqack = False", "\"Read-only class attribute\" class ProgPath(ConfClass): universal_open = \"open\" if DARWIN", "import socket import sys from scapy import VERSION, base_classes from", "packets except_filter : BPF filter for packets to ignore debug_match", "layers to store local configuration # noqa: E501 debug_tls:When 1,", "Interceptor(\"logLevel\", log_scapy.level, _loglevel_changer) checkIPID = False checkIPsrc = True checkIPaddr", "import MANUFDB return MANUFDB if attr == \"ethertypes\": from scapy.data", "layers match. If False, do not check IP layers that", "\"use_pcap\", False) else: conf.L3socket = L3pcapSocket conf.L3socket6 = functools.partial(L3pcapSocket, filter=\"ip6\")", ": default mode for listening socket (to get answers if", "\"use_bpf\": [\"use_pcap\"], } restore = {k: getattr(conf, k) for k", "conf.L2socket = _NotAvailableSocket conf.L2listen = _NotAvailableSocket # No need to", "license \"\"\" Implementation of the configuration object. \"\"\" from __future__", "->\" lst.append((num, \"%#6x %s %-20s (%s)\" % (num, dir, layer.__name__,", "resolve = Resolve() noenum = Resolve() emph = Emphasize() use_pypy", "%-20s (%s)\" % (num, dir, layer.__name__, layer._name))) for layer, num", "name self.intname = \"_intercepted_%s\" % name self.default = default self.hook", "import L3WinSocket, L3WinSocket6 conf.L3socket = L3WinSocket conf.L3socket6 = L3WinSocket6 conf.L2socket", "if isinstance(item, base_classes.Packet_metaclass): return self.layer2num[item] return self.num2layer[item] def __contains__(self, item):", "attributes\") def update(self, other): for co in other._caches_list: if hasattr(self,", "(k for k in six.iterkeys(self.__dict__) if t0 - self._timetable[k] <", "some NAT stacks) # noqa: E501 checkIPinIP: if True, checks", "self or self._timetable[key] < other._timetable[key]: dict.__setitem__(self, key, value) self._timetable[key] =", "False else: return True def isPyPy(): \"\"\"Returns either scapy is", "except Exception: return False else: return True def isPyPy(): \"\"\"Returns", "in self.layers return elt in self.fields def __repr__(self): return \"<%s", ": includes padding in disassembled packets except_filter : BPF filter", "item in self else default def __repr__(self): lst = []", "!= layer: lst.append((num, \"%#6x <- %-20s (%s)\" % (num, layer.__name__,", "globals _load(\"scapy.arch.bpf\") return if LINUX: from scapy.arch.linux import L3PacketSocket, L2Socket,", "if self.timeout is not None: t = self._timetable[item] if time.time()", "auto_fragment = True debug_dissector = False color_theme = Interceptor(\"color_theme\", NoTheme(),", "= True checkIPinIP = True check_TCPerror_seqack = False verb =", "remove(self, *flds): self.fields -= set(flds) self._recalc_layer_list() def __contains__(self, elt): if", "__contains__(self, elt): if isinstance(elt, base_classes.Packet_metaclass): return elt in self.layers return", "None: return dict.items(self) t0 = time.time() return [(k, v) for", "= Interceptor(\"use_bpf\", False, _socket_changer) use_npcap = False ipv6_enabled = socket.has_ipv6", "level of verbosity, from 0 (almost mute) to 3 (verbose)", "param in dependencies[attr]: Interceptor.set_from_hook(conf, param, False) try: _set_conf_sockets() except (ScapyInvalidPlatformException,", "selects the default output interface for srp() and sendp(). default:\"eth0\")", "= L3bpfSocket conf.L3socket6 = functools.partial(L3bpfSocket, filter=\"ip6\") conf.L2socket = L2bpfSocket conf.L2listen", "in self.__slots__: return object.__getattribute__(self, item) val = dict.__getitem__(self, item) if", "socket to exclude traffic from analysis # noqa: E501 histfile", "ProgPath() resolve = Resolve() noenum = Resolve() emph = Emphasize()", "either if it does # not exist in `self` or", "minver): \"\"\"Checks that module has a higher version that minver.", "cryptography library is recent (2.0 and later) \"\"\" try: import", "lst.sort() return \"\\n\".join(y for x, y in lst) class LayersList(list):", "try: _set_conf_sockets() except (ScapyInvalidPlatformException, ImportError) as e: for key, value", "in restore.items(): Interceptor.set_from_hook(conf, key, value) if isinstance(e, ScapyInvalidPlatformException): raise def", "= [\"timeout\", \"name\", \"_timetable\", \"__dict__\"] def __init__(self, name=\"noname\", timeout=None): self.timeout", "is present, and if it supports X25519, ChaCha20Poly1305 and such", "in dependencies} del restore[attr] # This is handled directly by", "if attr == \"services_udp\": from scapy.data import UDP_SERVICES return UDP_SERVICES", "debug_tls:When 1, print some TLS session secrets when they are", "src in IP and ICMP IP citation match (bug in", "# noqa: E501 class Emphasize(ConfigFieldList): pass class Resolve(ConfigFieldList): pass class", "_is_field(f): return hasattr(f, \"owners\") def _recalc_layer_list(self): self.layers = {owner for", "test - minver: a tuple of versions \"\"\" # We", "False ipv6_enabled = socket.has_ipv6 extensions_paths = \".\" stats_classic_protocols = []", "noqa: E501 checkIPinIP: if True, checks that IP-in-IP layers match.", "crypto_valid_advanced = crypto_valid_recent and isCryptographyAdvanced() fancy_prompt = True auto_crop_tables =", "Used in dot15d4.py logLevel = Interceptor(\"logLevel\", log_scapy.level, _loglevel_changer) checkIPID =", "\"display\" tcpdump = \"tcpdump\" tcpreplay = \"tcpreplay\" hexedit = \"hexer\"", "None else {} def __get__(self, obj, typ=None): if not hasattr(obj,", "for l in sorted(self, key=lambda x: x.__name__): doc = l.__doc__.split(\"\\n\")[0]", "# noqa: E501 histfile : history file padding : includes", "from 0 (almost mute) to 3 (verbose) promisc : default", "and self.layer2num[layer] == num: dir = \"<->\" else: dir =", "for f in self.fields for owner in f.owners} def add(self,", "for c in self._caches_list: c.flush() def __repr__(self): return \"\\n\".join(c.summary() for", "__repr__(self): return str(self) def __str__(self): s = \"\" keys =", "Solaris !\" ) # we are already in an Interceptor", "ImportError(\"Cannot execute crypto-related method! \" \"Please install python-cryptography v1.7 or", "if not isinstance(val, bool): raise TypeError(\"This argument should be a", "_load if conf.use_bpf and not BSD: Interceptor.set_from_hook(conf, \"use_bpf\", False) raise", "None layers = LayersList() commands = CommandsList() dot15d4_protocol = None", "done # noqa: E501 AS_resolver: choose the AS resolver class", "layers that encapsulates another IP layer check_TCPerror_seqack: if 1, also", "item): if isinstance(item, base_classes.Packet_metaclass): return item in self.layer2num return item", "self.timeout] # noqa: E501 def keys(self): if self.timeout is None:", "through # the timetable check try: return self[item] except KeyError:", "into debug.recv # noqa: E501 route : holds the Scapy", "self.__slots__: return object.__getattribute__(self, item) val = dict.__getitem__(self, item) if self.timeout", ": when 1, store received packet that are not matched", "checkIPsrc = True checkIPaddr = True checkIPinIP = True check_TCPerror_seqack", "timeout=timeout) self.add_cache(c) def __delattr__(self, attr): raise AttributeError(\"Cannot delete attributes\") def", "ReadOnlyAttribute(\"use_pypy\", isPyPy()) use_pcap = Interceptor( \"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"), _socket_changer )", "be \"ipython\", \"python\" or \"auto\". Default: Auto stealth : if", "= 5 prog = ProgPath() resolve = Resolve() noenum =", "commands\"\"\" print(repr(conf.commands)) class CacheInstance(dict, object): __slots__ = [\"timeout\", \"name\", \"_timetable\",", "version_tags = version_tags.group(1).split(\".\") version_tags = tuple(int(x) for x in version_tags)", "in self or self._timetable[key] < other._timetable[key]: dict.__setitem__(self, key, value) self._timetable[key]", "layer.__module__ not in self.ldict: self.ldict[layer.__module__] = [] self.ldict[layer.__module__].append(layer) def layers(self):", "default mode for sniff() filter : bpf filter added to", "L2socket = None L2listen = None BTsocket = None USBsocket", "t0 = time.time() return ((k, v) for (k, v) in", "conf.L3socket = L3RawSocket conf.L3socket6 = L3RawSocket6 def _socket_changer(attr, val): if", "'x509', 'zigbee'] contribs = dict() crypto_valid = isCryptographyValid() crypto_valid_recent =", "time.time() dict.__setitem__(self, item, v) def update(self, other): for key, value", "def _loglevel_changer(attr, val): \"\"\"Handle a change of conf.logLevel\"\"\" log_scapy.setLevel(val) class", "L2Socket conf.L2listen = L2ListenSocket # Update globals _load(\"scapy.arch.linux\") return if", "Resolve() noenum = Resolve() emph = Emphasize() use_pypy = ReadOnlyAttribute(\"use_pypy\",", "another IP layer check_TCPerror_seqack: if 1, also check that TCP", "self.fields = set() self.layers = set() @staticmethod def _is_field(f): return", "_readonly(name)) ) ReadOnlyAttribute.__doc__ = \"Read-only class attribute\" class ProgPath(ConfClass): universal_open", "some TLS session secrets when they are computed. recv_poll_rate: how", "output interface for srp() and sendp(). default:\"eth0\") # noqa: E501", "ImportError) as e: for key, value in restore.items(): Interceptor.set_from_hook(conf, key,", "= \"ifconfig\" class ConfigFieldList: def __init__(self): self.fields = set() self.layers", "# This program is published under a GPLv2 license \"\"\"", "for which resolution should be done noenum : holds list", "return False return _version_checker(cryptography, (1, 7)) def isCryptographyRecent(): \"\"\" Check", "filter=\"ip6\") conf.L2socket = L2bpfSocket conf.L2listen = L2bpfListenSocket # Update globals", "older. if key not in self or self._timetable[key] < other._timetable[key]:", "version that minver. params: - module: a module to test", "dict which can be used by contrib layers to store", "not exist in `self` or if the entry in `self`", "else \"--\" s.append(\"%-20s: %s\" % (l.__name__, doc)) return \"\\n\".join(s) def", "self.__dict__ = cnf.__dict__.copy() def __repr__(self): return str(self) def __str__(self): s", "hook=None, args=None, kargs=None): self.name = name self.intname = \"_intercepted_%s\" %", "key, value in six.iteritems(other): # We only update an element", "# noqa: E501 Its behaviour depends on the 'crypto_valid' attribute", "if t0 - self._timetable[k] < self.timeout] # noqa: E501 def", "when 1, store received packet that are not matched into", "= 60 bufsize = 2**16 histfile = os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"), \".scapy_history\"))", "table and provides methods to manipulate it warning_threshold : how", "try: from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # noqa: E501 X25519PrivateKey.generate() except", "return object.__getattribute__(self, item) val = dict.__getitem__(self, item) if self.timeout is", "stats_dot11_protocols = [] temp_files = [] netcache = NetCache() geoip_city", "are equal or byte swapped equals (bug in some IP", "manipulate it warning_threshold : how much time between warnings from", "version_tags) return version_tags >= minver def isCryptographyValid(): \"\"\" Check if", "object.__getattribute__(self, item) val = dict.__getitem__(self, item) if self.timeout is not", "import cryptography except ImportError: return False return _version_checker(cryptography, (2, 0))", "lst) class LayersList(list): def __init__(self): list.__init__(self) self.ldict = {} def", "tcpreplay = \"tcpreplay\" hexedit = \"hexer\" tshark = \"tshark\" wireshark", "if l.__doc__ else \"--\" s.append(\"%-20s: %s\" % (l.__name__, doc)) return", "used by default for ASN1 objects mib : holds MIB", "Interceptor(\"use_bpf\", False, _socket_changer) use_npcap = False ipv6_enabled = socket.has_ipv6 extensions_paths", "= functools.partial(L3pcapSocket, filter=\"ip6\") conf.L2socket = L2pcapSocket conf.L2listen = L2pcapListenSocket #", "\"<->\" else: dir = \" ->\" lst.append((num, \"%#6x %s %-20s", "supports libpcap on Solaris !\" ) # we are already", "be looked for contribs : a dict which can be", "\"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"), _socket_changer ) # XXX use_dnet is deprecated", "Scapy routing table and provides methods to manipulate it warning_threshold", "= _NotAvailableSocket # No need to update globals on Windows", "session will be saved interactive_shell : can be \"ipython\", \"python\"", "by _set_conf_sockets if val: # Only if True for param", "crypto_valid = isCryptographyValid() crypto_valid_recent = isCryptographyRecent() crypto_valid_advanced = crypto_valid_recent and", "entry in `self` is older. if key not in self", "def set_from_hook(obj, name, val): int_name = \"_intercepted_%s\" % name setattr(obj,", "= Num2Layer() l3types = Num2Layer() L3socket = None L3socket6 =", "version_tags >= minver def isCryptographyValid(): \"\"\" Check if the cryptography", "noqa: E501 def __repr__(self): s = [] if self: mk", "self.layer2num return item in self.num2layer def get(self, item, default=None): return", "\"\"\" def func_in(*args, **kwargs): if not conf.crypto_valid: raise ImportError(\"Cannot execute", "if True, checks that IP-in-IP layers match. If False, do", "Windows return from scapy.supersocket import L3RawSocket from scapy.layers.inet6 import L3RawSocket6", "import L3RawSocket6 conf.L3socket = L3RawSocket conf.L3socket6 = L3RawSocket6 def _socket_changer(attr,", "= Conf() def crypto_validator(func): \"\"\" This a decorator to be", "L2pcapListenSocket # Update globals _load(\"scapy.arch.pcapdnet\") return if conf.use_bpf: from scapy.arch.bpf.supersocket", "\"dot\" display = \"display\" tcpdump = \"tcpdump\" tcpreplay = \"tcpreplay\"", "%s\" % (l.__name__, doc)) return \"\\n\".join(s) def register(self, cmd): self.append(cmd)", "Codec used by default for ASN1 objects mib : holds", "to avoid import loops if attr == \"manufdb\": from scapy.data", "wlen: r = r[:wlen - 3] + \"...\" s +=", "every sniffing socket to exclude traffic from analysis # noqa:", "from scapy.data import ETHER_TYPES return ETHER_TYPES if attr == \"protocols\":", "setattr(obj, int_name, val) def __set__(self, obj, val): setattr(obj, self.intname, val)", "\" \".join(r.split()) wlen = 76 - max(len(i), 10) if len(r)", "'vxlan', 'x509', 'zigbee'] contribs = dict() crypto_valid = isCryptographyValid() crypto_valid_recent", "layer._name))) lst.sort() return \"\\n\".join(y for x, y in lst) class", "return object.__setattr__(self, item, v) self._timetable[item] = time.time() dict.__setitem__(self, item, v)", "traffic from analysis # noqa: E501 histfile : history file", "WINDOWS, LINUX, BSD, SOLARIS from scapy.error import log_scapy, warning, ScapyInvalidPlatformException", "are not matched into debug.recv # noqa: E501 route :", "# not exist in `self` or if the entry in", "to 0.05s. \"\"\" version = ReadOnlyAttribute(\"version\", VERSION) session = \"\"", "spoof on a lan) # noqa: E501 sniff_promisc : default", "of verbosity, from 0 (almost mute) to 3 (verbose) promisc", "item in self.layer2num return item in self.num2layer def get(self, item,", "False def _prompt_changer(attr, val): \"\"\"Change the current prompt theme\"\"\" try:", "are equals checkIPsrc: if 1, checks IP src in IP", "E501 debug_tls:When 1, print some TLS session secrets when they", "None BTsocket = None USBsocket = None min_pkt_size = 60", "method is needed to force the dict to go through", "L3WinSocket6 conf.L2socket = _NotAvailableSocket conf.L2listen = _NotAvailableSocket # No need", "self.intname = \"_intercepted_%s\" % name self.default = default self.hook =", "E501 iff : selects the default output interface for srp()", "(v for (k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k]", "import _NotAvailableSocket from scapy.arch.windows.native import L3WinSocket, L3WinSocket6 conf.L3socket = L3WinSocket", "used for any method relying on the cryptography library. #", "is part of Scapy # See http://www.secdev.org/projects/scapy for more information", "interface for srp() and sendp(). default:\"eth0\") # noqa: E501 verb", "not loaded by default load_layers = ['bluetooth', 'bluetooth4LE', 'dhcp', 'dhcp6',", "ConfClass(object): def configure(self, cnf): self.__dict__ = cnf.__dict__.copy() def __repr__(self): return", "tcpdump = \"tcpdump\" tcpreplay = \"tcpreplay\" hexedit = \"hexer\" tshark", "# Update globals _load(\"scapy.arch.linux\") return if WINDOWS: from scapy.arch.windows import", "in version_tags) return version_tags >= minver def isCryptographyValid(): \"\"\" Check", "debug_match : when 1, store received packet that are not", "in some IP stacks) # noqa: E501 if 2, strictly", "== \"protocols\": from scapy.data import IP_PROTOS return IP_PROTOS if attr", "string should NOT be done # noqa: E501 AS_resolver: choose", "default output interface for srp() and sendp(). default:\"eth0\") # noqa:", "\"services_udp\": from scapy.data import UDP_SERVICES return UDP_SERVICES if attr ==", "self.layer2num[item] return self.num2layer[item] def __contains__(self, item): if isinstance(item, base_classes.Packet_metaclass): return", "for owner in f.owners} def add(self, *flds): self.fields |= {f", "from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # noqa: E501 X25519PrivateKey.generate() except Exception:", "import _load if conf.use_bpf and not BSD: Interceptor.set_from_hook(conf, \"use_bpf\", False)", "self.ldict[layer.__module__].append(layer) def layers(self): result = [] # This import may", "lay in self.ldict: doc = eval(lay).__doc__ result.append((lay, doc.strip().split(\"\\n\")[0] if doc", "L3socket6 = None L2socket = None L2listen = None BTsocket", "self else default def __repr__(self): lst = [] for num,", "between IP sent and ICMP IP citation received # noqa:", "= False debug_tls = False wepkey = \"\" cache_iflist =", "self.num2layer = {} self.layer2num = {} def register(self, num, layer):", "NoTheme, apply_ipython_style ############ # Config # ############ class ConfClass(object): def", "# Those are loaded on runtime to avoid import loops", "self._timetable[k] < self.timeout) # noqa: E501 def items(self): if self.timeout", "\"Scapy only supports libpcap on Solaris !\" ) # we", "s = [] if self: mk = max(len(k) for k", "globals _load(\"scapy.arch.pcapdnet\") return if conf.use_bpf: from scapy.arch.bpf.supersocket import L2bpfListenSocket, \\", "should NOT be done # noqa: E501 AS_resolver: choose the", "'dhcp', 'dhcp6', 'dns', 'dot11', 'dot15d4', 'eap', 'gprs', 'hsrp', 'inet', 'inet6',", "True auto_crop_tables = True recv_poll_rate = 0.05 def __getattr__(self, attr):", "is present, and if it is recent enough for most", "for co in other._caches_list: if hasattr(self, co.name): getattr(self, co.name).update(co) else:", "elt in self.fields def __repr__(self): return \"<%s [%s]>\" % (self.__class__.__name__,", "layer): self.layer2num[layer] = num def __getitem__(self, item): if isinstance(item, base_classes.Packet_metaclass):", ": a dict which can be used by contrib layers", "self.timeout) # noqa: E501 def iterkeys(self): if self.timeout is None:", "= L2bpfSocket conf.L2listen = L2bpfListenSocket # Update globals _load(\"scapy.arch.bpf\") return", "No need to update globals on Windows return from scapy.supersocket", "class Interceptor(object): def __init__(self, name=None, default=None, hook=None, args=None, kargs=None): self.name", "1, print some TLS session secrets when they are computed.", "from scapy.arch.pcapdnet import L2pcapListenSocket, L2pcapSocket, \\ L3pcapSocket except (OSError, ImportError):", "t0 = time.time() return (k for k in six.iterkeys(self.__dict__) if", "attr == \"protocols\": from scapy.data import IP_PROTOS return IP_PROTOS if", "return item in self.num2layer def get(self, item, default=None): return self[item]", "'dot11', 'dot15d4', 'eap', 'gprs', 'hsrp', 'inet', 'inet6', 'ipsec', 'ir', 'isakmp',", "E501 def values(self): if self.timeout is None: return list(six.itervalues(self)) t0", "citation received # noqa: E501 if 1, checks that they", "from scapy.error import log_scapy, warning, ScapyInvalidPlatformException from scapy.modules import six", "import time import socket import sys from scapy import VERSION,", "self.intname, val) self.hook(self.name, val, *self.args, **self.kargs) def _readonly(name): default =", "by default load_layers = ['bluetooth', 'bluetooth4LE', 'dhcp', 'dhcp6', 'dns', 'dot11',", "on a lan) # noqa: E501 sniff_promisc : default mode", "or self._timetable[key] < other._timetable[key]: dict.__setitem__(self, key, value) self._timetable[key] = other._timetable[key]", "def items(self): if self.timeout is None: return dict.items(self) t0 =", "setattr(self, cache.name, cache) def new_cache(self, name, timeout=None): c = CacheInstance(name=name,", "def _readonly(name): default = Conf.__dict__[name].default Interceptor.set_from_hook(conf, name, default) raise ValueError(\"Read-only", "L3WinSocket conf.L3socket6 = L3WinSocket6 conf.L2socket = _NotAvailableSocket conf.L2listen = _NotAvailableSocket", "k in dependencies} del restore[attr] # This is handled directly", "# noqa: E501 def iterkeys(self): if self.timeout is None: return", "value) if isinstance(e, ScapyInvalidPlatformException): raise def _loglevel_changer(attr, val): \"\"\"Handle a", "val, *self.args, **self.kargs) def _readonly(name): default = Conf.__dict__[name].default Interceptor.set_from_hook(conf, name,", "2**16 histfile = os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"), \".scapy_history\")) padding = 1 except_filter", "route.py route6 = None # Filed by route6.py auto_fragment =", "_NotAvailableSocket from scapy.arch.windows.native import L3WinSocket, L3WinSocket6 conf.L3socket = L3WinSocket conf.L3socket6", ": level of verbosity, from 0 (almost mute) to 3", "histfile : history file padding : includes padding in disassembled", "\"\"\"This object contains the configuration of Scapy. session : filename", "% name self.default = default self.hook = hook self.args =", "'netflow', 'ntp', 'ppi', 'ppp', 'pptp', 'radius', 'rip', 'rtp', 'sctp', 'sixlowpan',", "def configure(self, cnf): self.__dict__ = cnf.__dict__.copy() def __repr__(self): return str(self)", "# noqa: E501 for m in [\"inet6\", \"dhcp6\"]: if m", "# can, tls, http are not loaded by default load_layers", "http://www.secdev.org/projects/scapy for more information # Copyright (C) <NAME> <<EMAIL>> #", "libpcap on Solaris !\" ) # we are already in", "E501 def iterkeys(self): if self.timeout is None: return six.iterkeys(self.__dict__) t0", "the cryptography library is present, and if it supports X25519,", "self.args = args if args is not None else []", "in `self` or if the entry in `self` is older.", "new packets. Defaults to 0.05s. \"\"\" version = ReadOnlyAttribute(\"version\", VERSION)", "v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout] #", "__iter__(self): return six.iterkeys(self.__dict__) def itervalues(self): if self.timeout is None: return", "strictly checks that they are equals checkIPsrc: if 1, checks", "library is recent (2.0 and later) \"\"\" try: import cryptography", "= {owner for f in self.fields for owner in f.owners}", "**self.kargs) def _readonly(name): default = Conf.__dict__[name].default Interceptor.set_from_hook(conf, name, default) raise", "Only if True for param in dependencies[attr]: Interceptor.set_from_hook(conf, param, False)", "import L2pcapListenSocket, L2pcapSocket, \\ L3pcapSocket except (OSError, ImportError): warning(\"No libpcap", "\"\\n\".join(c.summary() for c in self._caches_list) def _version_checker(module, minver): \"\"\"Checks that", "- 3] + \"...\" s += \"%-10s = %s\\n\" %", "k) for k in dependencies} del restore[attr] # This is", "you spoof on a lan) # noqa: E501 sniff_promisc :", "default) raise ValueError(\"Read-only value !\") ReadOnlyAttribute = functools.partial( Interceptor, hook=(lambda", "E501 X25519PrivateKey.generate() except Exception: return False else: return True def", "module has a higher version that minver. params: - module:", "\"\\n\".join(y for x, y in lst) class LayersList(list): def __init__(self):", "return dict.items(self) t0 = time.time() return [(k, v) for (k,", "noqa: E501 if 2, strictly checks that they are equals", "does # not exist in `self` or if the entry", "how much time between warnings from the same place ASN1_default_codec:", "noqa: E501 debug_tls:When 1, print some TLS session secrets when", "dot15d4_protocol = None # Used in dot15d4.py logLevel = Interceptor(\"logLevel\",", "setattr(obj, self.intname, self.default) return getattr(obj, self.intname) @staticmethod def set_from_hook(obj, name,", "can be used as a decorator def lsc(): \"\"\"Displays Scapy's", "is None: return dict.items(self) t0 = time.time() return [(k, v)", ": holds list of fields for which resolution should be", "% (num, dir, layer.__name__, layer._name))) for layer, num in six.iteritems(self.layer2num):", "param, False) try: _set_conf_sockets() except (ScapyInvalidPlatformException, ImportError) as e: for", "None # Used in dot15d4.py logLevel = Interceptor(\"logLevel\", log_scapy.level, _loglevel_changer)", "six.iteritems(other): # We only update an element from `other` either", "if attr == \"services_tcp\": from scapy.data import TCP_SERVICES return TCP_SERVICES", "= None # Filed by route6.py auto_fragment = True debug_dissector", "L3bpfSocket conf.L3socket = L3bpfSocket conf.L3socket6 = functools.partial(L3bpfSocket, filter=\"ip6\") conf.L2socket =", "received packet that are not matched into debug.recv # noqa:", "\".join(str(x) for x in self.fields)) # noqa: E501 class Emphasize(ConfigFieldList):", "# noqa: E501 verb : level of verbosity, from 0", "return False def _prompt_changer(attr, val): \"\"\"Change the current prompt theme\"\"\"", "Cannot load Scapy IPv6 layers.\") # noqa: E501 for m", "__repr__(self): s = [] for l in sorted(self, key=lambda x:", "def __len__(self): if self.timeout is None: return dict.__len__(self) return len(self.keys())", "if not Conf.ipv6_enabled: log_scapy.warning(\"IPv6 support disabled in Python. Cannot load", "prompt = Interceptor(\"prompt\", \">>> \", _prompt_changer) promisc = True sniff_promisc", "dict to go through # the timetable check try: return", "__repr__(self): return \"\\n\".join(c.summary() for c in self._caches_list) def _version_checker(module, minver):", "# Update globals _load(\"scapy.arch.pcapdnet\") return if conf.use_bpf: from scapy.arch.bpf.supersocket import", "== \"manufdb\": from scapy.data import MANUFDB return MANUFDB if attr", "is deprecated use_dnet = os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\") use_bpf = Interceptor(\"use_bpf\", False,", "IPv6 layers.\") # noqa: E501 for m in [\"inet6\", \"dhcp6\"]:", "minver def isCryptographyValid(): \"\"\" Check if the cryptography library is", "checks that IP-in-IP layers match. If False, do not check", "bpf filter added to every sniffing socket to exclude traffic", "equal or byte swapped equals (bug in some IP stacks)", "\"name\", \"_timetable\", \"__dict__\"] def __init__(self, name=\"noname\", timeout=None): self.timeout = timeout", "if layer.__module__ not in self.ldict: self.ldict[layer.__module__] = [] self.ldict[layer.__module__].append(layer) def", "= None USBsocket = None min_pkt_size = 60 bufsize =", "class CacheInstance(dict, object): __slots__ = [\"timeout\", \"name\", \"_timetable\", \"__dict__\"] def", "_socket_changer ) # XXX use_dnet is deprecated use_dnet = os.getenv(\"SCAPY_USE_PCAPDNET\",", "self.timeout is None: return six.itervalues(self.__dict__) t0 = time.time() return (v", "= \"tcpreplay\" hexedit = \"hexer\" tshark = \"tshark\" wireshark =", "return (v for (k, v) in six.iteritems(self.__dict__) if t0 -", "_set_conf_sockets(): \"\"\"Populate the conf.L2Socket and conf.L3Socket according to the various", "looked for contribs : a dict which can be used", "boolean\") dependencies = { # Things that will be turned", "route = None # Filed by route.py route6 = None", "'netbios', 'netflow', 'ntp', 'ppi', 'ppp', 'pptp', 'radius', 'rip', 'rtp', 'sctp',", "pdfreader = universal_open psreader = universal_open svgreader = universal_open dot", "use extensions_paths: path or list of paths where extensions are", "for contribs : a dict which can be used by", "ReadOnlyAttribute(\"version\", VERSION) session = \"\" interactive = False interactive_shell =", "choose the AS resolver class to use extensions_paths: path or", "required for the eval below import scapy # noqa: F401", "L2Socket, L2ListenSocket conf.L3socket = L3PacketSocket conf.L3socket6 = functools.partial(L3PacketSocket, filter=\"ip6\") conf.L2socket", "[%s]>\" % (self.__class__.__name__, \" \".join(str(x) for x in self.fields)) #", "holds list of fields for which resolution should be done", "= LayersList() commands = CommandsList() dot15d4_protocol = None # Used", "according to the various use_* parameters \"\"\" from scapy.main import", "= \" \".join(r.split()) wlen = 76 - max(len(i), 10) if", "stats_classic_protocols = [] stats_dot11_protocols = [] temp_files = [] netcache", "cache_iflist = {} route = None # Filed by route.py", "= NetCache() geoip_city = None # can, tls, http are", "= L3PacketSocket conf.L3socket6 = functools.partial(L3PacketSocket, filter=\"ip6\") conf.L2socket = L2Socket conf.L2listen", "on the cryptography library. # noqa: E501 Its behaviour depends", "t0 = time.time() return [k for k in six.iterkeys(self.__dict__) if", "= ProgPath() resolve = Resolve() noenum = Resolve() emph =", "cache): self._caches_list.append(cache) setattr(self, cache.name, cache) def new_cache(self, name, timeout=None): c", "and SOLARIS: Interceptor.set_from_hook(conf, \"use_pcap\", True) raise ScapyInvalidPlatformException( \"Scapy only supports", "import absolute_import from __future__ import print_function import functools import os", "\"protocols\": from scapy.data import IP_PROTOS return IP_PROTOS if attr ==", "(self.__class__.__name__, \" \".join(str(x) for x in self.fields)) # noqa: E501", "on runtime to avoid import loops if attr == \"manufdb\":", "= CacheInstance(name=name, timeout=timeout) self.add_cache(c) def __delattr__(self, attr): raise AttributeError(\"Cannot delete", "return ETHER_TYPES if attr == \"protocols\": from scapy.data import IP_PROTOS", "True for param in dependencies[attr]: Interceptor.set_from_hook(conf, param, False) try: _set_conf_sockets()", "default load_layers = ['bluetooth', 'bluetooth4LE', 'dhcp', 'dhcp6', 'dns', 'dot11', 'dot15d4',", "X25519PrivateKey.generate() except Exception: return False else: return True def isPyPy():", "self.layer2num[layer] = num def __getitem__(self, item): if isinstance(item, base_classes.Packet_metaclass): return", "interactive_shell : can be \"ipython\", \"python\" or \"auto\". Default: Auto", "items. Timeout=%rs\" % (self.name, len(self), self.timeout) # noqa: E501 def", "of paths where extensions are to be looked for contribs", "list of enum fields for which conversion to string should", "be used by contrib layers to store local configuration #", "import IP_PROTOS return IP_PROTOS if attr == \"services_udp\": from scapy.data", "__init__(self): self._caches_list = [] def add_cache(self, cache): self._caches_list.append(cache) setattr(self, cache.name,", "= True check_TCPerror_seqack = False verb = 2 prompt =", "hook=(lambda name, *args, **kwargs: _readonly(name)) ) ReadOnlyAttribute.__doc__ = \"Read-only class", "value in six.iteritems(other): # We only update an element from", "GPLv2 license \"\"\" Implementation of the configuration object. \"\"\" from", "the global 'conf'. \"\"\" def func_in(*args, **kwargs): if not conf.crypto_valid:", "= \"\" debug_match = False debug_tls = False wepkey =", "added to every sniffing socket to exclude traffic from analysis", "Interceptor(\"color_theme\", NoTheme(), _prompt_changer) warning_threshold = 5 prog = ProgPath() resolve", "register_num2layer(self, num, layer): self.num2layer[num] = layer def register_layer2num(self, num, layer):", "self.num2layer[num] != layer: lst.append((num, \"%#6x <- %-20s (%s)\" % (num,", "IP_PROTOS return IP_PROTOS if attr == \"services_udp\": from scapy.data import", "__slots__ = [\"timeout\", \"name\", \"_timetable\", \"__dict__\"] def __init__(self, name=\"noname\", timeout=None):", "and provides methods to manipulate it warning_threshold : how much", "num, layer): self.register_num2layer(num, layer) self.register_layer2num(num, layer) def register_num2layer(self, num, layer):", "libpcap provider available ! pcap won't be used\") Interceptor.set_from_hook(conf, \"use_pcap\",", "fields for which conversion to string should NOT be done", "an Interceptor hook, use Interceptor.set_from_hook if conf.use_pcap or conf.use_dnet: try:", "BSD, SOLARIS from scapy.error import log_scapy, warning, ScapyInvalidPlatformException from scapy.modules", "some IP stacks) # noqa: E501 if 2, strictly checks", "debug_match = False debug_tls = False wepkey = \"\" cache_iflist", "will be turned off \"use_pcap\": [\"use_bpf\"], \"use_bpf\": [\"use_pcap\"], } restore", "if self.timeout is None: return dict.items(self) t0 = time.time() return", "True, checks that IP-in-IP layers match. If False, do not", "in six.iteritems(self.num2layer): if layer in self.layer2num and self.layer2num[layer] == num:", "for new packets. Defaults to 0.05s. \"\"\" version = ReadOnlyAttribute(\"version\",", "tls, http are not loaded by default load_layers = ['bluetooth',", "(1, 7)) def isCryptographyRecent(): \"\"\" Check if the cryptography library", "\"%#6x %s %-20s (%s)\" % (num, dir, layer.__name__, layer._name))) for", "import six from scapy.themes import NoTheme, apply_ipython_style ############ # Config", "num, layer): self.layer2num[layer] = num def __getitem__(self, item): if isinstance(item,", "'dns', 'dot11', 'dot15d4', 'eap', 'gprs', 'hsrp', 'inet', 'inet6', 'ipsec', 'ir',", "self._timetable[item] = time.time() dict.__setitem__(self, item, v) def update(self, other): for", "L3WinSocket6 conf.L3socket = L3WinSocket conf.L3socket6 = L3WinSocket6 conf.L2socket = _NotAvailableSocket", "'l2tp', 'llmnr', 'lltd', 'mgcp', 'mobileip', 'netbios', 'netflow', 'ntp', 'ppi', 'ppp',", "if attr == \"manufdb\": from scapy.data import MANUFDB return MANUFDB", "LayersList(list): def __init__(self): list.__init__(self) self.ldict = {} def __repr__(self): return", "route6.py auto_fragment = True debug_dissector = False color_theme = Interceptor(\"color_theme\",", "recv_poll_rate = 0.05 def __getattr__(self, attr): # Those are loaded", "self.hook(self.name, val, *self.args, **self.kargs) def _readonly(name): default = Conf.__dict__[name].default Interceptor.set_from_hook(conf,", "prompt theme\"\"\" try: sys.ps1 = conf.color_theme.prompt(conf.prompt) except Exception: pass try:", "__set__(self, obj, val): setattr(obj, self.intname, val) self.hook(self.name, val, *self.args, **self.kargs)", "other._timetable[key]: dict.__setitem__(self, key, value) self._timetable[key] = other._timetable[key] def iteritems(self): if", "equals checkIPsrc: if 1, checks IP src in IP and", "= None L3socket6 = None L2socket = None L2listen =", "for k in dependencies} del restore[attr] # This is handled", "None else [] self.kargs = kargs if kargs is not", "# No need to update globals on Windows return from", "> wlen: r = r[:wlen - 3] + \"...\" s", "pass class Num2Layer: def __init__(self): self.num2layer = {} self.layer2num =", "pass def _set_conf_sockets(): \"\"\"Populate the conf.L2Socket and conf.L3Socket according to", "Update globals _load(\"scapy.arch.bpf\") return if LINUX: from scapy.arch.linux import L3PacketSocket,", "feel useless, but it is required for the eval below", "def __repr__(self): return \"<%s [%s]>\" % (self.__class__.__name__, \" \".join(str(x) for", "in IP and ICMP IP citation match (bug in some", "def register(self, layer): self.append(layer) if layer.__module__ not in self.ldict: self.ldict[layer.__module__]", "= \"tshark\" wireshark = \"wireshark\" ifconfig = \"ifconfig\" class ConfigFieldList:", "def __repr__(self): return str(self) def __str__(self): s = \"\" keys", "conf.L3socket = L3WinSocket conf.L3socket6 = L3WinSocket6 conf.L2socket = _NotAvailableSocket conf.L2listen", "if you spoof on a lan) # noqa: E501 sniff_promisc", "scapy.modules import six from scapy.themes import NoTheme, apply_ipython_style ############ #", "@staticmethod def set_from_hook(obj, name, val): int_name = \"_intercepted_%s\" % name", "name=None, default=None, hook=None, args=None, kargs=None): self.name = name self.intname =", "module.__version__) if not version_tags: return False version_tags = version_tags.group(1).split(\".\") version_tags", "session = \"\" interactive = False interactive_shell = \"\" stealth", "if isinstance(elt, base_classes.Packet_metaclass): return elt in self.layers return elt in", "method! \" \"Please install python-cryptography v1.7 or later.\") # noqa:", "in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout] # noqa:", "= L2pcapListenSocket # Update globals _load(\"scapy.arch.pcapdnet\") return if conf.use_bpf: from", "`self` is older. if key not in self or self._timetable[key]", "= None L2socket = None L2listen = None BTsocket =", "is recent (2.0 and later) \"\"\" try: import cryptography except", "logLevel = Interceptor(\"logLevel\", log_scapy.level, _loglevel_changer) checkIPID = False checkIPsrc =", "NetCache: def __init__(self): self._caches_list = [] def add_cache(self, cache): self._caches_list.append(cache)", "if WINDOWS: from scapy.arch.windows import _NotAvailableSocket from scapy.arch.windows.native import L3WinSocket,", "item): if item in self.__slots__: return object.__getattribute__(self, item) val =", "extensions_paths = \".\" stats_classic_protocols = [] stats_dot11_protocols = [] temp_files", "__getitem__(self, item): if item in self.__slots__: return object.__getattribute__(self, item) val", "warning_threshold : how much time between warnings from the same", "> self.timeout: raise KeyError(item) return val def get(self, item, default=None):", "cmd): self.append(cmd) return cmd # return cmd so that method", "# noqa: E501 def __iter__(self): return six.iterkeys(self.__dict__) def itervalues(self): if", "\"\"\" version = ReadOnlyAttribute(\"version\", VERSION) session = \"\" interactive =", "return if WINDOWS: from scapy.arch.windows import _NotAvailableSocket from scapy.arch.windows.native import", "ETHER_TYPES return ETHER_TYPES if attr == \"protocols\": from scapy.data import", "flds if self._is_field(f)} self._recalc_layer_list() def remove(self, *flds): self.fields -= set(flds)", "def __contains__(self, item): if isinstance(item, base_classes.Packet_metaclass): return item in self.layer2num", "debug_dissector = False color_theme = Interceptor(\"color_theme\", NoTheme(), _prompt_changer) warning_threshold =", "L2bpfSocket, L3bpfSocket conf.L3socket = L3bpfSocket conf.L3socket6 = functools.partial(L3bpfSocket, filter=\"ip6\") conf.L2socket", "F401 for lay in self.ldict: doc = eval(lay).__doc__ result.append((lay, doc.strip().split(\"\\n\")[0]", "pcap won't be used\") Interceptor.set_from_hook(conf, \"use_pcap\", False) else: conf.L3socket =", "num: dir = \"<->\" else: dir = \" ->\" lst.append((num,", "(to get answers if you spoof on a lan) #", "key, value) if isinstance(e, ScapyInvalidPlatformException): raise def _loglevel_changer(attr, val): \"\"\"Handle", "k in six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout] #", "get(self, item, default=None): return self[item] if item in self else", "item in six.iteritems(self.__dict__): s.append(fmt % item) return \"\\n\".join(s) class NetCache:", "need to update globals on Windows return from scapy.supersocket import", "\"xdg-open\" pdfreader = universal_open psreader = universal_open svgreader = universal_open", "and sendp(). default:\"eth0\") # noqa: E501 verb : level of", "is older. if key not in self or self._timetable[key] <", "self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys) for i in keys: if", "in [\"inet6\", \"dhcp6\"]: if m in Conf.load_layers: Conf.load_layers.remove(m) conf =", "on Solaris !\" ) # we are already in an", "import cryptography except ImportError: return False return _version_checker(cryptography, (1, 7))", "for any method relying on the cryptography library. # noqa:", "cnf): self.__dict__ = cnf.__dict__.copy() def __repr__(self): return str(self) def __str__(self):", "library. # noqa: E501 Its behaviour depends on the 'crypto_valid'", "val: # Only if True for param in dependencies[attr]: Interceptor.set_from_hook(conf,", "= 2**16 histfile = os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"), \".scapy_history\")) padding = 1", "runtime to avoid import loops if attr == \"manufdb\": from", "noqa: E501 def __len__(self): if self.timeout is None: return dict.__len__(self)", "'crypto_valid' attribute of the global 'conf'. \"\"\" def func_in(*args, **kwargs):", "= name self._timetable = {} def flush(self): self.__init__(name=self.name, timeout=self.timeout) def", "not check IP layers that encapsulates another IP layer check_TCPerror_seqack:", "other): for key, value in six.iteritems(other): # We only update", "class LayersList(list): def __init__(self): list.__init__(self) self.ldict = {} def __repr__(self):", "def __iter__(self): return six.iterkeys(self.__dict__) def itervalues(self): if self.timeout is None:", "1, also check that TCP seq and ack match the", "self._timetable = {} def flush(self): self.__init__(name=self.name, timeout=self.timeout) def __getitem__(self, item):", "sent and ICMP IP citation received # noqa: E501 if", "BPF filter for packets to ignore debug_match : when 1,", "Conf.__dict__[name].default Interceptor.set_from_hook(conf, name, default) raise ValueError(\"Read-only value !\") ReadOnlyAttribute =", "'sixlowpan', 'skinny', 'smb', 'snmp', 'tftp', 'vrrp', 'vxlan', 'x509', 'zigbee'] contribs", "else: self.add_cache(co.copy()) def flush(self): for c in self._caches_list: c.flush() def", "__repr__(self): return \"<%s [%s]>\" % (self.__class__.__name__, \" \".join(str(x) for x", "import may feel useless, but it is required for the", "list(six.itervalues(self)) t0 = time.time() return [v for (k, v) in", "can, tls, http are not loaded by default load_layers =", "pass try: apply_ipython_style(get_ipython()) except NameError: pass def _set_conf_sockets(): \"\"\"Populate the", "L3RawSocket conf.L3socket6 = L3RawSocket6 def _socket_changer(attr, val): if not isinstance(val,", "not matched into debug.recv # noqa: E501 route : holds", "\"not implemented\" iface = None iface6 = None layers =", "= self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys) for i in keys:", "getattr(obj, self.intname) @staticmethod def set_from_hook(obj, name, val): int_name = \"_intercepted_%s\"", "y in lst) class LayersList(list): def __init__(self): list.__init__(self) self.ldict =", "for k in six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout)", "def __repr__(self): s = [] for l in sorted(self, key=lambda", "but it is required for the eval below import scapy", "six.iterkeys(self.__dict__) t0 = time.time() return (k for k in six.iterkeys(self.__dict__)", "self.timeout] # noqa: E501 def __len__(self): if self.timeout is None:", "else [] self.kargs = kargs if kargs is not None", "l.__doc__.split(\"\\n\")[0] if l.__doc__ else \"--\" s.append(\"%-20s: %s\" % (l.__name__, doc))", "scapy.data import MANUFDB return MANUFDB if attr == \"ethertypes\": from", "log_scapy.setLevel(val) class Conf(ConfClass): \"\"\"This object contains the configuration of Scapy.", "use_dnet is deprecated use_dnet = os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\") use_bpf = Interceptor(\"use_bpf\",", "############ class ConfClass(object): def configure(self, cnf): self.__dict__ = cnf.__dict__.copy() def", "class Conf(ConfClass): \"\"\"This object contains the configuration of Scapy. session", "to go out (ARP, DNS, ...) checkIPID: if 0, doesn't", "<NAME> <<EMAIL>> # This program is published under a GPLv2", "\"__dict__\"] def __init__(self, name=\"noname\", timeout=None): self.timeout = timeout self.name =", "self.timeout) # noqa: E501 def __repr__(self): s = [] if", "SOLARIS: Interceptor.set_from_hook(conf, \"use_pcap\", True) raise ScapyInvalidPlatformException( \"Scapy only supports libpcap", "if conf.use_bpf and not BSD: Interceptor.set_from_hook(conf, \"use_bpf\", False) raise ScapyInvalidPlatformException(\"BSD-like", "mute) to 3 (verbose) promisc : default mode for listening", "{f for f in flds if self._is_field(f)} self._recalc_layer_list() def remove(self,", "= Conf.__dict__[name].default Interceptor.set_from_hook(conf, name, default) raise ValueError(\"Read-only value !\") ReadOnlyAttribute", "universal_open dot = \"dot\" display = \"display\" tcpdump = \"tcpdump\"", "set() @staticmethod def _is_field(f): return hasattr(f, \"owners\") def _recalc_layer_list(self): self.layers", "functools.partial(L3pcapSocket, filter=\"ip6\") conf.L2socket = L2pcapSocket conf.L2listen = L2pcapListenSocket # Update", "Num2Layer() l3types = Num2Layer() L3socket = None L3socket6 = None", "if the cryptography library is present, and if it supports", "load Scapy IPv6 layers.\") # noqa: E501 for m in", "or byte swapped equals (bug in some IP stacks) #", "= cnf.__dict__.copy() def __repr__(self): return str(self) def __str__(self): s =", "UDP_SERVICES if attr == \"services_tcp\": from scapy.data import TCP_SERVICES return", "# See http://www.secdev.org/projects/scapy for more information # Copyright (C) <NAME>", "__delattr__(self, attr): raise AttributeError(\"Cannot delete attributes\") def update(self, other): for", "# noqa: E501 X25519PrivateKey.generate() except Exception: return False else: return", "psreader = universal_open svgreader = universal_open dot = \"dot\" display", "on Windows return from scapy.supersocket import L3RawSocket from scapy.layers.inet6 import", "= [] temp_files = [] netcache = NetCache() geoip_city =", "if item in self.__slots__: return object.__getattribute__(self, item) val = dict.__getitem__(self,", "\"--\" s.append(\"%-20s: %s\" % (l.__name__, doc)) return \"\\n\".join(s) def register(self,", "a module to test - minver: a tuple of versions", "functools.partial( Interceptor, hook=(lambda name, *args, **kwargs: _readonly(name)) ) ReadOnlyAttribute.__doc__ =", "v) self._timetable[item] = time.time() dict.__setitem__(self, item, v) def update(self, other):", "not None else {} def __get__(self, obj, typ=None): if not", "restore[attr] # This is handled directly by _set_conf_sockets if val:", "in self else default def __repr__(self): lst = [] for", "mode for sniff() filter : bpf filter added to every", "theme\"\"\" try: sys.ps1 = conf.color_theme.prompt(conf.prompt) except Exception: pass try: apply_ipython_style(get_ipython())", "(%s)\" % (num, dir, layer.__name__, layer._name))) for layer, num in", "from scapy.data import UDP_SERVICES return UDP_SERVICES if attr == \"services_tcp\":", "history file padding : includes padding in disassembled packets except_filter", "# Filed by route6.py auto_fragment = True debug_dissector = False", "%-20s (%s)\" % (num, layer.__name__, layer._name))) lst.sort() return \"\\n\".join(y for", "l2types = Num2Layer() l3types = Num2Layer() L3socket = None L3socket6", "imports imp which is deprecated version_regexp = r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags =", "return dict.keys(self) t0 = time.time() return [k for k in", "socket (to get answers if you spoof on a lan)", "only supports libpcap on Solaris !\" ) # we are", "iteritems(self): if self.timeout is None: return six.iteritems(self.__dict__) t0 = time.time()", "in lst) class LayersList(list): def __init__(self): list.__init__(self) self.ldict = {}", "t0 - self._timetable[k] < self.timeout] # noqa: E501 def keys(self):", "by route.py route6 = None # Filed by route6.py auto_fragment", "t0 = time.time() return [v for (k, v) in six.iteritems(self.__dict__)", "current prompt theme\"\"\" try: sys.ps1 = conf.color_theme.prompt(conf.prompt) except Exception: pass", "< self.timeout] # noqa: E501 def keys(self): if self.timeout is", "= [] for num, layer in six.iteritems(self.num2layer): if layer in", "ones in ICMP citation # noqa: E501 iff : selects", "padding in disassembled packets except_filter : BPF filter for packets", "register(self, cmd): self.append(cmd) return cmd # return cmd so that", "from scapy.data import TCP_SERVICES return TCP_SERVICES return object.__getattr__(self, attr) if", "hasattr(f, \"owners\") def _recalc_layer_list(self): self.layers = {owner for f in", "def __init__(self): list.__init__(self) self.ldict = {} def __repr__(self): return \"\\n\".join(\"%-20s:", "def _recalc_layer_list(self): self.layers = {owner for f in self.fields for", "is None: return dict.__len__(self) return len(self.keys()) def summary(self): return \"%s:", "timeout=self.timeout) def __getitem__(self, item): if item in self.__slots__: return object.__getattribute__(self,", "!\" ) # we are already in an Interceptor hook,", "= False default_l2 = None l2types = Num2Layer() l3types =", "ICMP IP citation received # noqa: E501 if 1, checks", "self.timeout is None: return dict.keys(self) t0 = time.time() return [k", ") # we are already in an Interceptor hook, use", "def remove(self, *flds): self.fields -= set(flds) self._recalc_layer_list() def __contains__(self, elt):", "lst.append((num, \"%#6x %s %-20s (%s)\" % (num, dir, layer.__name__, layer._name)))", "'eap', 'gprs', 'hsrp', 'inet', 'inet6', 'ipsec', 'ir', 'isakmp', 'l2', 'l2tp',", "attr): # Those are loaded on runtime to avoid import", "'conf'. \"\"\" def func_in(*args, **kwargs): if not conf.crypto_valid: raise ImportError(\"Cannot", "for l in self) def register(self, layer): self.append(layer) if layer.__module__", "temp_files = [] netcache = NetCache() geoip_city = None #", "self.ldict: self.ldict[layer.__module__] = [] self.ldict[layer.__module__].append(layer) def layers(self): result = []", "the entry in `self` is older. if key not in", "ImportError: return False return _version_checker(cryptography, (2, 0)) def isCryptographyAdvanced(): \"\"\"", ": holds the Scapy routing table and provides methods to", "for sniff() filter : bpf filter added to every sniffing", "__init__(self, name=None, default=None, hook=None, args=None, kargs=None): self.name = name self.intname", "seq and ack match the ones in ICMP citation #", "num, layer in six.iteritems(self.num2layer): if layer in self.layer2num and self.layer2num[layer]", "E501 sniff_promisc : default mode for sniff() filter : bpf", "\\ L3pcapSocket except (OSError, ImportError): warning(\"No libpcap provider available !", "= [] def add_cache(self, cache): self._caches_list.append(cache) setattr(self, cache.name, cache) def", "\"wireshark\" ifconfig = \"ifconfig\" class ConfigFieldList: def __init__(self): self.fields =", "NameError: pass def _set_conf_sockets(): \"\"\"Populate the conf.L2Socket and conf.L3Socket according", "self.register_num2layer(num, layer) self.register_layer2num(num, layer) def register_num2layer(self, num, layer): self.num2layer[num] =", "to update globals on Windows return from scapy.supersocket import L3RawSocket", "checks IP src in IP and ICMP IP citation match", "list of fields for which resolution should be done noenum", "= dict() crypto_valid = isCryptographyValid() crypto_valid_recent = isCryptographyRecent() crypto_valid_advanced =", "includes padding in disassembled packets except_filter : BPF filter for", "conf.crypto_valid: raise ImportError(\"Cannot execute crypto-related method! \" \"Please install python-cryptography", "version = ReadOnlyAttribute(\"version\", VERSION) session = \"\" interactive = False", "_prompt_changer) warning_threshold = 5 prog = ProgPath() resolve = Resolve()", "return val def get(self, item, default=None): # overloading this method", "def register_num2layer(self, num, layer): self.num2layer[num] = layer def register_layer2num(self, num,", "ImportError): warning(\"No libpcap provider available ! pcap won't be used\")", "1, checks that they either are equal or byte swapped", "import UDP_SERVICES return UDP_SERVICES if attr == \"services_tcp\": from scapy.data", "self._timetable[k] < self.timeout) # noqa: E501 def iterkeys(self): if self.timeout", "!\") if not conf.use_pcap and SOLARIS: Interceptor.set_from_hook(conf, \"use_pcap\", True) raise", "return elt in self.layers return elt in self.fields def __repr__(self):", "conf.use_bpf and not BSD: Interceptor.set_from_hook(conf, \"use_bpf\", False) raise ScapyInvalidPlatformException(\"BSD-like (OSX,", "layer: lst.append((num, \"%#6x <- %-20s (%s)\" % (num, layer.__name__, layer._name)))", "== num: dir = \"<->\" else: dir = \" ->\"", "if self: mk = max(len(k) for k in six.iterkeys(self.__dict__)) fmt", "AS resolver class to use extensions_paths: path or list of", "globals on Windows return from scapy.supersocket import L3RawSocket from scapy.layers.inet6", "if args is not None else [] self.kargs = kargs", "L3bpfSocket conf.L3socket6 = functools.partial(L3bpfSocket, filter=\"ip6\") conf.L2socket = L2bpfSocket conf.L2listen =", "%s\" % (l.__name__, l.name) for l in self) def register(self,", "E501 verb : level of verbosity, from 0 (almost mute)", "None: return dict.keys(self) t0 = time.time() return [k for k", "if 2, strictly checks that they are equals checkIPsrc: if", "if item in self.__slots__: return object.__setattr__(self, item, v) self._timetable[item] =", "if the entry in `self` is older. if key not", "lst.append((num, \"%#6x <- %-20s (%s)\" % (num, layer.__name__, layer._name))) lst.sort()", "1) for item in six.iteritems(self.__dict__): s.append(fmt % item) return \"\\n\".join(s)", "self._caches_list = [] def add_cache(self, cache): self._caches_list.append(cache) setattr(self, cache.name, cache)", "# noqa: E501 iff : selects the default output interface", "{} def __get__(self, obj, typ=None): if not hasattr(obj, self.intname): setattr(obj,", "os.path.join(os.path.expanduser(\"~\"), \".scapy_history\")) padding = 1 except_filter = \"\" debug_match =", "KeyError(item) return val def get(self, item, default=None): # overloading this", "'dot15d4', 'eap', 'gprs', 'hsrp', 'inet', 'inet6', 'ipsec', 'ir', 'isakmp', 'l2',", "or later). \"\"\" try: import cryptography except ImportError: return False", "{} route = None # Filed by route.py route6 =", "elt in self.layers return elt in self.fields def __repr__(self): return", "_set_conf_sockets if val: # Only if True for param in", "# This import may feel useless, but it is required", "layers.\") # noqa: E501 for m in [\"inet6\", \"dhcp6\"]: if", "is needed to force the dict to go through #", "This is handled directly by _set_conf_sockets if val: # Only", "None: return six.itervalues(self.__dict__) t0 = time.time() return (v for (k,", "def iteritems(self): if self.timeout is None: return six.iteritems(self.__dict__) t0 =", "the AS resolver class to use extensions_paths: path or list", "import L3PacketSocket, L2Socket, L2ListenSocket conf.L3socket = L3PacketSocket conf.L3socket6 = functools.partial(L3PacketSocket,", "- self._timetable[k] < self.timeout] # noqa: E501 def values(self): if", "params: - module: a module to test - minver: a", "may feel useless, but it is required for the eval", "in flds if self._is_field(f)} self._recalc_layer_list() def remove(self, *flds): self.fields -=", "citation match (bug in some NAT stacks) # noqa: E501", "how often to check for new packets. Defaults to 0.05s.", "keys.update(self.__dict__) keys = sorted(keys) for i in keys: if i[0]", "so that method can be used as a decorator def", "{k: getattr(conf, k) for k in dependencies} del restore[attr] #", "= None BTsocket = None USBsocket = None min_pkt_size =", "l.name) for l in self) def register(self, layer): self.append(layer) if", "force the dict to go through # the timetable check", "def __repr__(self): return \"\\n\".join(c.summary() for c in self._caches_list) def _version_checker(module,", "dict.__setitem__(self, item, v) def update(self, other): for key, value in", "Exception: pass try: apply_ipython_style(get_ipython()) except NameError: pass def _set_conf_sockets(): \"\"\"Populate", "(OSError, ImportError): warning(\"No libpcap provider available ! pcap won't be", "the default output interface for srp() and sendp(). default:\"eth0\") #", "`self` or if the entry in `self` is older. if", "((k, v) for (k, v) in six.iteritems(self.__dict__) if t0 -", "True sniff_promisc = 1 raw_layer = None raw_summary = False", "padding = 1 except_filter = \"\" debug_match = False debug_tls", "noqa: E501 sniff_promisc : default mode for sniff() filter :", "t = self._timetable[item] if time.time() - t > self.timeout: raise", "ASN1_default_codec: Codec used by default for ASN1 objects mib :", "that minver. params: - module: a module to test -", "method relying on the cryptography library. # noqa: E501 Its", "attribute\" class ProgPath(ConfClass): universal_open = \"open\" if DARWIN else \"xdg-open\"", "padding : includes padding in disassembled packets except_filter : BPF", "for the eval below import scapy # noqa: F401 for", "match (bug in some NAT stacks) # noqa: E501 checkIPinIP:", "= time.time() return (v for (k, v) in six.iteritems(self.__dict__) if", "SOLARIS from scapy.error import log_scapy, warning, ScapyInvalidPlatformException from scapy.modules import", "for i in keys: if i[0] != \"_\": r =", "use_dnet = os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\") use_bpf = Interceptor(\"use_bpf\", False, _socket_changer) use_npcap", "return UDP_SERVICES if attr == \"services_tcp\": from scapy.data import TCP_SERVICES", "\" \".join(str(x) for x in self.fields)) # noqa: E501 class", "in f.owners} def add(self, *flds): self.fields |= {f for f", "'llmnr', 'lltd', 'mgcp', 'mobileip', 'netbios', 'netflow', 'ntp', 'ppi', 'ppp', 'pptp',", "verb = 2 prompt = Interceptor(\"prompt\", \">>> \", _prompt_changer) promisc", "if doc else lay)) return result class CommandsList(list): def __repr__(self):", "is recent enough for most usages in scapy (v1.7 or", "be saved interactive_shell : can be \"ipython\", \"python\" or \"auto\".", "= False color_theme = Interceptor(\"color_theme\", NoTheme(), _prompt_changer) warning_threshold = 5", "from scapy.data import MANUFDB return MANUFDB if attr == \"ethertypes\":", "= Interceptor( \"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"), _socket_changer ) # XXX use_dnet", "\"\"\" from __future__ import absolute_import from __future__ import print_function import", "not\"\"\" try: import __pypy__ # noqa: F401 return True except", "conf.L3socket6 = L3WinSocket6 conf.L2socket = _NotAvailableSocket conf.L2listen = _NotAvailableSocket #", "= {} self.layer2num = {} def register(self, num, layer): self.register_num2layer(num,", "if hasattr(self, co.name): getattr(self, co.name).update(co) else: self.add_cache(co.copy()) def flush(self): for", "cnf.__dict__.copy() def __repr__(self): return str(self) def __str__(self): s = \"\"", "Conf.load_layers: Conf.load_layers.remove(m) conf = Conf() def crypto_validator(func): \"\"\" This a", "k in six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout) #", "'ipsec', 'ir', 'isakmp', 'l2', 'l2tp', 'llmnr', 'lltd', 'mgcp', 'mobileip', 'netbios',", "Filed by route.py route6 = None # Filed by route6.py", "{} self.layer2num = {} def register(self, num, layer): self.register_num2layer(num, layer)", "'hsrp', 'inet', 'inet6', 'ipsec', 'ir', 'isakmp', 'l2', 'l2tp', 'llmnr', 'lltd',", "def keys(self): if self.timeout is None: return dict.keys(self) t0 =", "NOT be done # noqa: E501 AS_resolver: choose the AS", "val): setattr(obj, self.intname, val) self.hook(self.name, val, *self.args, **self.kargs) def _readonly(name):", "# We only update an element from `other` either if", "the ones in ICMP citation # noqa: E501 iff :", "We could use LooseVersion, but distutils imports imp which is", "the current prompt theme\"\"\" try: sys.ps1 = conf.color_theme.prompt(conf.prompt) except Exception:", "= \"\" cache_iflist = {} route = None # Filed", "as e: for key, value in restore.items(): Interceptor.set_from_hook(conf, key, value)", "self.num2layer def get(self, item, default=None): return self[item] if item in", "<<EMAIL>> # This program is published under a GPLv2 license", "item, v): if item in self.__slots__: return object.__setattr__(self, item, v)", "# Update globals _load(\"scapy.arch.bpf\") return if LINUX: from scapy.arch.linux import", "= layer def register_layer2num(self, num, layer): self.layer2num[layer] = num def", "it does # not exist in `self` or if the", "\"_\": r = repr(getattr(self, i)) r = \" \".join(r.split()) wlen", "'tftp', 'vrrp', 'vxlan', 'x509', 'zigbee'] contribs = dict() crypto_valid =", "class ProgPath(ConfClass): universal_open = \"open\" if DARWIN else \"xdg-open\" pdfreader", "class Emphasize(ConfigFieldList): pass class Resolve(ConfigFieldList): pass class Num2Layer: def __init__(self):", "could use LooseVersion, but distutils imports imp which is deprecated", "conf.L3socket = L3bpfSocket conf.L3socket6 = functools.partial(L3bpfSocket, filter=\"ip6\") conf.L2socket = L2bpfSocket", "'pptp', 'radius', 'rip', 'rtp', 'sctp', 'sixlowpan', 'skinny', 'smb', 'snmp', 'tftp',", "cryptography library is present, and if it is recent enough", "= isCryptographyRecent() crypto_valid_advanced = crypto_valid_recent and isCryptographyAdvanced() fancy_prompt = True", "def __init__(self, name=None, default=None, hook=None, args=None, kargs=None): self.name = name", "Interceptor(object): def __init__(self, name=None, default=None, hook=None, args=None, kargs=None): self.name =", "self.hook = hook self.args = args if args is not", "to use extensions_paths: path or list of paths where extensions", "\"\"\"Handle a change of conf.logLevel\"\"\" log_scapy.setLevel(val) class Conf(ConfClass): \"\"\"This object", "return self.layer2num[item] return self.num2layer[item] def __contains__(self, item): if isinstance(item, base_classes.Packet_metaclass):", "distutils imports imp which is deprecated version_regexp = r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags", "name, timeout=None): c = CacheInstance(name=name, timeout=timeout) self.add_cache(c) def __delattr__(self, attr):", "\"\").lower().startswith(\"y\") use_bpf = Interceptor(\"use_bpf\", False, _socket_changer) use_npcap = False ipv6_enabled", "__setitem__(self, item, v): if item in self.__slots__: return object.__setattr__(self, item,", "if i[0] != \"_\": r = repr(getattr(self, i)) r =", "__init__(self): list.__init__(self) self.ldict = {} def __repr__(self): return \"\\n\".join(\"%-20s: %s\"", "True debug_dissector = False color_theme = Interceptor(\"color_theme\", NoTheme(), _prompt_changer) warning_threshold", "class ConfClass(object): def configure(self, cnf): self.__dict__ = cnf.__dict__.copy() def __repr__(self):", "self._timetable[item] if time.time() - t > self.timeout: raise KeyError(item) return", "= L3WinSocket conf.L3socket6 = L3WinSocket6 conf.L2socket = _NotAvailableSocket conf.L2listen =", "off \"use_pcap\": [\"use_bpf\"], \"use_bpf\": [\"use_pcap\"], } restore = {k: getattr(conf,", "conf.use_pcap and SOLARIS: Interceptor.set_from_hook(conf, \"use_pcap\", True) raise ScapyInvalidPlatformException( \"Scapy only", "Scapy. session : filename where the session will be saved", "noqa: E501 if 1, checks that they either are equal", "to every sniffing socket to exclude traffic from analysis #", "int_name, val) def __set__(self, obj, val): setattr(obj, self.intname, val) self.hook(self.name,", "10) if len(r) > wlen: r = r[:wlen - 3]", "raise ImportError(\"Cannot execute crypto-related method! \" \"Please install python-cryptography v1.7", "return cmd # return cmd so that method can be", "file padding : includes padding in disassembled packets except_filter :", "in some NAT stacks) # noqa: E501 checkIPinIP: if True,", "# noqa: E501 def __repr__(self): s = [] if self:", "scapy is running under PyPy or not\"\"\" try: import __pypy__", "= L3pcapSocket conf.L3socket6 = functools.partial(L3pcapSocket, filter=\"ip6\") conf.L2socket = L2pcapSocket conf.L2listen", "be done # noqa: E501 AS_resolver: choose the AS resolver", "self.ldict[layer.__module__] = [] self.ldict[layer.__module__].append(layer) def layers(self): result = [] #", "= None # Filed by route.py route6 = None #", "new_cache(self, name, timeout=None): c = CacheInstance(name=name, timeout=timeout) self.add_cache(c) def __delattr__(self,", "60 bufsize = 2**16 histfile = os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"), \".scapy_history\")) padding", "useless, but it is required for the eval below import", "if item in self else default def __repr__(self): lst =", "element from `other` either if it does # not exist", "def __getitem__(self, item): if item in self.__slots__: return object.__getattribute__(self, item)", "7)) def isCryptographyRecent(): \"\"\" Check if the cryptography library is", "recent enough for most usages in scapy (v1.7 or later).", "class NetCache: def __init__(self): self._caches_list = [] def add_cache(self, cache):", "raise AttributeError(\"Cannot delete attributes\") def update(self, other): for co in", "not hasattr(obj, self.intname): setattr(obj, self.intname, self.default) return getattr(obj, self.intname) @staticmethod", "re import time import socket import sys from scapy import", "universal_open = \"open\" if DARWIN else \"xdg-open\" pdfreader = universal_open", "conf.L2listen = L2bpfListenSocket # Update globals _load(\"scapy.arch.bpf\") return if LINUX:", "to 3 (verbose) promisc : default mode for listening socket", "wepkey = \"\" cache_iflist = {} route = None #", "try: return self[item] except KeyError: return default def __setitem__(self, item,", "False verb = 2 prompt = Interceptor(\"prompt\", \">>> \", _prompt_changer)", "{} def __repr__(self): return \"\\n\".join(\"%-20s: %s\" % (l.__name__, l.name) for", "t0 - self._timetable[k] < self.timeout) # noqa: E501 def items(self):", "sendp(). default:\"eth0\") # noqa: E501 verb : level of verbosity,", "[] for num, layer in six.iteritems(self.num2layer): if layer in self.layer2num", "add(self, *flds): self.fields |= {f for f in flds if", "in self) def register(self, layer): self.append(layer) if layer.__module__ not in", "cryptography except ImportError: return False return _version_checker(cryptography, (1, 7)) def", "self.intname, self.default) return getattr(obj, self.intname) @staticmethod def set_from_hook(obj, name, val):", "result.append((lay, doc.strip().split(\"\\n\")[0] if doc else lay)) return result class CommandsList(list):", "self.default = default self.hook = hook self.args = args if", "raw_layer = None raw_summary = False default_l2 = None l2types", "such (v2.0 or later). \"\"\" try: from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey", "class CommandsList(list): def __repr__(self): s = [] for l in", "VERSION) session = \"\" interactive = False interactive_shell = \"\"", "isinstance(item, base_classes.Packet_metaclass): return self.layer2num[item] return self.num2layer[item] def __contains__(self, item): if", "Exception: return False else: return True def isPyPy(): \"\"\"Returns either", "len(self.keys()) def summary(self): return \"%s: %i valid items. Timeout=%rs\" %", "= L2bpfListenSocket # Update globals _load(\"scapy.arch.bpf\") return if LINUX: from", "% (self.__class__.__name__, \" \".join(str(x) for x in self.fields)) # noqa:", "\".\" stats_classic_protocols = [] stats_dot11_protocols = [] temp_files = []", "import sys from scapy import VERSION, base_classes from scapy.consts import", "num not in self.num2layer or self.num2layer[num] != layer: lst.append((num, \"%#6x", "'bluetooth4LE', 'dhcp', 'dhcp6', 'dns', 'dot11', 'dot15d4', 'eap', 'gprs', 'hsrp', 'inet',", "= ReadOnlyAttribute(\"version\", VERSION) session = \"\" interactive = False interactive_shell", "eval below import scapy # noqa: F401 for lay in", "(v2.0 or later). \"\"\" try: from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey #", "r[:wlen - 3] + \"...\" s += \"%-10s = %s\\n\"", "< self.timeout] # noqa: E501 def values(self): if self.timeout is", "list of paths where extensions are to be looked for", "configuration object. \"\"\" from __future__ import absolute_import from __future__ import", "# noqa: E501 def __len__(self): if self.timeout is None: return", "update globals on Windows return from scapy.supersocket import L3RawSocket from", "layer): self.append(layer) if layer.__module__ not in self.ldict: self.ldict[layer.__module__] = []", ": filename where the session will be saved interactive_shell :", "len(self), self.timeout) # noqa: E501 def __repr__(self): s = []", "return result class CommandsList(list): def __repr__(self): s = [] for", "conf.L3socket6 = functools.partial(L3pcapSocket, filter=\"ip6\") conf.L2socket = L2pcapSocket conf.L2listen = L2pcapListenSocket", "for (k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] <", "item): if isinstance(item, base_classes.Packet_metaclass): return self.layer2num[item] return self.num2layer[item] def __contains__(self,", "def isCryptographyAdvanced(): \"\"\" Check if the cryptography library is present,", "layers = LayersList() commands = CommandsList() dot15d4_protocol = None #", ") ReadOnlyAttribute.__doc__ = \"Read-only class attribute\" class ProgPath(ConfClass): universal_open =", "is running under PyPy or not\"\"\" try: import __pypy__ #", "\">>> \", _prompt_changer) promisc = True sniff_promisc = 1 raw_layer", "route : holds the Scapy routing table and provides methods", "def flush(self): self.__init__(name=self.name, timeout=self.timeout) def __getitem__(self, item): if item in", "% item) return \"\\n\".join(s) class NetCache: def __init__(self): self._caches_list =", "ipv6_enabled = socket.has_ipv6 extensions_paths = \".\" stats_classic_protocols = [] stats_dot11_protocols", "deprecated version_regexp = r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags = re.match(version_regexp, module.__version__) if not", "conf.L2listen = _NotAvailableSocket # No need to update globals on", "path or list of paths where extensions are to be", "= False interactive_shell = \"\" stealth = \"not implemented\" iface", "\"...\" s += \"%-10s = %s\\n\" % (i, r) return", "'snmp', 'tftp', 'vrrp', 'vxlan', 'x509', 'zigbee'] contribs = dict() crypto_valid", "= os.getenv('SCAPY_HISTFILE', os.path.join(os.path.expanduser(\"~\"), \".scapy_history\")) padding = 1 except_filter = \"\"", "x in self.fields)) # noqa: E501 class Emphasize(ConfigFieldList): pass class", "= None raw_summary = False default_l2 = None l2types =", "ProgPath(ConfClass): universal_open = \"open\" if DARWIN else \"xdg-open\" pdfreader =", "__getattr__(self, attr): # Those are loaded on runtime to avoid", "CommandsList(list): def __repr__(self): s = [] for l in sorted(self,", "True check_TCPerror_seqack = False verb = 2 prompt = Interceptor(\"prompt\",", "of fields for which resolution should be done noenum :", "__pypy__ # noqa: F401 return True except ImportError: return False", "= timeout self.name = name self._timetable = {} def flush(self):", "self.kargs = kargs if kargs is not None else {}", "match. If False, do not check IP layers that encapsulates", "should be a boolean\") dependencies = { # Things that", "f in flds if self._is_field(f)} self._recalc_layer_list() def remove(self, *flds): self.fields", "Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C)", "between warnings from the same place ASN1_default_codec: Codec used by", "(mk + 1) for item in six.iteritems(self.__dict__): s.append(fmt % item)", "'gprs', 'hsrp', 'inet', 'inet6', 'ipsec', 'ir', 'isakmp', 'l2', 'l2tp', 'llmnr',", "wireshark = \"wireshark\" ifconfig = \"ifconfig\" class ConfigFieldList: def __init__(self):", "= functools.partial(L3PacketSocket, filter=\"ip6\") conf.L2socket = L2Socket conf.L2listen = L2ListenSocket #", "as a decorator def lsc(): \"\"\"Displays Scapy's default commands\"\"\" print(repr(conf.commands))", "def isPyPy(): \"\"\"Returns either scapy is running under PyPy or", "import DARWIN, WINDOWS, LINUX, BSD, SOLARIS from scapy.error import log_scapy,", "def __repr__(self): return \"\\n\".join(\"%-20s: %s\" % (l.__name__, l.name) for l", "E501 def keys(self): if self.timeout is None: return dict.keys(self) t0", "IP sent and ICMP IP citation received # noqa: E501", "_socket_changer(attr, val): if not isinstance(val, bool): raise TypeError(\"This argument should", "None # can, tls, http are not loaded by default", "(2, 0)) def isCryptographyAdvanced(): \"\"\" Check if the cryptography library", "scapy.data import ETHER_TYPES return ETHER_TYPES if attr == \"protocols\": from", "other._timetable[key] def iteritems(self): if self.timeout is None: return six.iteritems(self.__dict__) t0", "'dhcp6', 'dns', 'dot11', 'dot15d4', 'eap', 'gprs', 'hsrp', 'inet', 'inet6', 'ipsec',", "c = CacheInstance(name=name, timeout=timeout) self.add_cache(c) def __delattr__(self, attr): raise AttributeError(\"Cannot", "= True recv_poll_rate = 0.05 def __getattr__(self, attr): # Those", "auto_crop_tables = True recv_poll_rate = 0.05 def __getattr__(self, attr): #", "= \"\" keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys) for", "decorator def lsc(): \"\"\"Displays Scapy's default commands\"\"\" print(repr(conf.commands)) class CacheInstance(dict,", "\"_intercepted_%s\" % name self.default = default self.hook = hook self.args", "six.iteritems(self.__dict__) t0 = time.time() return ((k, v) for (k, v)", "TCP seq and ack match the ones in ICMP citation", "return item in self.layer2num return item in self.num2layer def get(self,", "on the 'crypto_valid' attribute of the global 'conf'. \"\"\" def", "implemented\" iface = None iface6 = None layers = LayersList()", "None raw_summary = False default_l2 = None l2types = Num2Layer()", "*flds): self.fields -= set(flds) self._recalc_layer_list() def __contains__(self, elt): if isinstance(elt,", "cache) def new_cache(self, name, timeout=None): c = CacheInstance(name=name, timeout=timeout) self.add_cache(c)", "noenum = Resolve() emph = Emphasize() use_pypy = ReadOnlyAttribute(\"use_pypy\", isPyPy())", "__init__(self): self.num2layer = {} self.layer2num = {} def register(self, num,", "def _version_checker(module, minver): \"\"\"Checks that module has a higher version", "# noqa: E501 if 2, strictly checks that they are", "other._caches_list: if hasattr(self, co.name): getattr(self, co.name).update(co) else: self.add_cache(co.copy()) def flush(self):", "ScapyInvalidPlatformException(\"BSD-like (OSX, *BSD...) only !\") if not conf.use_pcap and SOLARIS:", "L2bpfSocket conf.L2listen = L2bpfListenSocket # Update globals _load(\"scapy.arch.bpf\") return if", "conf.use_bpf: from scapy.arch.bpf.supersocket import L2bpfListenSocket, \\ L2bpfSocket, L3bpfSocket conf.L3socket =", "(verbose) promisc : default mode for listening socket (to get", "checkIPsrc: if 1, checks IP src in IP and ICMP", "Interceptor.set_from_hook(conf, key, value) if isinstance(e, ScapyInvalidPlatformException): raise def _loglevel_changer(attr, val):", "name=\"noname\", timeout=None): self.timeout = timeout self.name = name self._timetable =", "= \"_intercepted_%s\" % name self.default = default self.hook = hook", "= {} def flush(self): self.__init__(name=self.name, timeout=self.timeout) def __getitem__(self, item): if", "ETHER_TYPES if attr == \"protocols\": from scapy.data import IP_PROTOS return", "listening socket (to get answers if you spoof on a", "def layers(self): result = [] # This import may feel", "version_tags = re.match(version_regexp, module.__version__) if not version_tags: return False version_tags", "socket.has_ipv6 extensions_paths = \".\" stats_classic_protocols = [] stats_dot11_protocols = []", "conf.L2Socket and conf.L3Socket according to the various use_* parameters \"\"\"", "This a decorator to be used for any method relying", "Interceptor.set_from_hook if conf.use_pcap or conf.use_dnet: try: from scapy.arch.pcapdnet import L2pcapListenSocket,", "['bluetooth', 'bluetooth4LE', 'dhcp', 'dhcp6', 'dns', 'dot11', 'dot15d4', 'eap', 'gprs', 'hsrp',", "= universal_open svgreader = universal_open dot = \"dot\" display =", "that IPID matches between IP sent and ICMP IP citation", "f in self.fields for owner in f.owners} def add(self, *flds):", "set() self.layers = set() @staticmethod def _is_field(f): return hasattr(f, \"owners\")", "or list of paths where extensions are to be looked", "[\"use_bpf\"], \"use_bpf\": [\"use_pcap\"], } restore = {k: getattr(conf, k) for", "get answers if you spoof on a lan) # noqa:", "already in an Interceptor hook, use Interceptor.set_from_hook if conf.use_pcap or", "TCP_SERVICES return TCP_SERVICES return object.__getattr__(self, attr) if not Conf.ipv6_enabled: log_scapy.warning(\"IPv6", "= set() self.layers = set() @staticmethod def _is_field(f): return hasattr(f,", "if layer in self.layer2num and self.layer2num[layer] == num: dir =", "= \"Read-only class attribute\" class ProgPath(ConfClass): universal_open = \"open\" if", "= kargs if kargs is not None else {} def", "time.time() - t > self.timeout: raise KeyError(item) return val def", "'rip', 'rtp', 'sctp', 'sixlowpan', 'skinny', 'smb', 'snmp', 'tftp', 'vrrp', 'vxlan',", "None: return list(six.itervalues(self)) t0 = time.time() return [v for (k,", "timeout=None): c = CacheInstance(name=name, timeout=timeout) self.add_cache(c) def __delattr__(self, attr): raise", "scapy.error import log_scapy, warning, ScapyInvalidPlatformException from scapy.modules import six from", "various use_* parameters \"\"\" from scapy.main import _load if conf.use_bpf", "= time.time() return (k for k in six.iterkeys(self.__dict__) if t0", "a higher version that minver. params: - module: a module", "isinstance(item, base_classes.Packet_metaclass): return item in self.layer2num return item in self.num2layer", "E501 Its behaviour depends on the 'crypto_valid' attribute of the", "DNS, ...) checkIPID: if 0, doesn't check that IPID matches", "be used as a decorator def lsc(): \"\"\"Displays Scapy's default", "wlen = 76 - max(len(i), 10) if len(r) > wlen:", "[] def add_cache(self, cache): self._caches_list.append(cache) setattr(self, cache.name, cache) def new_cache(self,", "delete attributes\") def update(self, other): for co in other._caches_list: if", "return if LINUX: from scapy.arch.linux import L3PacketSocket, L2Socket, L2ListenSocket conf.L3socket", "IP layers that encapsulates another IP layer check_TCPerror_seqack: if 1,", "1, prevents any unwanted packet to go out (ARP, DNS,", "CacheInstance(name=name, timeout=timeout) self.add_cache(c) def __delattr__(self, attr): raise AttributeError(\"Cannot delete attributes\")", "present, and if it supports X25519, ChaCha20Poly1305 and such (v2.0", "attr) if not Conf.ipv6_enabled: log_scapy.warning(\"IPv6 support disabled in Python. Cannot", "values(self): if self.timeout is None: return list(six.itervalues(self)) t0 = time.time()", "\"\" keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys) for i", "_NotAvailableSocket # No need to update globals on Windows return", "IP layer check_TCPerror_seqack: if 1, also check that TCP seq", "or not\"\"\" try: import __pypy__ # noqa: F401 return True", "encapsulates another IP layer check_TCPerror_seqack: if 1, also check that", "MIB direct access dictionary resolve : holds list of fields", "Auto stealth : if 1, prevents any unwanted packet to", "< self.timeout) # noqa: E501 def items(self): if self.timeout is", "v) in six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout) #", "flush(self): for c in self._caches_list: c.flush() def __repr__(self): return \"\\n\".join(c.summary()", "scapy # noqa: F401 for lay in self.ldict: doc =", "isinstance(val, bool): raise TypeError(\"This argument should be a boolean\") dependencies", "in self.fields)) # noqa: E501 class Emphasize(ConfigFieldList): pass class Resolve(ConfigFieldList):", "def _prompt_changer(attr, val): \"\"\"Change the current prompt theme\"\"\" try: sys.ps1", "} restore = {k: getattr(conf, k) for k in dependencies}", "= None l2types = Num2Layer() l3types = Num2Layer() L3socket =", "version_regexp = r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags = re.match(version_regexp, module.__version__) if not version_tags:", "return str(self) def __str__(self): s = \"\" keys = self.__class__.__dict__.copy()", "# Copyright (C) <NAME> <<EMAIL>> # This program is published", "val = dict.__getitem__(self, item) if self.timeout is not None: t", "CommandsList() dot15d4_protocol = None # Used in dot15d4.py logLevel =", "doc else lay)) return result class CommandsList(list): def __repr__(self): s", "layer.__name__, layer._name))) lst.sort() return \"\\n\".join(y for x, y in lst)", "for f in flds if self._is_field(f)} self._recalc_layer_list() def remove(self, *flds):", "def __setitem__(self, item, v): if item in self.__slots__: return object.__setattr__(self,", "iterkeys(self): if self.timeout is None: return six.iterkeys(self.__dict__) t0 = time.time()", "# we are already in an Interceptor hook, use Interceptor.set_from_hook", "# Only if True for param in dependencies[attr]: Interceptor.set_from_hook(conf, param,", "= 1 raw_layer = None raw_summary = False default_l2 =", "r = r[:wlen - 3] + \"...\" s += \"%-10s", "not None: t = self._timetable[item] if time.time() - t >", "(C) <NAME> <<EMAIL>> # This program is published under a", "elt): if isinstance(elt, base_classes.Packet_metaclass): return elt in self.layers return elt", "__repr__(self): s = [] if self: mk = max(len(k) for", "_load(\"scapy.arch.pcapdnet\") return if conf.use_bpf: from scapy.arch.bpf.supersocket import L2bpfListenSocket, \\ L2bpfSocket,", "either scapy is running under PyPy or not\"\"\" try: import", "conf.L3socket6 = L3RawSocket6 def _socket_changer(attr, val): if not isinstance(val, bool):", "AS_resolver: choose the AS resolver class to use extensions_paths: path", "often to check for new packets. Defaults to 0.05s. \"\"\"", "1 raw_layer = None raw_summary = False default_l2 = None", "attr == \"manufdb\": from scapy.data import MANUFDB return MANUFDB if", "check that TCP seq and ack match the ones in", "the cryptography library. # noqa: E501 Its behaviour depends on", "= [] netcache = NetCache() geoip_city = None # can,", "mk = max(len(k) for k in six.iterkeys(self.__dict__)) fmt = \"%%-%is", "self._timetable[key] < other._timetable[key]: dict.__setitem__(self, key, value) self._timetable[key] = other._timetable[key] def", "self.default) return getattr(obj, self.intname) @staticmethod def set_from_hook(obj, name, val): int_name", "_readonly(name): default = Conf.__dict__[name].default Interceptor.set_from_hook(conf, name, default) raise ValueError(\"Read-only value", "objects mib : holds MIB direct access dictionary resolve :", "and if it supports X25519, ChaCha20Poly1305 and such (v2.0 or", "dict.__getitem__(self, item) if self.timeout is not None: t = self._timetable[item]", "self[item] except KeyError: return default def __setitem__(self, item, v): if", "filter : bpf filter added to every sniffing socket to", "Things that will be turned off \"use_pcap\": [\"use_bpf\"], \"use_bpf\": [\"use_pcap\"],", "contains the configuration of Scapy. session : filename where the", "= crypto_valid_recent and isCryptographyAdvanced() fancy_prompt = True auto_crop_tables = True", "x.__name__): doc = l.__doc__.split(\"\\n\")[0] if l.__doc__ else \"--\" s.append(\"%-20s: %s\"", "layer in self.layer2num and self.layer2num[layer] == num: dir = \"<->\"", "= %s\\n\" % (i, r) return s[:-1] class Interceptor(object): def", "global 'conf'. \"\"\" def func_in(*args, **kwargs): if not conf.crypto_valid: raise", "in disassembled packets except_filter : BPF filter for packets to", "m in [\"inet6\", \"dhcp6\"]: if m in Conf.load_layers: Conf.load_layers.remove(m) conf", "in self._caches_list) def _version_checker(module, minver): \"\"\"Checks that module has a", "if it supports X25519, ChaCha20Poly1305 and such (v2.0 or later).", "= False verb = 2 prompt = Interceptor(\"prompt\", \">>> \",", "cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # noqa: E501 X25519PrivateKey.generate() except Exception: return", "val): if not isinstance(val, bool): raise TypeError(\"This argument should be", "attr == \"services_udp\": from scapy.data import UDP_SERVICES return UDP_SERVICES if", "E501 def __repr__(self): s = [] if self: mk =", "scapy.arch.windows import _NotAvailableSocket from scapy.arch.windows.native import L3WinSocket, L3WinSocket6 conf.L3socket =", "be a boolean\") dependencies = { # Things that will", "= 1 except_filter = \"\" debug_match = False debug_tls =", "= {} def register(self, num, layer): self.register_num2layer(num, layer) self.register_layer2num(num, layer)", "% (num, layer.__name__, layer._name))) lst.sort() return \"\\n\".join(y for x, y", "Check if the cryptography library is recent (2.0 and later)", "= \"hexer\" tshark = \"tshark\" wireshark = \"wireshark\" ifconfig =", "for param in dependencies[attr]: Interceptor.set_from_hook(conf, param, False) try: _set_conf_sockets() except", "self.timeout is None: return six.iteritems(self.__dict__) t0 = time.time() return ((k,", "the eval below import scapy # noqa: F401 for lay", "= conf.color_theme.prompt(conf.prompt) except Exception: pass try: apply_ipython_style(get_ipython()) except NameError: pass", "if isinstance(item, base_classes.Packet_metaclass): return item in self.layer2num return item in", "= \"wireshark\" ifconfig = \"ifconfig\" class ConfigFieldList: def __init__(self): self.fields", "if self.timeout is None: return six.iterkeys(self.__dict__) t0 = time.time() return", "[] if self: mk = max(len(k) for k in six.iterkeys(self.__dict__))", "def __set__(self, obj, val): setattr(obj, self.intname, val) self.hook(self.name, val, *self.args,", "XXX use_dnet is deprecated use_dnet = os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\") use_bpf =", "to store local configuration # noqa: E501 debug_tls:When 1, print", "the 'crypto_valid' attribute of the global 'conf'. \"\"\" def func_in(*args,", "def update(self, other): for key, value in six.iteritems(other): # We", "\"services_tcp\": from scapy.data import TCP_SERVICES return TCP_SERVICES return object.__getattr__(self, attr)", "(ARP, DNS, ...) checkIPID: if 0, doesn't check that IPID", "= \"_intercepted_%s\" % name setattr(obj, int_name, val) def __set__(self, obj,", "key, value in restore.items(): Interceptor.set_from_hook(conf, key, value) if isinstance(e, ScapyInvalidPlatformException):", "if attr == \"protocols\": from scapy.data import IP_PROTOS return IP_PROTOS", "only !\") if not conf.use_pcap and SOLARIS: Interceptor.set_from_hook(conf, \"use_pcap\", True)", "\"tshark\" wireshark = \"wireshark\" ifconfig = \"ifconfig\" class ConfigFieldList: def", "def crypto_validator(func): \"\"\" This a decorator to be used for", "Defaults to 0.05s. \"\"\" version = ReadOnlyAttribute(\"version\", VERSION) session =", "c.flush() def __repr__(self): return \"\\n\".join(c.summary() for c in self._caches_list) def", "# noqa: F401 return True except ImportError: return False def", "layer) self.register_layer2num(num, layer) def register_num2layer(self, num, layer): self.num2layer[num] = layer", "False version_tags = version_tags.group(1).split(\".\") version_tags = tuple(int(x) for x in", "\" ->\" lst.append((num, \"%#6x %s %-20s (%s)\" % (num, dir,", "also check that TCP seq and ack match the ones", "for packets to ignore debug_match : when 1, store received", "match the ones in ICMP citation # noqa: E501 iff", "dictionary resolve : holds list of fields for which resolution", "noqa: E501 def __iter__(self): return six.iterkeys(self.__dict__) def itervalues(self): if self.timeout", "try: from scapy.arch.pcapdnet import L2pcapListenSocket, L2pcapSocket, \\ L3pcapSocket except (OSError,", "functools.partial(L3PacketSocket, filter=\"ip6\") conf.L2socket = L2Socket conf.L2listen = L2ListenSocket # Update", "'ppi', 'ppp', 'pptp', 'radius', 'rip', 'rtp', 'sctp', 'sixlowpan', 'skinny', 'smb',", "if not conf.crypto_valid: raise ImportError(\"Cannot execute crypto-related method! \" \"Please", "and ICMP IP citation received # noqa: E501 if 1,", "dependencies} del restore[attr] # This is handled directly by _set_conf_sockets", "[] self.kargs = kargs if kargs is not None else", "def flush(self): for c in self._caches_list: c.flush() def __repr__(self): return", "= time.time() return [(k, v) for (k, v) in six.iteritems(self.__dict__)", "X25519, ChaCha20Poly1305 and such (v2.0 or later). \"\"\" try: from", "universal_open svgreader = universal_open dot = \"dot\" display = \"display\"", "return TCP_SERVICES return object.__getattr__(self, attr) if not Conf.ipv6_enabled: log_scapy.warning(\"IPv6 support", "conf.L2listen = L2pcapListenSocket # Update globals _load(\"scapy.arch.pcapdnet\") return if conf.use_bpf:", "default_l2 = None l2types = Num2Layer() l3types = Num2Layer() L3socket", "of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright", "in dot15d4.py logLevel = Interceptor(\"logLevel\", log_scapy.level, _loglevel_changer) checkIPID = False", "default=None, hook=None, args=None, kargs=None): self.name = name self.intname = \"_intercepted_%s\"", "os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"), _socket_changer ) # XXX use_dnet is deprecated use_dnet", "conf = Conf() def crypto_validator(func): \"\"\" This a decorator to", "verbosity, from 0 (almost mute) to 3 (verbose) promisc :", "E501 def items(self): if self.timeout is None: return dict.items(self) t0", "*args, **kwargs: _readonly(name)) ) ReadOnlyAttribute.__doc__ = \"Read-only class attribute\" class", "__get__(self, obj, typ=None): if not hasattr(obj, self.intname): setattr(obj, self.intname, self.default)", "scapy.themes import NoTheme, apply_ipython_style ############ # Config # ############ class", "not in self.num2layer or self.num2layer[num] != layer: lst.append((num, \"%#6x <-", "six.iteritems(self.__dict__) if t0 - self._timetable[k] < self.timeout] # noqa: E501", "apply_ipython_style(get_ipython()) except NameError: pass def _set_conf_sockets(): \"\"\"Populate the conf.L2Socket and", "None # Filed by route6.py auto_fragment = True debug_dissector =", "except_filter : BPF filter for packets to ignore debug_match :", "BSD: Interceptor.set_from_hook(conf, \"use_bpf\", False) raise ScapyInvalidPlatformException(\"BSD-like (OSX, *BSD...) only !\")", "conf.L3socket = L3PacketSocket conf.L3socket6 = functools.partial(L3PacketSocket, filter=\"ip6\") conf.L2socket = L2Socket", "sniffing socket to exclude traffic from analysis # noqa: E501", "def __repr__(self): s = [] if self: mk = max(len(k)", "only update an element from `other` either if it does", "NetCache() geoip_city = None # can, tls, http are not", "\"use_pcap\", True) raise ScapyInvalidPlatformException( \"Scapy only supports libpcap on Solaris", "that method can be used as a decorator def lsc():", "ScapyInvalidPlatformException( \"Scapy only supports libpcap on Solaris !\" ) #", "in six.iteritems(self.__dict__): s.append(fmt % item) return \"\\n\".join(s) class NetCache: def", "return ((k, v) for (k, v) in six.iteritems(self.__dict__) if t0", "file is part of Scapy # See http://www.secdev.org/projects/scapy for more", "\"\\n\".join(\"%-20s: %s\" % (l.__name__, l.name) for l in self) def", ": selects the default output interface for srp() and sendp().", "\"manufdb\": from scapy.data import MANUFDB return MANUFDB if attr ==", "(num, dir, layer.__name__, layer._name))) for layer, num in six.iteritems(self.layer2num): if", "getattr(conf, k) for k in dependencies} del restore[attr] # This", "Emphasize(ConfigFieldList): pass class Resolve(ConfigFieldList): pass class Num2Layer: def __init__(self): self.num2layer", "del restore[attr] # This is handled directly by _set_conf_sockets if", "analysis # noqa: E501 histfile : history file padding :", "if not conf.use_pcap and SOLARIS: Interceptor.set_from_hook(conf, \"use_pcap\", True) raise ScapyInvalidPlatformException(", "checkIPinIP = True check_TCPerror_seqack = False verb = 2 prompt", "check for new packets. Defaults to 0.05s. \"\"\" version =", "cryptography library is present, and if it supports X25519, ChaCha20Poly1305", "parameters \"\"\" from scapy.main import _load if conf.use_bpf and not", "True) raise ScapyInvalidPlatformException( \"Scapy only supports libpcap on Solaris !\"", "-= set(flds) self._recalc_layer_list() def __contains__(self, elt): if isinstance(elt, base_classes.Packet_metaclass): return", "noqa: E501 route : holds the Scapy routing table and", "can be \"ipython\", \"python\" or \"auto\". Default: Auto stealth :", "L3socket = None L3socket6 = None L2socket = None L2listen", "0 (almost mute) to 3 (verbose) promisc : default mode", "can be used by contrib layers to store local configuration", "Interceptor( \"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"), _socket_changer ) # XXX use_dnet is", "and not BSD: Interceptor.set_from_hook(conf, \"use_bpf\", False) raise ScapyInvalidPlatformException(\"BSD-like (OSX, *BSD...)", "% (mk + 1) for item in six.iteritems(self.__dict__): s.append(fmt %", "ChaCha20Poly1305 and such (v2.0 or later). \"\"\" try: from cryptography.hazmat.primitives.asymmetric.x25519", "else \"xdg-open\" pdfreader = universal_open psreader = universal_open svgreader =", "try: import cryptography except ImportError: return False return _version_checker(cryptography, (1,", "cache.name, cache) def new_cache(self, name, timeout=None): c = CacheInstance(name=name, timeout=timeout)", "AttributeError(\"Cannot delete attributes\") def update(self, other): for co in other._caches_list:", "contribs : a dict which can be used by contrib", "isCryptographyValid(): \"\"\" Check if the cryptography library is present, and", "Interceptor.set_from_hook(conf, \"use_pcap\", True) raise ScapyInvalidPlatformException( \"Scapy only supports libpcap on", "None min_pkt_size = 60 bufsize = 2**16 histfile = os.getenv('SCAPY_HISTFILE',", "later). \"\"\" try: import cryptography except ImportError: return False return", "item in self.num2layer def get(self, item, default=None): return self[item] if", "v) for (k, v) in six.iteritems(self.__dict__) if t0 - self._timetable[k]", "= r[:wlen - 3] + \"...\" s += \"%-10s =", "if the cryptography library is present, and if it is", "for layer, num in six.iteritems(self.layer2num): if num not in self.num2layer", "'radius', 'rip', 'rtp', 'sctp', 'sixlowpan', 'skinny', 'smb', 'snmp', 'tftp', 'vrrp',", "return dict.__len__(self) return len(self.keys()) def summary(self): return \"%s: %i valid", "http are not loaded by default load_layers = ['bluetooth', 'bluetooth4LE',", "imp which is deprecated version_regexp = r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags = re.match(version_regexp,", "a lan) # noqa: E501 sniff_promisc : default mode for", "__len__(self): if self.timeout is None: return dict.__len__(self) return len(self.keys()) def", "PyPy or not\"\"\" try: import __pypy__ # noqa: F401 return", "that TCP seq and ack match the ones in ICMP", "time.time() return [k for k in six.iterkeys(self.__dict__) if t0 -", "isPyPy()) use_pcap = Interceptor( \"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"), _socket_changer ) #", "t0 - self._timetable[k] < self.timeout) # noqa: E501 def iterkeys(self):", "name setattr(obj, int_name, val) def __set__(self, obj, val): setattr(obj, self.intname,", "return six.itervalues(self.__dict__) t0 = time.time() return (v for (k, v)", "- self._timetable[k] < self.timeout) # noqa: E501 def __iter__(self): return", "= False ipv6_enabled = socket.has_ipv6 extensions_paths = \".\" stats_classic_protocols =", "and conf.L3Socket according to the various use_* parameters \"\"\" from", "information # Copyright (C) <NAME> <<EMAIL>> # This program is", "(ScapyInvalidPlatformException, ImportError) as e: for key, value in restore.items(): Interceptor.set_from_hook(conf,", "conf.L2socket = L2bpfSocket conf.L2listen = L2bpfListenSocket # Update globals _load(\"scapy.arch.bpf\")", "def isCryptographyRecent(): \"\"\" Check if the cryptography library is recent", "= \"dot\" display = \"display\" tcpdump = \"tcpdump\" tcpreplay =", "in `self` is older. if key not in self or", "args=None, kargs=None): self.name = name self.intname = \"_intercepted_%s\" % name", "update an element from `other` either if it does #", "self: mk = max(len(k) for k in six.iterkeys(self.__dict__)) fmt =", "in an Interceptor hook, use Interceptor.set_from_hook if conf.use_pcap or conf.use_dnet:", "= CommandsList() dot15d4_protocol = None # Used in dot15d4.py logLevel", "= functools.partial( Interceptor, hook=(lambda name, *args, **kwargs: _readonly(name)) ) ReadOnlyAttribute.__doc__", "done noenum : holds list of enum fields for which", "timeout self.name = name self._timetable = {} def flush(self): self.__init__(name=self.name,", "noqa: F401 return True except ImportError: return False def _prompt_changer(attr,", "use LooseVersion, but distutils imports imp which is deprecated version_regexp", "\"\"\" try: import cryptography except ImportError: return False return _version_checker(cryptography,", "sys from scapy import VERSION, base_classes from scapy.consts import DARWIN,", "warning, ScapyInvalidPlatformException from scapy.modules import six from scapy.themes import NoTheme,", "= Interceptor(\"logLevel\", log_scapy.level, _loglevel_changer) checkIPID = False checkIPsrc = True", "hasattr(self, co.name): getattr(self, co.name).update(co) else: self.add_cache(co.copy()) def flush(self): for c", "False wepkey = \"\" cache_iflist = {} route = None", "ignore debug_match : when 1, store received packet that are", "# overloading this method is needed to force the dict", "[] self.ldict[layer.__module__].append(layer) def layers(self): result = [] # This import", "!= \"_\": r = repr(getattr(self, i)) r = \" \".join(r.split())", "{} def register(self, num, layer): self.register_num2layer(num, layer) self.register_layer2num(num, layer) def", "self.num2layer[item] def __contains__(self, item): if isinstance(item, base_classes.Packet_metaclass): return item in", "if it does # not exist in `self` or if", "\"auto\". Default: Auto stealth : if 1, prevents any unwanted", "False default_l2 = None l2types = Num2Layer() l3types = Num2Layer()", "disassembled packets except_filter : BPF filter for packets to ignore", "isCryptographyRecent() crypto_valid_advanced = crypto_valid_recent and isCryptographyAdvanced() fancy_prompt = True auto_crop_tables", "should be done noenum : holds list of enum fields", "None # Filed by route.py route6 = None # Filed", "six.iteritems(self.layer2num): if num not in self.num2layer or self.num2layer[num] != layer:", "ifconfig = \"ifconfig\" class ConfigFieldList: def __init__(self): self.fields = set()", "not BSD: Interceptor.set_from_hook(conf, \"use_bpf\", False) raise ScapyInvalidPlatformException(\"BSD-like (OSX, *BSD...) only", "a tuple of versions \"\"\" # We could use LooseVersion,", "= set() @staticmethod def _is_field(f): return hasattr(f, \"owners\") def _recalc_layer_list(self):", "ReadOnlyAttribute.__doc__ = \"Read-only class attribute\" class ProgPath(ConfClass): universal_open = \"open\"", "except KeyError: return default def __setitem__(self, item, v): if item", "self.name = name self.intname = \"_intercepted_%s\" % name self.default =", "def itervalues(self): if self.timeout is None: return six.itervalues(self.__dict__) t0 =", "fields for which resolution should be done noenum : holds", "to be used for any method relying on the cryptography", "and if it is recent enough for most usages in", "be used\") Interceptor.set_from_hook(conf, \"use_pcap\", False) else: conf.L3socket = L3pcapSocket conf.L3socket6", "KeyError: return default def __setitem__(self, item, v): if item in", "= functools.partial(L3bpfSocket, filter=\"ip6\") conf.L2socket = L2bpfSocket conf.L2listen = L2bpfListenSocket #", "'ppp', 'pptp', 'radius', 'rip', 'rtp', 'sctp', 'sixlowpan', 'skinny', 'smb', 'snmp',", "= [] for l in sorted(self, key=lambda x: x.__name__): doc", "== \"ethertypes\": from scapy.data import ETHER_TYPES return ETHER_TYPES if attr", "for srp() and sendp(). default:\"eth0\") # noqa: E501 verb :", "Default: Auto stealth : if 1, prevents any unwanted packet", "< self.timeout] # noqa: E501 def __len__(self): if self.timeout is", "they are computed. recv_poll_rate: how often to check for new", "ICMP citation # noqa: E501 iff : selects the default", ": bpf filter added to every sniffing socket to exclude", "'skinny', 'smb', 'snmp', 'tftp', 'vrrp', 'vxlan', 'x509', 'zigbee'] contribs =", "install python-cryptography v1.7 or later.\") # noqa: E501 return func(*args,", "to ignore debug_match : when 1, store received packet that", "log_scapy.level, _loglevel_changer) checkIPID = False checkIPsrc = True checkIPaddr =", "v) def update(self, other): for key, value in six.iteritems(other): #", "if not version_tags: return False version_tags = version_tags.group(1).split(\".\") version_tags =", "= None min_pkt_size = 60 bufsize = 2**16 histfile =", "return _version_checker(cryptography, (1, 7)) def isCryptographyRecent(): \"\"\" Check if the", "return six.iterkeys(self.__dict__) def itervalues(self): if self.timeout is None: return six.itervalues(self.__dict__)", "val): \"\"\"Change the current prompt theme\"\"\" try: sys.ps1 = conf.color_theme.prompt(conf.prompt)", "False) try: _set_conf_sockets() except (ScapyInvalidPlatformException, ImportError) as e: for key,", "def __init__(self, name=\"noname\", timeout=None): self.timeout = timeout self.name = name", "sniff_promisc = 1 raw_layer = None raw_summary = False default_l2", "most usages in scapy (v1.7 or later). \"\"\" try: import", "self.timeout is None: return list(six.itervalues(self)) t0 = time.time() return [v", "be turned off \"use_pcap\": [\"use_bpf\"], \"use_bpf\": [\"use_pcap\"], } restore =", "% (l.__name__, l.name) for l in self) def register(self, layer):", "def __delattr__(self, attr): raise AttributeError(\"Cannot delete attributes\") def update(self, other):", "exclude traffic from analysis # noqa: E501 histfile : history", "the conf.L2Socket and conf.L3Socket according to the various use_* parameters", "configuration # noqa: E501 debug_tls:When 1, print some TLS session", "if isinstance(e, ScapyInvalidPlatformException): raise def _loglevel_changer(attr, val): \"\"\"Handle a change", "dependencies[attr]: Interceptor.set_from_hook(conf, param, False) try: _set_conf_sockets() except (ScapyInvalidPlatformException, ImportError) as", "self.fields def __repr__(self): return \"<%s [%s]>\" % (self.__class__.__name__, \" \".join(str(x)", "Interceptor.set_from_hook(conf, param, False) try: _set_conf_sockets() except (ScapyInvalidPlatformException, ImportError) as e:", "are not loaded by default load_layers = ['bluetooth', 'bluetooth4LE', 'dhcp',", "it is recent enough for most usages in scapy (v1.7", "t > self.timeout: raise KeyError(item) return val def get(self, item,", "from scapy.modules import six from scapy.themes import NoTheme, apply_ipython_style ############", "keys(self): if self.timeout is None: return dict.keys(self) t0 = time.time()", "- self._timetable[k] < self.timeout] # noqa: E501 def __len__(self): if", "are loaded on runtime to avoid import loops if attr", "if True for param in dependencies[attr]: Interceptor.set_from_hook(conf, param, False) try:", "= Interceptor(\"prompt\", \">>> \", _prompt_changer) promisc = True sniff_promisc =", "filter=\"ip6\") conf.L2socket = L2Socket conf.L2listen = L2ListenSocket # Update globals", "log_scapy.warning(\"IPv6 support disabled in Python. Cannot load Scapy IPv6 layers.\")", "layer def register_layer2num(self, num, layer): self.layer2num[layer] = num def __getitem__(self,", "has a higher version that minver. params: - module: a", "True def isPyPy(): \"\"\"Returns either scapy is running under PyPy", "conf.L3socket6 = functools.partial(L3PacketSocket, filter=\"ip6\") conf.L2socket = L2Socket conf.L2listen = L2ListenSocket", "str(self) def __str__(self): s = \"\" keys = self.__class__.__dict__.copy() keys.update(self.__dict__)", "loops if attr == \"manufdb\": from scapy.data import MANUFDB return", "L2pcapSocket, \\ L3pcapSocket except (OSError, ImportError): warning(\"No libpcap provider available", "to test - minver: a tuple of versions \"\"\" #", "six.iterkeys(self.__dict__) if t0 - self._timetable[k] < self.timeout) # noqa: E501", "return [v for (k, v) in six.iteritems(self.__dict__) if t0 -", "+ \"...\" s += \"%-10s = %s\\n\" % (i, r)", "to force the dict to go through # the timetable", "are to be looked for contribs : a dict which", "E501 AS_resolver: choose the AS resolver class to use extensions_paths:", "E501 for m in [\"inet6\", \"dhcp6\"]: if m in Conf.load_layers:", "= version_tags.group(1).split(\".\") version_tags = tuple(int(x) for x in version_tags) return", "= _NotAvailableSocket conf.L2listen = _NotAvailableSocket # No need to update", "# This is handled directly by _set_conf_sockets if val: #", "s.append(fmt % item) return \"\\n\".join(s) class NetCache: def __init__(self): self._caches_list", "= Interceptor(\"color_theme\", NoTheme(), _prompt_changer) warning_threshold = 5 prog = ProgPath()", "0)) def isCryptographyAdvanced(): \"\"\" Check if the cryptography library is", "\"ifconfig\" class ConfigFieldList: def __init__(self): self.fields = set() self.layers =", "# noqa: E501 sniff_promisc : default mode for sniff() filter", "except ImportError: return False return _version_checker(cryptography, (2, 0)) def isCryptographyAdvanced():", "time.time() return (k for k in six.iterkeys(self.__dict__) if t0 -", "= Resolve() noenum = Resolve() emph = Emphasize() use_pypy =", "self._caches_list.append(cache) setattr(self, cache.name, cache) def new_cache(self, name, timeout=None): c =", "None: return six.iterkeys(self.__dict__) t0 = time.time() return (k for k", "item in self.__slots__: return object.__setattr__(self, item, v) self._timetable[item] = time.time()", "won't be used\") Interceptor.set_from_hook(conf, \"use_pcap\", False) else: conf.L3socket = L3pcapSocket", "= None iface6 = None layers = LayersList() commands =", "if time.time() - t > self.timeout: raise KeyError(item) return val", "conf.use_pcap or conf.use_dnet: try: from scapy.arch.pcapdnet import L2pcapListenSocket, L2pcapSocket, \\", "Num2Layer: def __init__(self): self.num2layer = {} self.layer2num = {} def", "co.name): getattr(self, co.name).update(co) else: self.add_cache(co.copy()) def flush(self): for c in", "to exclude traffic from analysis # noqa: E501 histfile :", "val): \"\"\"Handle a change of conf.logLevel\"\"\" log_scapy.setLevel(val) class Conf(ConfClass): \"\"\"This", "############ # Config # ############ class ConfClass(object): def configure(self, cnf):", "item, v) self._timetable[item] = time.time() dict.__setitem__(self, item, v) def update(self,", "L2bpfListenSocket, \\ L2bpfSocket, L3bpfSocket conf.L3socket = L3bpfSocket conf.L3socket6 = functools.partial(L3bpfSocket,", "# noqa: F401 for lay in self.ldict: doc = eval(lay).__doc__", "Conf() def crypto_validator(func): \"\"\" This a decorator to be used", "bool): raise TypeError(\"This argument should be a boolean\") dependencies =", "from __future__ import absolute_import from __future__ import print_function import functools", "= repr(getattr(self, i)) r = \" \".join(r.split()) wlen = 76", "self.timeout is not None: t = self._timetable[item] if time.time() -", "from analysis # noqa: E501 histfile : history file padding", "LINUX: from scapy.arch.linux import L3PacketSocket, L2Socket, L2ListenSocket conf.L3socket = L3PacketSocket", "import ETHER_TYPES return ETHER_TYPES if attr == \"protocols\": from scapy.data", "|= {f for f in flds if self._is_field(f)} self._recalc_layer_list() def", "six from scapy.themes import NoTheme, apply_ipython_style ############ # Config #", "= {} route = None # Filed by route.py route6", "= time.time() return [k for k in six.iterkeys(self.__dict__) if t0", "to string should NOT be done # noqa: E501 AS_resolver:", "'zigbee'] contribs = dict() crypto_valid = isCryptographyValid() crypto_valid_recent = isCryptographyRecent()", "is handled directly by _set_conf_sockets if val: # Only if", "%i valid items. Timeout=%rs\" % (self.name, len(self), self.timeout) # noqa:", "lst = [] for num, layer in six.iteritems(self.num2layer): if layer", "return False return _version_checker(cryptography, (2, 0)) def isCryptographyAdvanced(): \"\"\" Check", "interactive_shell = \"\" stealth = \"not implemented\" iface = None", "object): __slots__ = [\"timeout\", \"name\", \"_timetable\", \"__dict__\"] def __init__(self, name=\"noname\",", "self) def register(self, layer): self.append(layer) if layer.__module__ not in self.ldict:", "turned off \"use_pcap\": [\"use_bpf\"], \"use_bpf\": [\"use_pcap\"], } restore = {k:", "\"tcpdump\" tcpreplay = \"tcpreplay\" hexedit = \"hexer\" tshark = \"tshark\"", "% (l.__name__, doc)) return \"\\n\".join(s) def register(self, cmd): self.append(cmd) return", "else: return True def isPyPy(): \"\"\"Returns either scapy is running", "_socket_changer) use_npcap = False ipv6_enabled = socket.has_ipv6 extensions_paths = \".\"", "t0 - self._timetable[k] < self.timeout] # noqa: E501 def values(self):", "X25519PrivateKey # noqa: E501 X25519PrivateKey.generate() except Exception: return False else:", "session : filename where the session will be saved interactive_shell", "scapy import VERSION, base_classes from scapy.consts import DARWIN, WINDOWS, LINUX,", "isCryptographyAdvanced() fancy_prompt = True auto_crop_tables = True recv_poll_rate = 0.05", "used as a decorator def lsc(): \"\"\"Displays Scapy's default commands\"\"\"", "sorted(keys) for i in keys: if i[0] != \"_\": r", "in self._caches_list: c.flush() def __repr__(self): return \"\\n\".join(c.summary() for c in", "that IP-in-IP layers match. If False, do not check IP", "= Resolve() emph = Emphasize() use_pypy = ReadOnlyAttribute(\"use_pypy\", isPyPy()) use_pcap", "doc)) return \"\\n\".join(s) def register(self, cmd): self.append(cmd) return cmd #", "76 - max(len(i), 10) if len(r) > wlen: r =", "= L3RawSocket6 def _socket_changer(attr, val): if not isinstance(val, bool): raise", "store received packet that are not matched into debug.recv #", "= ReadOnlyAttribute(\"use_pypy\", isPyPy()) use_pcap = Interceptor( \"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"), _socket_changer", "dict.items(self) t0 = time.time() return [(k, v) for (k, v)", "base_classes from scapy.consts import DARWIN, WINDOWS, LINUX, BSD, SOLARIS from", "return if conf.use_bpf: from scapy.arch.bpf.supersocket import L2bpfListenSocket, \\ L2bpfSocket, L3bpfSocket", "self.layer2num[layer] == num: dir = \"<->\" else: dir = \"", "IP_PROTOS if attr == \"services_udp\": from scapy.data import UDP_SERVICES return", "and later) \"\"\" try: import cryptography except ImportError: return False", "E501 checkIPinIP: if True, checks that IP-in-IP layers match. If", "isCryptographyValid() crypto_valid_recent = isCryptographyRecent() crypto_valid_advanced = crypto_valid_recent and isCryptographyAdvanced() fancy_prompt", "- max(len(i), 10) if len(r) > wlen: r = r[:wlen", "scapy.data import TCP_SERVICES return TCP_SERVICES return object.__getattr__(self, attr) if not", "this method is needed to force the dict to go", "2 prompt = Interceptor(\"prompt\", \">>> \", _prompt_changer) promisc = True", "noqa: E501 class Emphasize(ConfigFieldList): pass class Resolve(ConfigFieldList): pass class Num2Layer:", "from scapy.consts import DARWIN, WINDOWS, LINUX, BSD, SOLARIS from scapy.error", "if attr == \"ethertypes\": from scapy.data import ETHER_TYPES return ETHER_TYPES", "in keys: if i[0] != \"_\": r = repr(getattr(self, i))", "LayersList() commands = CommandsList() dot15d4_protocol = None # Used in", "available ! pcap won't be used\") Interceptor.set_from_hook(conf, \"use_pcap\", False) else:", "six.iteritems(self.num2layer): if layer in self.layer2num and self.layer2num[layer] == num: dir", "time.time() return ((k, v) for (k, v) in six.iteritems(self.__dict__) if", "unwanted packet to go out (ARP, DNS, ...) checkIPID: if", "used by contrib layers to store local configuration # noqa:", "Update globals _load(\"scapy.arch.pcapdnet\") return if conf.use_bpf: from scapy.arch.bpf.supersocket import L2bpfListenSocket,", "saved interactive_shell : can be \"ipython\", \"python\" or \"auto\". Default:", "where the session will be saved interactive_shell : can be", "if val: # Only if True for param in dependencies[attr]:", "below import scapy # noqa: F401 for lay in self.ldict:", "use_pypy = ReadOnlyAttribute(\"use_pypy\", isPyPy()) use_pcap = Interceptor( \"use_pcap\", os.getenv(\"SCAPY_USE_PCAPDNET\", \"\").lower().startswith(\"y\"),", "= universal_open dot = \"dot\" display = \"display\" tcpdump =", "return True def isPyPy(): \"\"\"Returns either scapy is running under", "try: sys.ps1 = conf.color_theme.prompt(conf.prompt) except Exception: pass try: apply_ipython_style(get_ipython()) except", "other): for co in other._caches_list: if hasattr(self, co.name): getattr(self, co.name).update(co)", "value) self._timetable[key] = other._timetable[key] def iteritems(self): if self.timeout is None:", "= 2 prompt = Interceptor(\"prompt\", \">>> \", _prompt_changer) promisc =", "citation # noqa: E501 iff : selects the default output", "from scapy.themes import NoTheme, apply_ipython_style ############ # Config # ############", "NAT stacks) # noqa: E501 checkIPinIP: if True, checks that", "= \".\" stats_classic_protocols = [] stats_dot11_protocols = [] temp_files =", "update(self, other): for key, value in six.iteritems(other): # We only", "program is published under a GPLv2 license \"\"\" Implementation of", "doc = l.__doc__.split(\"\\n\")[0] if l.__doc__ else \"--\" s.append(\"%-20s: %s\" %", "except Exception: pass try: apply_ipython_style(get_ipython()) except NameError: pass def _set_conf_sockets():", "= L2Socket conf.L2listen = L2ListenSocket # Update globals _load(\"scapy.arch.linux\") return", "an element from `other` either if it does # not", "object.__getattr__(self, attr) if not Conf.ipv6_enabled: log_scapy.warning(\"IPv6 support disabled in Python.", "import print_function import functools import os import re import time", "(%s)\" % (num, layer.__name__, layer._name))) lst.sort() return \"\\n\".join(y for x,", ": holds list of enum fields for which conversion to", "If False, do not check IP layers that encapsulates another", "def get(self, item, default=None): # overloading this method is needed", "is None: return six.iterkeys(self.__dict__) t0 = time.time() return (k for", "for ASN1 objects mib : holds MIB direct access dictionary", "doc.strip().split(\"\\n\")[0] if doc else lay)) return result class CommandsList(list): def", "ScapyInvalidPlatformException): raise def _loglevel_changer(attr, val): \"\"\"Handle a change of conf.logLevel\"\"\"", "fmt = \"%%-%is %%s\" % (mk + 1) for item", "keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys) for i in", "interactive = False interactive_shell = \"\" stealth = \"not implemented\"", "in other._caches_list: if hasattr(self, co.name): getattr(self, co.name).update(co) else: self.add_cache(co.copy()) def", "_prompt_changer(attr, val): \"\"\"Change the current prompt theme\"\"\" try: sys.ps1 =", "num def __getitem__(self, item): if isinstance(item, base_classes.Packet_metaclass): return self.layer2num[item] return", "disabled in Python. Cannot load Scapy IPv6 layers.\") # noqa:", ": default mode for sniff() filter : bpf filter added", "= L2ListenSocket # Update globals _load(\"scapy.arch.linux\") return if WINDOWS: from", "{} def flush(self): self.__init__(name=self.name, timeout=self.timeout) def __getitem__(self, item): if item", "time between warnings from the same place ASN1_default_codec: Codec used", "= re.match(version_regexp, module.__version__) if not version_tags: return False version_tags =", "the various use_* parameters \"\"\" from scapy.main import _load if", "os import re import time import socket import sys from", "= \"<->\" else: dir = \" ->\" lst.append((num, \"%#6x %s", "is None: return list(six.itervalues(self)) t0 = time.time() return [v for", "of Scapy. session : filename where the session will be", "for key, value in six.iteritems(other): # We only update an", "be used for any method relying on the cryptography library.", "which is deprecated version_regexp = r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags = re.match(version_regexp, module.__version__)", "universal_open psreader = universal_open svgreader = universal_open dot = \"dot\"", "register(self, layer): self.append(layer) if layer.__module__ not in self.ldict: self.ldict[layer.__module__] =", "See http://www.secdev.org/projects/scapy for more information # Copyright (C) <NAME> <<EMAIL>>", "self.ldict: doc = eval(lay).__doc__ result.append((lay, doc.strip().split(\"\\n\")[0] if doc else lay))", "if t0 - self._timetable[k] < self.timeout) # noqa: E501 def", "< self.timeout) # noqa: E501 def __iter__(self): return six.iterkeys(self.__dict__) def", "self.layers = set() @staticmethod def _is_field(f): return hasattr(f, \"owners\") def", "# noqa: E501 debug_tls:When 1, print some TLS session secrets", "\"owners\") def _recalc_layer_list(self): self.layers = {owner for f in self.fields", "packets. Defaults to 0.05s. \"\"\" version = ReadOnlyAttribute(\"version\", VERSION) session", "def __getattr__(self, attr): # Those are loaded on runtime to", "def __init__(self): self._caches_list = [] def add_cache(self, cache): self._caches_list.append(cache) setattr(self,", "support disabled in Python. Cannot load Scapy IPv6 layers.\") #", "[(k, v) for (k, v) in six.iteritems(self.__dict__) if t0 -", "items(self): if self.timeout is None: return dict.items(self) t0 = time.time()", "display = \"display\" tcpdump = \"tcpdump\" tcpreplay = \"tcpreplay\" hexedit", "lsc(): \"\"\"Displays Scapy's default commands\"\"\" print(repr(conf.commands)) class CacheInstance(dict, object): __slots__", "import log_scapy, warning, ScapyInvalidPlatformException from scapy.modules import six from scapy.themes", "default=None): return self[item] if item in self else default def", "to be looked for contribs : a dict which can", "and isCryptographyAdvanced() fancy_prompt = True auto_crop_tables = True recv_poll_rate =", "self.timeout] # noqa: E501 def values(self): if self.timeout is None:", "for x in self.fields)) # noqa: E501 class Emphasize(ConfigFieldList): pass", "= [] self.ldict[layer.__module__].append(layer) def layers(self): result = [] # This", "# Used in dot15d4.py logLevel = Interceptor(\"logLevel\", log_scapy.level, _loglevel_changer) checkIPID", "= time.time() dict.__setitem__(self, item, v) def update(self, other): for key,", "self.fields |= {f for f in flds if self._is_field(f)} self._recalc_layer_list()", "default commands\"\"\" print(repr(conf.commands)) class CacheInstance(dict, object): __slots__ = [\"timeout\", \"name\",", "_loglevel_changer) checkIPID = False checkIPsrc = True checkIPaddr = True", "lay)) return result class CommandsList(list): def __repr__(self): s = []", "= r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags = re.match(version_regexp, module.__version__) if not version_tags: return", "if self.timeout is None: return six.itervalues(self.__dict__) t0 = time.time() return", "place ASN1_default_codec: Codec used by default for ASN1 objects mib", "setattr(obj, self.intname, val) self.hook(self.name, val, *self.args, **self.kargs) def _readonly(name): default", "return from scapy.supersocket import L3RawSocket from scapy.layers.inet6 import L3RawSocket6 conf.L3socket", "is deprecated version_regexp = r'[a-z]?((?:\\d|\\.)+\\d+)(?:\\.dev[0-9]+)?' version_tags = re.match(version_regexp, module.__version__) if", "result = [] # This import may feel useless, but", "Num2Layer() L3socket = None L3socket6 = None L2socket = None", "noqa: E501 for m in [\"inet6\", \"dhcp6\"]: if m in", "and ack match the ones in ICMP citation # noqa:", "\"\"\"Change the current prompt theme\"\"\" try: sys.ps1 = conf.color_theme.prompt(conf.prompt) except", "it supports X25519, ChaCha20Poly1305 and such (v2.0 or later). \"\"\"", "use_bpf = Interceptor(\"use_bpf\", False, _socket_changer) use_npcap = False ipv6_enabled =", "will be saved interactive_shell : can be \"ipython\", \"python\" or", "[] stats_dot11_protocols = [] temp_files = [] netcache = NetCache()", "if 1, prevents any unwanted packet to go out (ARP,", "conversion to string should NOT be done # noqa: E501", "return getattr(obj, self.intname) @staticmethod def set_from_hook(obj, name, val): int_name =", "checkIPID = False checkIPsrc = True checkIPaddr = True checkIPinIP", "from scapy.main import _load if conf.use_bpf and not BSD: Interceptor.set_from_hook(conf,", "= { # Things that will be turned off \"use_pcap\":", "or conf.use_dnet: try: from scapy.arch.pcapdnet import L2pcapListenSocket, L2pcapSocket, \\ L3pcapSocket", "self.fields for owner in f.owners} def add(self, *flds): self.fields |=", "= time.time() return [v for (k, v) in six.iteritems(self.__dict__) if", "doesn't check that IPID matches between IP sent and ICMP", "3] + \"...\" s += \"%-10s = %s\\n\" % (i,", "from __future__ import print_function import functools import os import re", "if key not in self or self._timetable[key] < other._timetable[key]: dict.__setitem__(self," ]
[ "{}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}] ), ResponseTest(", "and \"version\" in rjs @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse?q=hello\", [{\"entities\": {},", "# unused in test app \"pipeline\": \"keyword\", \"path\": tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\":", "rjs @utilities.slowtest @pytest.inlineCallbacks def test_post_train_internal_error(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\":", "\"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?q=hello ńöñàśçií\", [{\"entities\": {}, \"confidence\": 1.0,", "'intent', '_text', 'confidence']) @utilities.slowtest @pytest.inlineCallbacks def test_post_train(app, rasa_default_train_data): response =", "in rjs assert \"default\" in rjs[\"available_projects\"] @pytest.inlineCallbacks def test_config(app): response", "rjs[0] for prop in ['entities', 'intent', '_text', 'confidence']) @pytest.mark.parametrize(\"response_test\", [", "), ResponseTest( \"http://dummy_uri/parse?q=\", [{\"entities\": {}, \"confidence\": 0.0, \"intent\": None, \"_text\":", "response = yield app.get(query) assert response.code == 200, \"Project should", "\"A project name to train must be specified\" assert \"error\"", "return json.loads(train_file.read()) @pytest.inlineCallbacks def test_root(app): response = yield app.get(\"http://dummy_uri/\") content", "in ['entities', 'intent', '_text', 'confidence']) @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse\", [{\"entities\":", "yield app.get(\"http://dummy_uri/config\") assert response.code == 200 @pytest.inlineCallbacks def test_version(app): response", "@pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse?q=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\",", "format is not valid\" assert \"error\" in rjs @pytest.inlineCallbacks def", "1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}] ), ResponseTest( \"http://dummy_uri/parse?q=\", [{\"entities\":", "\"greet\", \"_text\": \"hello ńöñàśçií\"}], payload={\"q\": \"hello ńöñàśçií\"} ), ]) @pytest.inlineCallbacks", "\"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response = app.post(train_u, data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response =", "response = yield app.get(query) assert response.code == 404, \"Project should", "from treq.testing import StubTreq from rasa_nlu.config import RasaNLUConfig import json", "prop in ['entities', 'intent', '_text', 'confidence']) @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse\",", "yield response.json() assert response.code == 200 and \"version\" in rjs", "\"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}] ), ResponseTest( \"http://dummy_uri/parse?q=\", [{\"entities\": {},", "-*- from __future__ import unicode_literals from __future__ import print_function from", "import io from tests import utilities from tests.utilities import ResponseTest", "\"./data/demo-restaurants.json\", \"emulate\": \"wit\", \"max_training_processes\": 1 } config = RasaNLUConfig(cmdline_args=_config) rasa", "\"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"q\": \"hello\"} ), ResponseTest(", "\"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"query\":", "ńöñàśçií\"}], payload={\"q\": \"hello ńöñàśçií\"} ), ]) @pytest.inlineCallbacks def test_post_parse(app, response_test):", "== 200 and \"version\" in rjs @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse?q=hello\",", "query = \"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response = yield app.get(query) assert response.code ==", "in rjs @pytest.inlineCallbacks def test_model_hot_reloading(app, rasa_default_train_data): query = \"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response", "absolute_import import tempfile import pytest import time from treq.testing import", "payload={\"query\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\":", "def test_root(app): response = yield app.get(\"http://dummy_uri/\") content = yield response.text()", "Klein application to mock Rasa HTTP server. :param component_builder: :return:", "200, \"Training should end successfully\" response = yield app.get(query) assert", "\"server_model_dirs\": {}, \"data\": \"./data/demo-restaurants.json\", \"emulate\": \"wit\", \"max_training_processes\": 1 } config", "@pytest.inlineCallbacks def test_status(app): response = yield app.get(\"http://dummy_uri/status\") rjs = yield", "= yield response.json() assert response.code == 200 assert len(rjs) ==", "@pytest.inlineCallbacks def test_post_train(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3)", "import utilities from tests.utilities import ResponseTest from rasa_nlu.server import RasaNLU", "} config = RasaNLUConfig(cmdline_args=_config) rasa = RasaNLU(config, testing=True) return StubTreq(rasa.app.resource())", "\"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?q=hello ńöñàśçií\", [{\"entities\": {}, \"confidence\":", "== 200, \"Project should now exist after it got trained\"", "all(prop in rjs[0] for prop in ['entities', 'intent', '_text', 'confidence'])", "assert response.code == 500, \"The training data format is not", "yield response rjs = yield response.json() assert response.code == 404,", "\"available_projects\" in rjs assert \"default\" in rjs[\"available_projects\"] @pytest.inlineCallbacks def test_config(app):", "== 1 assert all(prop in rjs[0] for prop in ['entities',", "@pytest.inlineCallbacks def test_get_parse(app, response_test): response = yield app.get(response_test.endpoint) rjs =", "tests.utilities import ResponseTest from rasa_nlu.server import RasaNLU @pytest.fixture(scope=\"module\") def app(tmpdir_factory):", "\"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}],", "ResponseTest( \"http://dummy_uri/parse?q=hello ńöñàśçií\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\":", "response.code == 404, \"A project name to train must be", "\"The training data format is not valid\" assert \"error\" in", "content_type='application/json') rjs = yield response.json() assert response.code == 200 assert", "tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config = { 'write': nlu_log_file, 'port': -1, # unused", "\"intent\": None, \"_text\": \"\"}] ), ]) @pytest.inlineCallbacks def test_get_parse(app, response_test):", "404, \"A project name to train must be specified\" assert", "= yield app.get(query) assert response.code == 200, \"Project should now", "\"path\": tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\": {}, \"data\": \"./data/demo-restaurants.json\", \"emulate\": \"wit\", \"max_training_processes\": 1", "HTTP server. :param component_builder: :return: \"\"\" _, nlu_log_file = tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\")", "\"max_training_processes\": 1 } config = RasaNLUConfig(cmdline_args=_config) rasa = RasaNLU(config, testing=True)", "rjs @pytest.inlineCallbacks def test_model_hot_reloading(app, rasa_default_train_data): query = \"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response =", "encoding='utf-8') as train_file: return json.loads(train_file.read()) @pytest.inlineCallbacks def test_root(app): response =", "RasaNLUConfig import json import io from tests import utilities from", "app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}), content_type='application/json') time.sleep(3) app.flush() response = yield response", "= yield response rjs = yield response.json() assert response.code ==", "= yield app.get(query) assert response.code == 404, \"Project should not", "should end successfully\" response = yield app.get(query) assert response.code ==", "server. :param component_builder: :return: \"\"\" _, nlu_log_file = tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config", "def app(tmpdir_factory): \"\"\" This fixture makes use of the IResource", "specified\" assert \"error\" in rjs @utilities.slowtest @pytest.inlineCallbacks def test_post_train_internal_error(app, rasa_default_train_data):", "data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}), content_type='application/json') time.sleep(3) app.flush() response = yield response rjs", ":return: \"\"\" _, nlu_log_file = tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config = { 'write':", "200 assert len(rjs) == 1 assert all(prop in rjs[0] for", "test_post_parse(app, response_test): response = yield app.post(response_test.endpoint, data=json.dumps(response_test.payload), content_type='application/json') rjs =", "-1, # unused in test app \"pipeline\": \"keyword\", \"path\": tmpdir_factory.mktemp(\"projects\").strpath,", "\"http://dummy_uri/parse?q=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ),", "response.code == 200, \"Training should end successfully\" response = yield", "\"http://dummy_uri/parse?query=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ),", "response = yield app.get(\"http://dummy_uri/\") content = yield response.text() assert response.code", "payload={\"q\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\":", "app.get(\"http://dummy_uri/status\") rjs = yield response.json() assert response.code == 200 and", "def test_model_hot_reloading(app, rasa_default_train_data): query = \"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response = yield app.get(query)", "\"greet\", \"_text\": \"hello ńöñàśçií\"}] ), ResponseTest( \"http://dummy_uri/parse?q=\", [{\"entities\": {}, \"confidence\":", "the Klein application to mock Rasa HTTP server. :param component_builder:", "not valid\" assert \"error\" in rjs @pytest.inlineCallbacks def test_model_hot_reloading(app, rasa_default_train_data):", "None, \"_text\": \"\"}] ), ]) @pytest.inlineCallbacks def test_get_parse(app, response_test): response", "response = app.post(train_u, data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response = yield", "['entities', 'intent', '_text', 'confidence']) @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {},", "response_test): response = yield app.get(response_test.endpoint) rjs = yield response.json() assert", "response = app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}), content_type='application/json') time.sleep(3) app.flush() response =", "1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?q=hello ńöñàśçií\", [{\"entities\":", "1 assert all(prop in rjs[0] for prop in ['entities', 'intent',", "config = RasaNLUConfig(cmdline_args=_config) rasa = RasaNLU(config, testing=True) return StubTreq(rasa.app.resource()) @pytest.fixture", "= app.post(train_u, data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response = yield response", "import StubTreq from rasa_nlu.config import RasaNLUConfig import json import io", "{}, \"data\": \"./data/demo-restaurants.json\", \"emulate\": \"wit\", \"max_training_processes\": 1 } config =", "of the IResource interface of the Klein application to mock", "rjs @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse?q=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\":", "@utilities.slowtest @pytest.inlineCallbacks def test_post_train_internal_error(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}),", "from __future__ import print_function from __future__ import division from __future__", "in ['entities', 'intent', '_text', 'confidence']) @utilities.slowtest @pytest.inlineCallbacks def test_post_train(app, rasa_default_train_data):", "exist yet\" train_u = \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response = app.post(train_u, data=json.dumps(rasa_default_train_data), content_type='application/json')", "assert response.code == 200 and content.startswith(\"hello\") @pytest.inlineCallbacks def test_status(app): response", "print_function from __future__ import division from __future__ import absolute_import import", "500, \"The training data format is not valid\" assert \"error\"", "== 200 @pytest.inlineCallbacks def test_version(app): response = yield app.get(\"http://dummy_uri/version\") rjs", "]) @pytest.inlineCallbacks def test_get_parse(app, response_test): response = yield app.get(response_test.endpoint) rjs", "utf-8 -*- from __future__ import unicode_literals from __future__ import print_function", "app.get(\"http://dummy_uri/version\") rjs = yield response.json() assert response.code == 200 and", "@pytest.fixture(scope=\"module\") def app(tmpdir_factory): \"\"\" This fixture makes use of the", "response_test): response = yield app.post(response_test.endpoint, data=json.dumps(response_test.payload), content_type='application/json') rjs = yield", "\"greet\", \"_text\": \"hello\"}], payload={\"q\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {},", "__future__ import division from __future__ import absolute_import import tempfile import", "rasa = RasaNLU(config, testing=True) return StubTreq(rasa.app.resource()) @pytest.fixture def rasa_default_train_data(): with", "\"_text\": \"\"}] ), ]) @pytest.inlineCallbacks def test_get_parse(app, response_test): response =", "== 200 and \"available_projects\" in rjs assert \"default\" in rjs[\"available_projects\"]", "'confidence']) @utilities.slowtest @pytest.inlineCallbacks def test_post_train(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data),", "\"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?query=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\",", "\"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?q=hello ńöñàśçií\",", "rasa_default_train_data): response = app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}), content_type='application/json') time.sleep(3) app.flush() response", "yield app.get(response_test.endpoint) rjs = yield response.json() assert response.code == 200", "app.post(train_u, data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response = yield response assert", "-*- coding: utf-8 -*- from __future__ import unicode_literals from __future__", "import unicode_literals from __future__ import print_function from __future__ import division", "test_root(app): response = yield app.get(\"http://dummy_uri/\") content = yield response.text() assert", "yield response.json() assert response.code == 200 and \"available_projects\" in rjs", "\"confidence\": 0.0, \"intent\": None, \"_text\": \"\"}] ), ]) @pytest.inlineCallbacks def", "0.0, \"intent\": None, \"_text\": \"\"}] ), ]) @pytest.inlineCallbacks def test_get_parse(app,", "app.get(\"http://dummy_uri/config\") assert response.code == 200 @pytest.inlineCallbacks def test_version(app): response =", "\"http://dummy_uri/parse?q=hello ńöñàśçií\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello", "assert \"error\" in rjs @pytest.inlineCallbacks def test_model_hot_reloading(app, rasa_default_train_data): query =", "\"Training should end successfully\" response = yield app.get(query) assert response.code", "yield app.get(query) assert response.code == 200, \"Project should now exist", "'intent', '_text', 'confidence']) @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\":", "rjs = yield response.json() assert response.code == 200 assert len(rjs)", "in rjs[0] for prop in ['entities', 'intent', '_text', 'confidence']) @utilities.slowtest", "= \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response = app.post(train_u, data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response", "app.get(query) assert response.code == 404, \"Project should not exist yet\"", "@pytest.inlineCallbacks def test_config(app): response = yield app.get(\"http://dummy_uri/config\") assert response.code ==", "json.loads(train_file.read()) @pytest.inlineCallbacks def test_root(app): response = yield app.get(\"http://dummy_uri/\") content =", "== 404, \"A project name to train must be specified\"", "200 and \"version\" in rjs @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse?q=hello\", [{\"entities\":", "app.flush() response = yield response assert response.code == 200, \"Training", "= yield response.json() assert response.code == 200 and \"available_projects\" in", "'port': -1, # unused in test app \"pipeline\": \"keyword\", \"path\":", "rasa_nlu.config import RasaNLUConfig import json import io from tests import", "nlu_log_file, 'port': -1, # unused in test app \"pipeline\": \"keyword\",", "must be specified\" assert \"error\" in rjs @utilities.slowtest @pytest.inlineCallbacks def", "\"error\" in rjs @pytest.inlineCallbacks def test_model_hot_reloading(app, rasa_default_train_data): query = \"http://dummy_uri/parse?q=hello&project=my_keyword_model\"", "'_text', 'confidence']) @utilities.slowtest @pytest.inlineCallbacks def test_post_train(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train\",", "rasa_default_train_data): response = app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response =", "test_model_hot_reloading(app, rasa_default_train_data): query = \"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response = yield app.get(query) assert", "time from treq.testing import StubTreq from rasa_nlu.config import RasaNLUConfig import", "), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\":", "= yield app.post(response_test.endpoint, data=json.dumps(response_test.payload), content_type='application/json') rjs = yield response.json() assert", "= yield response.text() assert response.code == 200 and content.startswith(\"hello\") @pytest.inlineCallbacks", "'write': nlu_log_file, 'port': -1, # unused in test app \"pipeline\":", "content_type='application/json') time.sleep(3) app.flush() response = yield response rjs = yield", "data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response = yield response rjs =", "RasaNLUConfig(cmdline_args=_config) rasa = RasaNLU(config, testing=True) return StubTreq(rasa.app.resource()) @pytest.fixture def rasa_default_train_data():", "unicode_literals from __future__ import print_function from __future__ import division from", "\"\"}] ), ]) @pytest.inlineCallbacks def test_get_parse(app, response_test): response = yield", "__future__ import print_function from __future__ import division from __future__ import", "@pytest.inlineCallbacks def test_post_train_internal_error(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}), content_type='application/json')", "response = yield app.get(\"http://dummy_uri/version\") rjs = yield response.json() assert response.code", "response.code == 200 and \"available_projects\" in rjs assert \"default\" in", "== 200 and content.startswith(\"hello\") @pytest.inlineCallbacks def test_status(app): response = yield", "import absolute_import import tempfile import pytest import time from treq.testing", ":param component_builder: :return: \"\"\" _, nlu_log_file = tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config =", "in rjs[0] for prop in ['entities', 'intent', '_text', 'confidence']) @pytest.mark.parametrize(\"response_test\",", "tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\": {}, \"data\": \"./data/demo-restaurants.json\", \"emulate\": \"wit\", \"max_training_processes\": 1 }", "data format is not valid\" assert \"error\" in rjs @pytest.inlineCallbacks", "rjs = yield response.json() assert response.code == 404, \"A project", "in test app \"pipeline\": \"keyword\", \"path\": tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\": {}, \"data\":", "\"error\" in rjs @utilities.slowtest @pytest.inlineCallbacks def test_post_train_internal_error(app, rasa_default_train_data): response =", "application to mock Rasa HTTP server. :param component_builder: :return: \"\"\"", "{}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"query\": \"hello\"} ),", "\"greet\", \"_text\": \"hello\"}], payload={\"query\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {},", "ńöñàśçií\"} ), ]) @pytest.inlineCallbacks def test_post_parse(app, response_test): response = yield", "test_config(app): response = yield app.get(\"http://dummy_uri/config\") assert response.code == 200 @pytest.inlineCallbacks", "response = yield app.get(\"http://dummy_uri/config\") assert response.code == 200 @pytest.inlineCallbacks def", "@pytest.inlineCallbacks def test_version(app): response = yield app.get(\"http://dummy_uri/version\") rjs = yield", "assert response.code == 200, \"Project should now exist after it", "treq.testing import StubTreq from rasa_nlu.config import RasaNLUConfig import json import", "yield app.get(\"http://dummy_uri/status\") rjs = yield response.json() assert response.code == 200", "\"version\" in rjs @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse?q=hello\", [{\"entities\": {}, \"confidence\":", "yet\" train_u = \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response = app.post(train_u, data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3)", "train must be specified\" assert \"error\" in rjs @utilities.slowtest @pytest.inlineCallbacks", "\"\"\" _, nlu_log_file = tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config = { 'write': nlu_log_file,", "is not valid\" assert \"error\" in rjs @pytest.inlineCallbacks def test_model_hot_reloading(app,", "the IResource interface of the Klein application to mock Rasa", "response = yield app.get(response_test.endpoint) rjs = yield response.json() assert response.code", "ResponseTest( \"http://dummy_uri/parse?query=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}]", "['entities', 'intent', '_text', 'confidence']) @utilities.slowtest @pytest.inlineCallbacks def test_post_train(app, rasa_default_train_data): response", "\"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}] ), ResponseTest( \"http://dummy_uri/parse?q=\",", "not exist yet\" train_u = \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response = app.post(train_u, data=json.dumps(rasa_default_train_data),", "@utilities.slowtest @pytest.inlineCallbacks def test_post_train(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data), content_type='application/json')", "\"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?q=hello ńöñàśçií\", [{\"entities\": {},", "\"http://dummy_uri/parse?q=\", [{\"entities\": {}, \"confidence\": 0.0, \"intent\": None, \"_text\": \"\"}] ),", "payload={\"q\": \"hello ńöñàśçií\"} ), ]) @pytest.inlineCallbacks def test_post_parse(app, response_test): response", "def test_post_train_internal_error(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}), content_type='application/json') time.sleep(3)", "response.code == 200 assert len(rjs) == 1 assert all(prop in", "response rjs = yield response.json() assert response.code == 404, \"A", "{ 'write': nlu_log_file, 'port': -1, # unused in test app", "app.get(query) assert response.code == 200, \"Project should now exist after", "utilities from tests.utilities import ResponseTest from rasa_nlu.server import RasaNLU @pytest.fixture(scope=\"module\")", "== 404, \"Project should not exist yet\" train_u = \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\"", "__future__ import absolute_import import tempfile import pytest import time from", "rjs = yield response.json() assert response.code == 200 and \"available_projects\"", "This fixture makes use of the IResource interface of the", "def test_get_parse(app, response_test): response = yield app.get(response_test.endpoint) rjs = yield", "to mock Rasa HTTP server. :param component_builder: :return: \"\"\" _,", "training data format is not valid\" assert \"error\" in rjs", "import print_function from __future__ import division from __future__ import absolute_import", "io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8') as train_file: return json.loads(train_file.read()) @pytest.inlineCallbacks def test_root(app): response", "), ]) @pytest.inlineCallbacks def test_post_parse(app, response_test): response = yield app.post(response_test.endpoint,", "response.code == 200, \"Project should now exist after it got", "), ResponseTest( \"http://dummy_uri/parse?query=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\":", "in rjs @utilities.slowtest @pytest.inlineCallbacks def test_post_train_internal_error(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train?project=test\",", "train_file: return json.loads(train_file.read()) @pytest.inlineCallbacks def test_root(app): response = yield app.get(\"http://dummy_uri/\")", "response.code == 200 @pytest.inlineCallbacks def test_version(app): response = yield app.get(\"http://dummy_uri/version\")", "in rjs @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse?q=hello\", [{\"entities\": {}, \"confidence\": 1.0,", "@pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\",", "ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello", "ńöñàśçií\"}] ), ResponseTest( \"http://dummy_uri/parse?q=\", [{\"entities\": {}, \"confidence\": 0.0, \"intent\": None,", "1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}], payload={\"q\": \"hello ńöñàśçií\"} ),", "yield app.get(\"http://dummy_uri/\") content = yield response.text() assert response.code == 200", "\"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"q\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\":", "valid\" assert \"error\" in rjs @pytest.inlineCallbacks def test_model_hot_reloading(app, rasa_default_train_data): query", "RasaNLU(config, testing=True) return StubTreq(rasa.app.resource()) @pytest.fixture def rasa_default_train_data(): with io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8')", "'confidence']) @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\":", "return StubTreq(rasa.app.resource()) @pytest.fixture def rasa_default_train_data(): with io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8') as train_file:", "def test_status(app): response = yield app.get(\"http://dummy_uri/status\") rjs = yield response.json()", "rjs assert \"default\" in rjs[\"available_projects\"] @pytest.inlineCallbacks def test_config(app): response =", "), ]) @pytest.inlineCallbacks def test_get_parse(app, response_test): response = yield app.get(response_test.endpoint)", "from tests import utilities from tests.utilities import ResponseTest from rasa_nlu.server", "[ ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\":", "'_text', 'confidence']) @pytest.mark.parametrize(\"response_test\", [ ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0,", "@pytest.fixture def rasa_default_train_data(): with io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8') as train_file: return json.loads(train_file.read())", "import json import io from tests import utilities from tests.utilities", "= yield response.json() assert response.code == 500, \"The training data", "import RasaNLUConfig import json import io from tests import utilities", "== 200, \"Training should end successfully\" response = yield app.get(query)", "assert response.code == 200 and \"version\" in rjs @pytest.mark.parametrize(\"response_test\", [", "assert response.code == 200, \"Training should end successfully\" response =", "app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response = yield response rjs", "yield response.json() assert response.code == 500, \"The training data format", "= \"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response = yield app.get(query) assert response.code == 404,", "\"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response = yield app.get(query) assert response.code == 404, \"Project", "response = app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response = yield", "app.get(\"http://dummy_uri/\") content = yield response.text() assert response.code == 200 and", "rasa_default_train_data): query = \"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response = yield app.get(query) assert response.code", "end successfully\" response = yield app.get(query) assert response.code == 200,", "rasa_default_train_data(): with io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8') as train_file: return json.loads(train_file.read()) @pytest.inlineCallbacks def", "ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}],", "= app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}), content_type='application/json') time.sleep(3) app.flush() response = yield", "from rasa_nlu.config import RasaNLUConfig import json import io from tests", "import time from treq.testing import StubTreq from rasa_nlu.config import RasaNLUConfig", "]) @pytest.inlineCallbacks def test_post_parse(app, response_test): response = yield app.post(response_test.endpoint, data=json.dumps(response_test.payload),", "\"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"query\": \"hello\"} ), ResponseTest(", "ńöñàśçií\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}]", "[{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}] ),", "= tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config = { 'write': nlu_log_file, 'port': -1, #", "from __future__ import absolute_import import tempfile import pytest import time", "len(rjs) == 1 assert all(prop in rjs[0] for prop in", "\"hello\"}], payload={\"q\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0,", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from", "nlu_log_file = tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config = { 'write': nlu_log_file, 'port': -1,", "200 and \"available_projects\" in rjs assert \"default\" in rjs[\"available_projects\"] @pytest.inlineCallbacks", "{}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?q=hello", "<filename>tests/base/test_server.py # -*- coding: utf-8 -*- from __future__ import unicode_literals", "testing=True) return StubTreq(rasa.app.resource()) @pytest.fixture def rasa_default_train_data(): with io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8') as", "yield app.post(response_test.endpoint, data=json.dumps(response_test.payload), content_type='application/json') rjs = yield response.json() assert response.code", "\"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\",", "_config = { 'write': nlu_log_file, 'port': -1, # unused in", "makes use of the IResource interface of the Klein application", "content = yield response.text() assert response.code == 200 and content.startswith(\"hello\")", "\"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?query=hello\", [{\"entities\": {}, \"confidence\": 1.0,", "200 and content.startswith(\"hello\") @pytest.inlineCallbacks def test_status(app): response = yield app.get(\"http://dummy_uri/status\")", "prop in ['entities', 'intent', '_text', 'confidence']) @utilities.slowtest @pytest.inlineCallbacks def test_post_train(app,", "yield response.json() assert response.code == 200 assert len(rjs) == 1", "should not exist yet\" train_u = \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response = app.post(train_u,", "ResponseTest( \"http://dummy_uri/parse?q=\", [{\"entities\": {}, \"confidence\": 0.0, \"intent\": None, \"_text\": \"\"}]", "\"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?query=hello\", [{\"entities\":", "rasa_nlu.server import RasaNLU @pytest.fixture(scope=\"module\") def app(tmpdir_factory): \"\"\" This fixture makes", "time.sleep(3) app.flush() response = yield response assert response.code == 200,", "response.json() assert response.code == 200 assert len(rjs) == 1 assert", "yield app.get(query) assert response.code == 404, \"Project should not exist", "component_builder: :return: \"\"\" _, nlu_log_file = tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config = {", "json import io from tests import utilities from tests.utilities import", "Rasa HTTP server. :param component_builder: :return: \"\"\" _, nlu_log_file =", "content.startswith(\"hello\") @pytest.inlineCallbacks def test_status(app): response = yield app.get(\"http://dummy_uri/status\") rjs =", "= yield app.get(response_test.endpoint) rjs = yield response.json() assert response.code ==", "import tempfile import pytest import time from treq.testing import StubTreq", "yield response.text() assert response.code == 200 and content.startswith(\"hello\") @pytest.inlineCallbacks def", "[{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"query\": \"hello\"}", "and content.startswith(\"hello\") @pytest.inlineCallbacks def test_status(app): response = yield app.get(\"http://dummy_uri/status\") rjs", "\"\"\" This fixture makes use of the IResource interface of", "{}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}], payload={\"q\": \"hello", "response = yield response assert response.code == 200, \"Training should", "response.text() assert response.code == 200 and content.startswith(\"hello\") @pytest.inlineCallbacks def test_status(app):", "def test_post_parse(app, response_test): response = yield app.post(response_test.endpoint, data=json.dumps(response_test.payload), content_type='application/json') rjs", "content_type='application/json') time.sleep(3) app.flush() response = yield response assert response.code ==", "), ResponseTest( \"http://dummy_uri/parse?q=hello ńöñàśçií\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\",", "for prop in ['entities', 'intent', '_text', 'confidence']) @utilities.slowtest @pytest.inlineCallbacks def", "def test_version(app): response = yield app.get(\"http://dummy_uri/version\") rjs = yield response.json()", "coding: utf-8 -*- from __future__ import unicode_literals from __future__ import", "rjs[0] for prop in ['entities', 'intent', '_text', 'confidence']) @utilities.slowtest @pytest.inlineCallbacks", "\"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?query=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\":", "response.code == 500, \"The training data format is not valid\"", "test_post_train(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response", "response = yield app.get(\"http://dummy_uri/status\") rjs = yield response.json() assert response.code", "\"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?q=hello ńöñàśçií\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\":", "rjs = yield response.json() assert response.code == 500, \"The training", "response.code == 200 and content.startswith(\"hello\") @pytest.inlineCallbacks def test_status(app): response =", "import ResponseTest from rasa_nlu.server import RasaNLU @pytest.fixture(scope=\"module\") def app(tmpdir_factory): \"\"\"", "= yield app.get(\"http://dummy_uri/version\") rjs = yield response.json() assert response.code ==", "tempfile import pytest import time from treq.testing import StubTreq from", "assert all(prop in rjs[0] for prop in ['entities', 'intent', '_text',", "= yield app.get(\"http://dummy_uri/\") content = yield response.text() assert response.code ==", "[ ResponseTest( \"http://dummy_uri/parse?q=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\":", "404, \"Project should not exist yet\" train_u = \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response", "yield response assert response.code == 200, \"Training should end successfully\"", "response.json() assert response.code == 200 and \"available_projects\" in rjs assert", "response assert response.code == 200, \"Training should end successfully\" response", "import division from __future__ import absolute_import import tempfile import pytest", "interface of the Klein application to mock Rasa HTTP server.", "1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?query=hello\", [{\"entities\": {},", "assert \"error\" in rjs @utilities.slowtest @pytest.inlineCallbacks def test_post_train_internal_error(app, rasa_default_train_data): response", "= app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response = yield response", "to train must be specified\" assert \"error\" in rjs @utilities.slowtest", "1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"query\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\",", "@pytest.inlineCallbacks def test_post_parse(app, response_test): response = yield app.post(response_test.endpoint, data=json.dumps(response_test.payload), content_type='application/json')", "StubTreq(rasa.app.resource()) @pytest.fixture def rasa_default_train_data(): with io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8') as train_file: return", "tests import utilities from tests.utilities import ResponseTest from rasa_nlu.server import", "test_get_parse(app, response_test): response = yield app.get(response_test.endpoint) rjs = yield response.json()", "def test_config(app): response = yield app.get(\"http://dummy_uri/config\") assert response.code == 200", "{}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?query=hello\",", "assert len(rjs) == 1 assert all(prop in rjs[0] for prop", "\"_text\": \"hello ńöñàśçií\"}] ), ResponseTest( \"http://dummy_uri/parse?q=\", [{\"entities\": {}, \"confidence\": 0.0,", "= yield response.json() assert response.code == 200 and \"version\" in", "= RasaNLU(config, testing=True) return StubTreq(rasa.app.resource()) @pytest.fixture def rasa_default_train_data(): with io.open('data/examples/rasa/demo-rasa.json',", "\"hello ńöñàśçií\"}] ), ResponseTest( \"http://dummy_uri/parse?q=\", [{\"entities\": {}, \"confidence\": 0.0, \"intent\":", "= yield response assert response.code == 200, \"Training should end", "ResponseTest( \"http://dummy_uri/parse?q=hello\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}]", "import pytest import time from treq.testing import StubTreq from rasa_nlu.config", "IResource interface of the Klein application to mock Rasa HTTP", "{}, \"confidence\": 0.0, \"intent\": None, \"_text\": \"\"}] ), ]) @pytest.inlineCallbacks", "= { 'write': nlu_log_file, 'port': -1, # unused in test", "assert response.code == 200 @pytest.inlineCallbacks def test_version(app): response = yield", "unused in test app \"pipeline\": \"keyword\", \"path\": tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\": {},", "response.json() assert response.code == 200 and \"version\" in rjs @pytest.mark.parametrize(\"response_test\",", "\"Project should not exist yet\" train_u = \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response =", "StubTreq from rasa_nlu.config import RasaNLUConfig import json import io from", "\"wit\", \"max_training_processes\": 1 } config = RasaNLUConfig(cmdline_args=_config) rasa = RasaNLU(config,", "1 } config = RasaNLUConfig(cmdline_args=_config) rasa = RasaNLU(config, testing=True) return", "data=json.dumps(response_test.payload), content_type='application/json') rjs = yield response.json() assert response.code == 200", "from tests.utilities import ResponseTest from rasa_nlu.server import RasaNLU @pytest.fixture(scope=\"module\") def", "test_post_train_internal_error(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train?project=test\", data=json.dumps({\"data\": \"dummy_data_for_triggering_an_error\"}), content_type='application/json') time.sleep(3) app.flush()", "[{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"q\": \"hello\"}", "\"keyword\", \"path\": tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\": {}, \"data\": \"./data/demo-restaurants.json\", \"emulate\": \"wit\", \"max_training_processes\":", "app.get(response_test.endpoint) rjs = yield response.json() assert response.code == 200 assert", "as train_file: return json.loads(train_file.read()) @pytest.inlineCallbacks def test_root(app): response = yield", "response.json() assert response.code == 404, \"A project name to train", "from __future__ import division from __future__ import absolute_import import tempfile", "assert response.code == 200 and \"available_projects\" in rjs assert \"default\"", "rjs = yield response.json() assert response.code == 200 and \"version\"", "def test_post_train(app, rasa_default_train_data): response = app.post(\"http://dummy_uri/train\", data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush()", "for prop in ['entities', 'intent', '_text', 'confidence']) @pytest.mark.parametrize(\"response_test\", [ ResponseTest(", "[{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}], payload={\"q\":", "with io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8') as train_file: return json.loads(train_file.read()) @pytest.inlineCallbacks def test_root(app):", "\"emulate\": \"wit\", \"max_training_processes\": 1 } config = RasaNLUConfig(cmdline_args=_config) rasa =", "\"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"q\":", "import RasaNLU @pytest.fixture(scope=\"module\") def app(tmpdir_factory): \"\"\" This fixture makes use", "\"_text\": \"hello\"}], payload={\"query\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\":", "assert response.code == 404, \"Project should not exist yet\" train_u", "\"pipeline\": \"keyword\", \"path\": tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\": {}, \"data\": \"./data/demo-restaurants.json\", \"emulate\": \"wit\",", "app \"pipeline\": \"keyword\", \"path\": tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\": {}, \"data\": \"./data/demo-restaurants.json\", \"emulate\":", "RasaNLU @pytest.fixture(scope=\"module\") def app(tmpdir_factory): \"\"\" This fixture makes use of", "name to train must be specified\" assert \"error\" in rjs", "1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"q\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\",", "\"hello ńöñàśçií\"} ), ]) @pytest.inlineCallbacks def test_post_parse(app, response_test): response =", "response = yield app.post(response_test.endpoint, data=json.dumps(response_test.payload), content_type='application/json') rjs = yield response.json()", "\"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}], payload={\"q\": \"hello ńöñàśçií\"} ), ])", "\"hello\"}], payload={\"query\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\": 1.0,", "_, nlu_log_file = tempfile.mkstemp(suffix=\"_rasa_nlu_logs.json\") _config = { 'write': nlu_log_file, 'port':", "app.flush() response = yield response rjs = yield response.json() assert", "== 200 assert len(rjs) == 1 assert all(prop in rjs[0]", "\"_text\": \"hello\"}], payload={\"q\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\": {}, \"confidence\":", "yield response rjs = yield response.json() assert response.code == 500,", "== 500, \"The training data format is not valid\" assert", "test app \"pipeline\": \"keyword\", \"path\": tmpdir_factory.mktemp(\"projects\").strpath, \"server_model_dirs\": {}, \"data\": \"./data/demo-restaurants.json\",", "= RasaNLUConfig(cmdline_args=_config) rasa = RasaNLU(config, testing=True) return StubTreq(rasa.app.resource()) @pytest.fixture def", "project name to train must be specified\" assert \"error\" in", "\"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest( \"http://dummy_uri/parse?query=hello\", [{\"entities\": {}, \"confidence\":", "division from __future__ import absolute_import import tempfile import pytest import", "response.code == 404, \"Project should not exist yet\" train_u =", "time.sleep(3) app.flush() response = yield response rjs = yield response.json()", "in rjs[\"available_projects\"] @pytest.inlineCallbacks def test_config(app): response = yield app.get(\"http://dummy_uri/config\") assert", "train_u = \"http://dummy_uri/train?project=my_keyword_model&pipeline=keyword\" response = app.post(train_u, data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush()", "pytest import time from treq.testing import StubTreq from rasa_nlu.config import", "io from tests import utilities from tests.utilities import ResponseTest from", "test_status(app): response = yield app.get(\"http://dummy_uri/status\") rjs = yield response.json() assert", "assert response.code == 404, \"A project name to train must", "= yield app.get(\"http://dummy_uri/status\") rjs = yield response.json() assert response.code ==", "from __future__ import unicode_literals from __future__ import print_function from __future__", "fixture makes use of the IResource interface of the Klein", "yield response.json() assert response.code == 404, \"A project name to", "assert \"default\" in rjs[\"available_projects\"] @pytest.inlineCallbacks def test_config(app): response = yield", "= yield response.json() assert response.code == 404, \"A project name", "\"dummy_data_for_triggering_an_error\"}), content_type='application/json') time.sleep(3) app.flush() response = yield response rjs =", "response rjs = yield response.json() assert response.code == 500, \"The", "mock Rasa HTTP server. :param component_builder: :return: \"\"\" _, nlu_log_file", "rjs[\"available_projects\"] @pytest.inlineCallbacks def test_config(app): response = yield app.get(\"http://dummy_uri/config\") assert response.code", "\"default\" in rjs[\"available_projects\"] @pytest.inlineCallbacks def test_config(app): response = yield app.get(\"http://dummy_uri/config\")", "app(tmpdir_factory): \"\"\" This fixture makes use of the IResource interface", "\"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"query\": \"hello\"} ), ResponseTest( \"http://dummy_uri/parse\", [{\"entities\":", "\"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello ńöñàśçií\"}], payload={\"q\": \"hello ńöñàśçií\"}", "__future__ import unicode_literals from __future__ import print_function from __future__ import", "ResponseTest from rasa_nlu.server import RasaNLU @pytest.fixture(scope=\"module\") def app(tmpdir_factory): \"\"\" This", "test_version(app): response = yield app.get(\"http://dummy_uri/version\") rjs = yield response.json() assert", "[{\"entities\": {}, \"confidence\": 0.0, \"intent\": None, \"_text\": \"\"}] ), ])", "of the Klein application to mock Rasa HTTP server. :param", "yield app.get(\"http://dummy_uri/version\") rjs = yield response.json() assert response.code == 200", "\"data\": \"./data/demo-restaurants.json\", \"emulate\": \"wit\", \"max_training_processes\": 1 } config = RasaNLUConfig(cmdline_args=_config)", "data=json.dumps(rasa_default_train_data), content_type='application/json') time.sleep(3) app.flush() response = yield response assert response.code", "and \"available_projects\" in rjs assert \"default\" in rjs[\"available_projects\"] @pytest.inlineCallbacks def", "app.post(response_test.endpoint, data=json.dumps(response_test.payload), content_type='application/json') rjs = yield response.json() assert response.code ==", "be specified\" assert \"error\" in rjs @utilities.slowtest @pytest.inlineCallbacks def test_post_train_internal_error(app,", "response.code == 200 and \"version\" in rjs @pytest.mark.parametrize(\"response_test\", [ ResponseTest(", "assert response.code == 200 assert len(rjs) == 1 assert all(prop", "successfully\" response = yield app.get(query) assert response.code == 200, \"Project", "200 @pytest.inlineCallbacks def test_version(app): response = yield app.get(\"http://dummy_uri/version\") rjs =", "[{\"entities\": {}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}] ), ResponseTest(", "\"_text\": \"hello ńöñàśçií\"}], payload={\"q\": \"hello ńöñàśçií\"} ), ]) @pytest.inlineCallbacks def", "response.json() assert response.code == 500, \"The training data format is", "use of the IResource interface of the Klein application to", "\"hello ńöñàśçií\"}], payload={\"q\": \"hello ńöñàśçií\"} ), ]) @pytest.inlineCallbacks def test_post_parse(app,", "@pytest.inlineCallbacks def test_model_hot_reloading(app, rasa_default_train_data): query = \"http://dummy_uri/parse?q=hello&project=my_keyword_model\" response = yield", "def rasa_default_train_data(): with io.open('data/examples/rasa/demo-rasa.json', encoding='utf-8') as train_file: return json.loads(train_file.read()) @pytest.inlineCallbacks", "response = yield response rjs = yield response.json() assert response.code", "from rasa_nlu.server import RasaNLU @pytest.fixture(scope=\"module\") def app(tmpdir_factory): \"\"\" This fixture", "= yield app.get(\"http://dummy_uri/config\") assert response.code == 200 @pytest.inlineCallbacks def test_version(app):", "{}, \"confidence\": 1.0, \"intent\": \"greet\", \"_text\": \"hello\"}], payload={\"q\": \"hello\"} ),", "@pytest.inlineCallbacks def test_root(app): response = yield app.get(\"http://dummy_uri/\") content = yield" ]
[ "self.notify_release_stages = None self.auto_notify = True self.send_code = True self.send_environment", "property is ' + 'deprecated in favor of referencing properties", "not None: self.project_root = project_root if proxy_host is not None:", "should be sent asynchronously \"\"\" return self._asynchronous @asynchronous.setter # type:", "self.notify_release_stages is None or \\ (isinstance(self.notify_release_stages, (tuple, list)) and self.release_stage", "@property def delivery(self): \"\"\" Transport mechanism used to make API", "uncaught exceptions should be automatically captured and reported \"\"\" return", "be sent with events \"\"\" return self._send_code @send_code.setter # type:", "notify_release_stages is not None: self.notify_release_stages = notify_release_stages if params_filters is", "self.app_type = None self.app_version = None self.params_filters = [\"password\", \"password_confirmation\",", "not None: self.app_version = app_version if asynchronous is not None:", "def app_type(self): \"\"\" Category for the current application or task", "= notify_release_stages if params_filters is not None: self.params_filters = params_filters", "= ContextVar('bugsnag-request', default=None) # type: ignore except ImportError: from bugsnag.utils", "= ignore_classes if lib_root is not None: self.lib_root = lib_root", "self.asynchronous = True self.delivery = create_default_delivery() self.lib_root = sysconfig.get_path('purelib') self.project_root", "except ImportError: from bugsnag.utils import ThreadContextVar _request_info = ThreadContextVar('bugsnag-request', default=None)", "os.getcwd() self.app_type = None self.app_version = None self.params_filters = [\"password\",", "are ignored by default. \"\"\" return self._ignore_classes @ignore_classes.setter # type:", "being sent in events. By default the following keys are", "def session_endpoint(self): \"\"\" Sessions API endpoint. Set this property if", "return self._send_environment @send_environment.setter # type: ignore @validate_bool_setter def send_environment(self, value:", "code. Traceback file paths which contain this prefix are considered", "future release.') warnings.warn(message.format(type(value).__name__), RuntimeWarning) @property def endpoint(self): \"\"\" Event API", "events \"\"\" return self._send_code @send_code.setter # type: ignore @validate_bool_setter def", "are delivered. \"\"\" return self._notify_release_stages @notify_release_stages.setter # type: ignore @validate_iterable_setter", "traceback lines. \"\"\" return self._project_root @project_root.setter # type: ignore @validate_str_setter", "None: self.send_code = send_code if send_environment is not None: self.send_environment", "self.ignore_classes is not None and \\ fully_qualified_class_name(exception) in self.ignore_classes class", "= value @property def release_stage(self): \"\"\" The development phase of", "got ' + '{0}. This will be an error in", "def endpoint(self): \"\"\" Event API endpoint. Set this property if", "ContextVar('bugsnag-request', default=None) # type: ignore except ImportError: from bugsnag.utils import", "occur in production vs development or staging environments. \"\"\" return", "filters applied to event metadata to prevent the values from", "def should_ignore(self, exception: BaseException) -> bool: return self.ignore_classes is not", "be automatically detected and delivered from web request integrations \"\"\"", "\"\"\" def __init__(self): self.api_key = os.environ.get('BUGSNAG_API_KEY', None) self.release_stage = os.environ.get(\"BUGSNAG_RELEASE_STAGE\",", "@auto_capture_sessions.setter # type: ignore @validate_bool_setter def auto_capture_sessions(self, value: bool): self._auto_capture_sessions", "ThreadContextVar('bugsnag-request', default=None) # type: ignore # noqa: E501 __all__ =", "default this value is None and all events and sessions", "'{0}. This will be an error in a future release.')", "path to the Python library. Any traceback frame which contains", "self.grouping_hash = None self.user = {} self.metadata = {} #", "\"\"\" @classmethod def get_instance(cls): \"\"\" Get this thread's instance of", "getattr(self, name) def configure(self, **options): \"\"\" Set one or more", "prefix are considered a part of the project. This prefix", "current application \"\"\" return self._app_version @app_version.setter # type: ignore @validate_str_setter", "_request_info.set(instance) # type: ignore return instance @classmethod def clear(cls): \"\"\"", "app_version is not None: self.app_version = app_version if asynchronous is", "RuntimeWarning) @property def endpoint(self): \"\"\" Event API endpoint. Set this", "value: str): self._project_root = value @property def proxy_host(self): \"\"\" The", "\"production\") self.notify_release_stages = None self.auto_notify = True self.send_code = True", "in a future release.') warnings.warn(message.format(type(value).__name__), RuntimeWarning) @property def endpoint(self): \"\"\"", "@property def session_endpoint(self): \"\"\" Sessions API endpoint. Set this property", "= MiddlewareStack() self.internal_middleware = MiddlewareStack() self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware) self.proxy_host = None", "asynchronous(self): \"\"\" If API requests should be sent asynchronously \"\"\"", "= socket.gethostname() else: self.hostname = None self.runtime_versions = {\"python\": platform.python_version()}", "sent. \"\"\" return self._delivery @delivery.setter # type: ignore def delivery(self,", "return self._session_endpoint @session_endpoint.setter # type: ignore @validate_required_str_setter def session_endpoint(self, value:", "prefix is also stripped to make file names easier to", "@property def api_key(self): \"\"\" Unique application identifier \"\"\" return self._api_key", "property if using Bugsnag On-Premise. >>> config = Configuration() >>>", "settings. \"\"\" @classmethod def get_instance(cls): \"\"\" Get this thread's instance", "= None self.auto_notify = True self.send_code = True self.send_environment =", "the current application \"\"\" return self._app_version @app_version.setter # type: ignore", "is not None: self.hostname = hostname if ignore_classes is not", "def proxy_host(self): \"\"\" The host name of the proxy to", "not None: self.send_code = send_code if send_environment is not None:", "self.notify_release_stages) def should_ignore(self, exception: BaseException) -> bool: return self.ignore_classes is", "= None self.app_version = None self.params_filters = [\"password\", \"password_confirmation\", \"cookie\",", "password * password_confirmation \"\"\" return self._params_filters @params_filters.setter # type: ignore", "If the source code lines immediately surrounding traceback locations should", "sessions should be automatically detected and delivered from web request", "= value @property def proxy_host(self): \"\"\" The host name of", "cookie * password * password_confirmation \"\"\" return self._params_filters @params_filters.setter #", "implement Delivery interface, got ' + '{0}. This will be", "message = ('delivery should implement Delivery interface, got ' +", "= RequestConfiguration() _request_info.set(instance) # type: ignore return instance @classmethod def", "The host name of the application server. This value is", "\"\"\" return getattr(self, name) def configure(self, **options): \"\"\" Set one", "False self.asynchronous = True self.delivery = create_default_delivery() self.lib_root = sysconfig.get_path('purelib')", "def app_version(self, value: str): self._app_version = value @property def asynchronous(self):", "def get_instance(cls): \"\"\" Get this thread's instance of the RequestConfiguration.", "ignore_classes is not None: self.ignore_classes = ignore_classes if lib_root is", "self._app_type = value @property def app_version(self): \"\"\" Release version of", "self._auto_capture_sessions = value @property def auto_notify(self): \"\"\" If uncaught exceptions", "platform import socket import sysconfig from typing import List, Any,", "\"django.http.response.Http404\", ] self.endpoint = DEFAULT_ENDPOINT self.session_endpoint = DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions =", "(fully_qualified_class_name, validate_str_setter, validate_bool_setter, validate_iterable_setter, validate_required_str_setter) from bugsnag.delivery import (create_default_delivery, DEFAULT_ENDPOINT,", "def lib_root(self, value: str): self._lib_root = value @property def notify_release_stages(self):", "in self.ignore_classes class RequestConfiguration: \"\"\" Per-request Bugsnag configuration settings. \"\"\"", "= value @property def session_endpoint(self): \"\"\" Sessions API endpoint. Set", "@proxy_host.setter # type: ignore @validate_str_setter def proxy_host(self, value: str): self._proxy_host", "get(self, name): \"\"\" Get a single configuration option \"\"\" warnings.warn('Using", "prefix is considered out-of-project. The prefix is also stripped to", "On-Premise. >>> config = Configuration() >>> config.endpoint = 'https://notify.bugsnag.example.co' \"\"\"", "self.auto_capture_sessions = auto_capture_sessions if delivery is not None: self.delivery =", "library. Any traceback frame which contains lib_root as a prefix", "api_key(self): \"\"\" Unique application identifier \"\"\" return self._api_key @api_key.setter #", "= hostname if ignore_classes is not None: self.ignore_classes = ignore_classes", "directory containing the application source code. Traceback file paths which", "values which are permitted to capture and send events and", "release_stage(self): \"\"\" The development phase of the deployed application. This", "return self._lib_root @lib_root.setter # type: ignore @validate_str_setter def lib_root(self, value:", "is not None: self.endpoint = endpoint if hostname is not", "= Configuration() >>> config.session_endpoint = 'https://sessions.bugsnag.example.co' \"\"\" return self._session_endpoint @session_endpoint.setter", "which contains lib_root as a prefix is considered out-of-project. The", "return self._auto_notify @auto_notify.setter # type: ignore @validate_bool_setter def auto_notify(self, value:", "\"\"\" If API requests should be sent asynchronously \"\"\" return", "def send_environment(self): \"\"\" If the request environment should be automatically", "value: bool): self._auto_capture_sessions = value @property def auto_notify(self): \"\"\" If", "= value @property def params_filters(self): \"\"\" A list of filters", "\"\"\" If uncaught exceptions should be automatically captured and reported", "this property if using Bugsnag On-Premise. >>> config = Configuration()", "asynchronous is not None: self.asynchronous = asynchronous if auto_notify is", "type: ignore @validate_str_setter def app_type(self, value: str): self._app_type = value", "traceback_exclude_modules return self def get(self, name): \"\"\" Get a single", "= auto_capture_sessions if delivery is not None: self.delivery = delivery", "Union import warnings from bugsnag.sessiontracker import SessionMiddleware from bugsnag.middleware import", "self.internal_middleware.append(SessionMiddleware) self.proxy_host = None if not os.getenv(\"DYNO\"): self.hostname = socket.gethostname()", "self.proxy_host = proxy_host if release_stage is not None: self.release_stage =", "identifier \"\"\" return self._api_key @api_key.setter # type: ignore @validate_required_str_setter def", "option \"\"\" warnings.warn('Using get() to retrieve a Configuration property is", "The prefix is also stripped to make file names easier", "= value def should_notify(self) -> bool: return self.notify_release_stages is None", "single configuration option \"\"\" return getattr(self, name) def configure(self, **options):", "a single configuration option \"\"\" warnings.warn('Using get() to retrieve a", "is not None: self.auto_capture_sessions = auto_capture_sessions if delivery is not", "' + 'deprecated in favor of referencing properties directly', DeprecationWarning)", "def project_root(self): \"\"\" The working directory containing the application source", "def release_stage(self, value: str): self._release_stage = value @property def send_code(self):", "self.endpoint = DEFAULT_ENDPOINT self.session_endpoint = DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions = True self.traceback_exclude_modules", "SessionMiddleware from bugsnag.middleware import DefaultMiddleware, MiddlewareStack from bugsnag.utils import (fully_qualified_class_name,", "type: ignore @validate_bool_setter def send_code(self, value: bool): self._send_code = value", "Clear this thread's instance of the RequestConfiguration. \"\"\" _request_info.set(None) def", "\"\"\" The host name of the application server. This value", "_request_info = ContextVar('bugsnag-request', default=None) # type: ignore except ImportError: from", "and delivered from web request integrations \"\"\" return self._auto_capture_sessions @auto_capture_sessions.setter", "be automatically collected and attached to events \"\"\" return self._send_environment", "MiddlewareStack from bugsnag.utils import (fully_qualified_class_name, validate_str_setter, validate_bool_setter, validate_iterable_setter, validate_required_str_setter) from", "Category for the current application or task \"\"\" return self._app_type", "endpoint if hostname is not None: self.hostname = hostname if", "= ('Configuration', 'RequestConfiguration') class Configuration: \"\"\" Global app-level Bugsnag configuration", "contextvars import ContextVar _request_info = ContextVar('bugsnag-request', default=None) # type: ignore", "os.getenv(\"DYNO\"): self.hostname = socket.gethostname() else: self.hostname = None self.runtime_versions =", "@classmethod def get_instance(cls): \"\"\" Get this thread's instance of the", "= value @property def auto_notify(self): \"\"\" If uncaught exceptions should", "def ignore_classes(self, value: Union[List[str], Tuple[str]]): self._ignore_classes = value @property def", "List[str]): self._traceback_exclude_modules = value def should_notify(self) -> bool: return self.notify_release_stages", "None: self.params_filters = params_filters if project_root is not None: self.project_root", "class names which should be ignored when capturing uncaught exceptions", "request integrations \"\"\" return self._auto_capture_sessions @auto_capture_sessions.setter # type: ignore @validate_bool_setter", "to deliver requests, if any \"\"\" return self._proxy_host @proxy_host.setter #", "import socket import sysconfig from typing import List, Any, Tuple,", "to capture and send events and sessions. By default this", "= session_endpoint if traceback_exclude_modules is not None: self.traceback_exclude_modules = traceback_exclude_modules", "\"\"\" Category for the current application or task \"\"\" return", "not None: self.endpoint = endpoint if hostname is not None:", "is also stripped to make file names easier to read.", "{} self.environment_data = {} self.session_data = {} def get(self, name)", "is not None and \\ fully_qualified_class_name(exception) in self.ignore_classes class RequestConfiguration:", "return self._ignore_classes @ignore_classes.setter # type: ignore @validate_iterable_setter def ignore_classes(self, value:", "None self.user = {} self.metadata = {} # legacy fields", "session_endpoint if traceback_exclude_modules is not None: self.traceback_exclude_modules = traceback_exclude_modules return", "\"\"\" Fully qualified class names which should be ignored when", "referencing properties directly', DeprecationWarning) return getattr(self, name) @property def api_key(self):", "self._lib_root = value @property def notify_release_stages(self): \"\"\" A list of", "str): self._endpoint = value @property def hostname(self): \"\"\" The host", "str): self._app_type = value @property def app_version(self): \"\"\" Release version", "of the proxy to use to deliver requests, if any", "or staging environments. \"\"\" return self._release_stage @release_stage.setter # type: ignore", "= ('delivery should implement Delivery interface, got ' + '{0}.", "metadata. \"\"\" return self._hostname @hostname.setter # type: ignore @validate_str_setter def", "be ignored when capturing uncaught exceptions and other events. KeyboardInterrupt", "is not None: self.release_stage = release_stage if send_code is not", "= None self.grouping_hash = None self.user = {} self.metadata =", "bugsnag.delivery import (create_default_delivery, DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT) from bugsnag.uwsgi import warn_if_running_uwsgi_without_threads try:", "should be automatically collected and attached to events \"\"\" return", "option \"\"\" return getattr(self, name) def configure(self, **options): \"\"\" Set", "surrounding traceback locations should be sent with events \"\"\" return", "value) return self @property def meta_data(self) -> Any: warnings.warn('RequestConfiguration.meta_data has", "self.runtime_versions = {\"python\": platform.python_version()} def configure(self, api_key=None, app_type=None, app_version=None, asynchronous=None,", "other events. KeyboardInterrupt and Http404 exceptions are ignored by default.", "-> Any: warnings.warn('RequestConfiguration.meta_data has been renamed to ' + '\"metadata\"',", "interface, got ' + '{0}. This will be an error", "value @property def auto_notify(self): \"\"\" If uncaught exceptions should be", "is not None: self.traceback_exclude_modules = traceback_exclude_modules return self def get(self,", "project_root(self): \"\"\" The working directory containing the application source code.", "are filtered: * authorization * cookie * password * password_confirmation", "which should be stripped from event tracebacks entirely \"\"\" return", "also stripped to increase file name readability in traceback lines.", "self._notify_release_stages @notify_release_stages.setter # type: ignore @validate_iterable_setter def notify_release_stages(self, value: List[str]):", "version of the current application \"\"\" return self._app_version @app_version.setter #", "<filename>bugsnag/configuration.py<gh_stars>0 import os import platform import socket import sysconfig from", "is not None: self.ignore_classes = ignore_classes if lib_root is not", "str): self._session_endpoint = value @property def traceback_exclude_modules(self): \"\"\" Modules which", "= None self.extra_data = {} self.request_data = {} self.environment_data =", "str): self._api_key = value @property def app_type(self): \"\"\" Category for", "= 'https://sessions.bugsnag.example.co' \"\"\" return self._session_endpoint @session_endpoint.setter # type: ignore @validate_required_str_setter", "= value @property def send_environment(self): \"\"\" If the request environment", "bool): self._auto_notify = value @property def delivery(self): \"\"\" Transport mechanism", "auto_notify if auto_capture_sessions is not None: self.auto_capture_sessions = auto_capture_sessions if", "directly', DeprecationWarning) return getattr(self, name) @property def api_key(self): \"\"\" Unique", "the request environment should be automatically collected and attached to", "app_type if app_version is not None: self.app_version = app_version if", "type: ignore @validate_bool_setter def send_environment(self, value: bool): self._send_environment = value", "A list of release_stage values which are permitted to capture", "if lib_root is not None: self.lib_root = lib_root if notify_release_stages", "value: bool): self._asynchronous = value if value: warn_if_running_uwsgi_without_threads() @property def", "= value @property def app_type(self): \"\"\" Category for the current", "captured and reported \"\"\" return self._auto_notify @auto_notify.setter # type: ignore", "@release_stage.setter # type: ignore @validate_str_setter def release_stage(self, value: str): self._release_stage", "value: Union[List[str], Tuple[str]]): self._ignore_classes = value @property def lib_root(self): \"\"\"", "def params_filters(self, value: List[str]): self._params_filters = value @property def project_root(self):", "or task \"\"\" return self._app_type @app_type.setter # type: ignore @validate_str_setter", "the values from being sent in events. By default the", "@validate_str_setter def app_type(self, value: str): self._app_type = value @property def", "Set this property if using Bugsnag On-Premise. >>> config =", "@params_filters.setter # type: ignore @validate_iterable_setter def params_filters(self, value: List[str]): self._params_filters", "ignore @validate_bool_setter def send_code(self, value: bool): self._send_code = value @property", "create_default_delivery() self.lib_root = sysconfig.get_path('purelib') self.project_root = os.getcwd() self.app_type = None", "self def get(self, name): \"\"\" Get a single configuration option", "# type: ignore @validate_str_setter def project_root(self, value: str): self._project_root =", "application \"\"\" return self._app_version @app_version.setter # type: ignore @validate_str_setter def", "def clear(cls): \"\"\" Clear this thread's instance of the RequestConfiguration.", "self._hostname = value @property def ignore_classes(self): \"\"\" Fully qualified class", "this prefix are considered a part of the project. This", "value: str): self._proxy_host = value @property def release_stage(self): \"\"\" The", "= release_stage if send_code is not None: self.send_code = send_code", "self._send_code @send_code.setter # type: ignore @validate_bool_setter def send_code(self, value: bool):", "\"\"\" _request_info.set(None) def __init__(self): self.context = None self.grouping_hash = None", "# type: ignore @validate_str_setter def app_type(self, value: str): self._app_type =", "be automatically captured and reported \"\"\" return self._auto_notify @auto_notify.setter #", "Any, Tuple, Union import warnings from bugsnag.sessiontracker import SessionMiddleware from", "favor of referencing properties directly', DeprecationWarning) return getattr(self, name) @property", "detected and delivered from web request integrations \"\"\" return self._auto_capture_sessions", "else: self.hostname = None self.runtime_versions = {\"python\": platform.python_version()} def configure(self,", "= None if instance is None: instance = RequestConfiguration() _request_info.set(instance)", "import List, Any, Tuple, Union import warnings from bugsnag.sessiontracker import", "validate_iterable_setter, validate_required_str_setter) from bugsnag.delivery import (create_default_delivery, DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT) from bugsnag.uwsgi", "events and sessions. By default this value is None and", "permitted to capture and send events and sessions. By default", "exception: BaseException) -> bool: return self.ignore_classes is not None and", "self.metadata = {} # legacy fields self.user_id = None self.extra_data", "warn_if_running_uwsgi_without_threads try: from contextvars import ContextVar _request_info = ContextVar('bugsnag-request', default=None)", "def configure(self, api_key=None, app_type=None, app_version=None, asynchronous=None, auto_notify=None, auto_capture_sessions=None, delivery=None, endpoint=None,", "interface to customize how requests are sent. \"\"\" return self._delivery", "name) def configure(self, **options): \"\"\" Set one or more configuration", "delivered from web request integrations \"\"\" return self._auto_capture_sessions @auto_capture_sessions.setter #", "the RequestConfiguration. \"\"\" try: instance = _request_info.get() except LookupError: instance", "import SessionMiddleware from bugsnag.middleware import DefaultMiddleware, MiddlewareStack from bugsnag.utils import", "automatically captured and reported \"\"\" return self._auto_notify @auto_notify.setter # type:", "an error in a future release.') warnings.warn(message.format(type(value).__name__), RuntimeWarning) @property def", "\"\"\" return self._notify_release_stages @notify_release_stages.setter # type: ignore @validate_iterable_setter def notify_release_stages(self,", "Transport mechanism used to make API requests. Implement the Delivery", "events. KeyboardInterrupt and Http404 exceptions are ignored by default. \"\"\"", "all events and sessions are delivered. \"\"\" return self._notify_release_stages @notify_release_stages.setter", "get(self, name) -> Any: \"\"\" Get a single configuration option", "# type: ignore @validate_iterable_setter def ignore_classes(self, value: Union[List[str], Tuple[str]]): self._ignore_classes", "\"\"\" return self._send_code @send_code.setter # type: ignore @validate_bool_setter def send_code(self,", "return self._auto_capture_sessions @auto_capture_sessions.setter # type: ignore @validate_bool_setter def auto_capture_sessions(self, value:", "self.request_data = {} self.environment_data = {} self.session_data = {} def", "proxy_host(self, value: str): self._proxy_host = value @property def release_stage(self): \"\"\"", "self._session_endpoint = value @property def traceback_exclude_modules(self): \"\"\" Modules which should", "instance = None if instance is None: instance = RequestConfiguration()", "is not None: self.project_root = project_root if proxy_host is not", "= True self.delivery = create_default_delivery() self.lib_root = sysconfig.get_path('purelib') self.project_root =", "for Heroku applications and included in event device metadata. \"\"\"", "is ' + 'deprecated in favor of referencing properties directly',", "automatically detected and delivered from web request integrations \"\"\" return", "if any \"\"\" return self._proxy_host @proxy_host.setter # type: ignore @validate_str_setter", "Any: warnings.warn('RequestConfiguration.meta_data has been renamed to ' + '\"metadata\"', DeprecationWarning)", "if ignore_classes is not None: self.ignore_classes = ignore_classes if lib_root", "{} self.metadata = {} # legacy fields self.user_id = None", "not None: self.send_environment = send_environment if session_endpoint is not None:", "exceptions are ignored by default. \"\"\" return self._ignore_classes @ignore_classes.setter #", "None: self.traceback_exclude_modules = traceback_exclude_modules return self def get(self, name): \"\"\"", "value): if hasattr(value, 'deliver') and callable(value.deliver): self._delivery = value else:", "Configuration() >>> config.endpoint = 'https://notify.bugsnag.example.co' \"\"\" return self._endpoint @endpoint.setter #", "@property def meta_data(self) -> Any: warnings.warn('RequestConfiguration.meta_data has been renamed to", "= os.environ.get('BUGSNAG_API_KEY', None) self.release_stage = os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\") self.notify_release_stages = None", "default. \"\"\" return self._ignore_classes @ignore_classes.setter # type: ignore @validate_iterable_setter def", "be an error in a future release.') warnings.warn(message.format(type(value).__name__), RuntimeWarning) @property", "file name readability in traceback lines. \"\"\" return self._project_root @project_root.setter", "error in a future release.') warnings.warn(message.format(type(value).__name__), RuntimeWarning) @property def endpoint(self):", "lib_root(self): \"\"\" The path to the Python library. Any traceback", "return getattr(self, name) @property def api_key(self): \"\"\" Unique application identifier", "application server. This value is automatically detected for Heroku applications", "params_filters is not None: self.params_filters = params_filters if project_root is", "\"\"\" return self._traceback_exclude_modules @traceback_exclude_modules.setter # type: ignore @validate_iterable_setter def traceback_exclude_modules(self,", "self.release_stage in self.notify_release_stages) def should_ignore(self, exception: BaseException) -> bool: return", "self.ignore_classes = ignore_classes if lib_root is not None: self.lib_root =", "# type: ignore @validate_str_setter def lib_root(self, value: str): self._lib_root =", "def get(self, name) -> Any: \"\"\" Get a single configuration", "endpoint is not None: self.endpoint = endpoint if hostname is", "self.session_data = {} def get(self, name) -> Any: \"\"\" Get", "\"cookie\", \"authorization\"] self.ignore_classes = [ \"KeyboardInterrupt\", \"django.http.Http404\", \"django.http.response.Http404\", ] self.endpoint", "retrieve a Configuration property is ' + 'deprecated in favor", "for name, value in options.items(): setattr(self, name, value) return self", "configuration option \"\"\" return getattr(self, name) def configure(self, **options): \"\"\"", "else: message = ('delivery should implement Delivery interface, got '", "None: self.proxy_host = proxy_host if release_stage is not None: self.release_stage", "\"\"\" Get a single configuration option \"\"\" return getattr(self, name)", "\"\"\" Release version of the current application \"\"\" return self._app_version", "-> Any: \"\"\" Get a single configuration option \"\"\" return", "[ \"KeyboardInterrupt\", \"django.http.Http404\", \"django.http.response.Http404\", ] self.endpoint = DEFAULT_ENDPOINT self.session_endpoint =", "configuration settings. \"\"\" @classmethod def get_instance(cls): \"\"\" Get this thread's", "type: ignore @validate_str_setter def app_version(self, value: str): self._app_version = value", "which occur in production vs development or staging environments. \"\"\"", "self._release_stage @release_stage.setter # type: ignore @validate_str_setter def release_stage(self, value: str):", "None: self.session_endpoint = session_endpoint if traceback_exclude_modules is not None: self.traceback_exclude_modules", "RequestConfiguration() _request_info.set(instance) # type: ignore return instance @classmethod def clear(cls):", "send_code is not None: self.send_code = send_code if send_environment is", "Release version of the current application \"\"\" return self._app_version @app_version.setter", "self.hostname = None self.runtime_versions = {\"python\": platform.python_version()} def configure(self, api_key=None,", "str): self._project_root = value @property def proxy_host(self): \"\"\" The host", "Unique application identifier \"\"\" return self._api_key @api_key.setter # type: ignore", "immediately surrounding traceback locations should be sent with events \"\"\"", "self._send_code = value @property def send_environment(self): \"\"\" If the request", "send_environment if session_endpoint is not None: self.session_endpoint = session_endpoint if", "If API requests should be sent asynchronously \"\"\" return self._asynchronous", "= True self.traceback_exclude_modules = [] self.middleware = MiddlewareStack() self.internal_middleware =", "# type: ignore @validate_iterable_setter def params_filters(self, value: List[str]): self._params_filters =", "import warn_if_running_uwsgi_without_threads try: from contextvars import ContextVar _request_info = ContextVar('bugsnag-request',", "True self.send_environment = False self.asynchronous = True self.delivery = create_default_delivery()", "a part of the project. This prefix is also stripped", "def api_key(self): \"\"\" Unique application identifier \"\"\" return self._api_key @api_key.setter", "traceback_exclude_modules=None): \"\"\" Validate and set configuration options. Will warn if", "def lib_root(self): \"\"\" The path to the Python library. Any", "= {} self.environment_data = {} self.session_data = {} def get(self,", "value @property def release_stage(self): \"\"\" The development phase of the", "and included in event device metadata. \"\"\" return self._hostname @hostname.setter", "should be automatically captured and reported \"\"\" return self._auto_notify @auto_notify.setter", "not None: self.asynchronous = asynchronous if auto_notify is not None:", "return self.notify_release_stages is None or \\ (isinstance(self.notify_release_stages, (tuple, list)) and", "properties directly', DeprecationWarning) return getattr(self, name) @property def api_key(self): \"\"\"", "this value is None and all events and sessions are", "def project_root(self, value: str): self._project_root = value @property def proxy_host(self):", "value: warn_if_running_uwsgi_without_threads() @property def auto_capture_sessions(self): \"\"\" If sessions should be", "options.items(): setattr(self, name, value) return self @property def meta_data(self) ->", "None: self.hostname = hostname if ignore_classes is not None: self.ignore_classes", "= None self.params_filters = [\"password\", \"password_confirmation\", \"cookie\", \"authorization\"] self.ignore_classes =", "meta_data(self) -> Any: warnings.warn('RequestConfiguration.meta_data has been renamed to ' +", "traceback_exclude_modules is not None: self.traceback_exclude_modules = traceback_exclude_modules return self def", "def params_filters(self): \"\"\" A list of filters applied to event", "ignore @validate_bool_setter def asynchronous(self, value: bool): self._asynchronous = value if", "proxy_host if release_stage is not None: self.release_stage = release_stage if", "@property def app_type(self): \"\"\" Category for the current application or", "instance of the RequestConfiguration. \"\"\" try: instance = _request_info.get() except", "warnings.warn(message.format(type(value).__name__), RuntimeWarning) @property def endpoint(self): \"\"\" Event API endpoint. Set", "events \"\"\" return self._send_environment @send_environment.setter # type: ignore @validate_bool_setter def", "value def should_notify(self) -> bool: return self.notify_release_stages is None or", "By default the following keys are filtered: * authorization *", "The development phase of the deployed application. This value is", "\"\"\" warnings.warn('Using get() to retrieve a Configuration property is '", "release_stage values which are permitted to capture and send events", "in favor of referencing properties directly', DeprecationWarning) return getattr(self, name)", "DEFAULT_ENDPOINT self.session_endpoint = DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions = True self.traceback_exclude_modules = []", "warn_if_running_uwsgi_without_threads() @property def auto_capture_sessions(self): \"\"\" If sessions should be automatically", "def session_endpoint(self, value: str): self._session_endpoint = value @property def traceback_exclude_modules(self):", "+ '{0}. This will be an error in a future", "send_code=None, send_environment=None, session_endpoint=None, traceback_exclude_modules=None): \"\"\" Validate and set configuration options.", "@property def params_filters(self): \"\"\" A list of filters applied to", "endpoint. Set this property if using Bugsnag On-Premise. >>> config", "'https://notify.bugsnag.example.co' \"\"\" return self._endpoint @endpoint.setter # type: ignore @validate_required_str_setter def", "self._auto_notify @auto_notify.setter # type: ignore @validate_bool_setter def auto_notify(self, value: bool):", "make file names easier to read. \"\"\" return self._lib_root @lib_root.setter", "if delivery is not None: self.delivery = delivery if endpoint", "reported \"\"\" return self._auto_notify @auto_notify.setter # type: ignore @validate_bool_setter def", "self.traceback_exclude_modules = traceback_exclude_modules return self def get(self, name): \"\"\" Get", "legacy fields self.user_id = None self.extra_data = {} self.request_data =", "requests should be sent asynchronously \"\"\" return self._asynchronous @asynchronous.setter #", "requests. Implement the Delivery interface to customize how requests are", "should be ignored when capturing uncaught exceptions and other events.", "= proxy_host if release_stage is not None: self.release_stage = release_stage", "None self.runtime_versions = {\"python\": platform.python_version()} def configure(self, api_key=None, app_type=None, app_version=None,", "ignore @validate_str_setter def release_stage(self, value: str): self._release_stage = value @property", "should be sent with events \"\"\" return self._send_code @send_code.setter #", "self._lib_root @lib_root.setter # type: ignore @validate_str_setter def lib_root(self, value: str):", "= delivery if endpoint is not None: self.endpoint = endpoint", "if hostname is not None: self.hostname = hostname if ignore_classes", "\"\"\" A list of filters applied to event metadata to", "to prevent the values from being sent in events. By", "return self._project_root @project_root.setter # type: ignore @validate_str_setter def project_root(self, value:", "lib_root is not None: self.lib_root = lib_root if notify_release_stages is", "the following keys are filtered: * authorization * cookie *", "settings. \"\"\" for name, value in options.items(): setattr(self, name, value)", "configure(self, api_key=None, app_type=None, app_version=None, asynchronous=None, auto_notify=None, auto_capture_sessions=None, delivery=None, endpoint=None, hostname=None,", "params_filters if project_root is not None: self.project_root = project_root if", "is not None: self.lib_root = lib_root if notify_release_stages is not", "\"\"\" The development phase of the deployed application. This value", "value @property def lib_root(self): \"\"\" The path to the Python", "to use to deliver requests, if any \"\"\" return self._proxy_host", "proxy to use to deliver requests, if any \"\"\" return", "if auto_notify is not None: self.auto_notify = auto_notify if auto_capture_sessions", "@property def app_version(self): \"\"\" Release version of the current application", "part of the project. This prefix is also stripped to", "Union[List[str], Tuple[str]]): self._ignore_classes = value @property def lib_root(self): \"\"\" The", "bugsnag.sessiontracker import SessionMiddleware from bugsnag.middleware import DefaultMiddleware, MiddlewareStack from bugsnag.utils", "value: str): self._hostname = value @property def ignore_classes(self): \"\"\" Fully", "used to differentiate events which occur in production vs development", "type: ignore @validate_required_str_setter def endpoint(self, value: str): self._endpoint = value", "instance @classmethod def clear(cls): \"\"\" Clear this thread's instance of", "thread's instance of the RequestConfiguration. \"\"\" try: instance = _request_info.get()", "send_environment is not None: self.send_environment = send_environment if session_endpoint is", "None: instance = RequestConfiguration() _request_info.set(instance) # type: ignore return instance", "Delivery interface, got ' + '{0}. This will be an", "release.') warnings.warn(message.format(type(value).__name__), RuntimeWarning) @property def endpoint(self): \"\"\" Event API endpoint.", "get() to retrieve a Configuration property is ' + 'deprecated", "def hostname(self): \"\"\" The host name of the application server.", "def notify_release_stages(self, value: List[str]): self._notify_release_stages = value @property def params_filters(self):", "= False self.asynchronous = True self.delivery = create_default_delivery() self.lib_root =", "in event device metadata. \"\"\" return self._hostname @hostname.setter # type:", "if app_version is not None: self.app_version = app_version if asynchronous", "return getattr(self, name) def configure(self, **options): \"\"\" Set one or", "self.release_stage = release_stage if send_code is not None: self.send_code =", "name of the proxy to use to deliver requests, if", "API requests should be sent asynchronously \"\"\" return self._asynchronous @asynchronous.setter", "\"\"\" Validate and set configuration options. Will warn if an", "mechanism used to make API requests. Implement the Delivery interface", "not None: self.proxy_host = proxy_host if release_stage is not None:", "callable(value.deliver): self._delivery = value else: message = ('delivery should implement", "@validate_iterable_setter def ignore_classes(self, value: Union[List[str], Tuple[str]]): self._ignore_classes = value @property", "= Configuration() >>> config.endpoint = 'https://notify.bugsnag.example.co' \"\"\" return self._endpoint @endpoint.setter", "import (fully_qualified_class_name, validate_str_setter, validate_bool_setter, validate_iterable_setter, validate_required_str_setter) from bugsnag.delivery import (create_default_delivery,", "value: str): self._app_type = value @property def app_version(self): \"\"\" Release", "when capturing uncaught exceptions and other events. KeyboardInterrupt and Http404", "('Configuration', 'RequestConfiguration') class Configuration: \"\"\" Global app-level Bugsnag configuration settings.", "from web request integrations \"\"\" return self._auto_capture_sessions @auto_capture_sessions.setter # type:", "Get this thread's instance of the RequestConfiguration. \"\"\" try: instance", "delivered. \"\"\" return self._notify_release_stages @notify_release_stages.setter # type: ignore @validate_iterable_setter def", "= value @property def traceback_exclude_modules(self): \"\"\" Modules which should be", "= asynchronous if auto_notify is not None: self.auto_notify = auto_notify", "get_instance(cls): \"\"\" Get this thread's instance of the RequestConfiguration. \"\"\"", "auto_capture_sessions(self): \"\"\" If sessions should be automatically detected and delivered", "from bugsnag.delivery import (create_default_delivery, DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT) from bugsnag.uwsgi import warn_if_running_uwsgi_without_threads", "which contain this prefix are considered a part of the", "Http404 exceptions are ignored by default. \"\"\" return self._ignore_classes @ignore_classes.setter", "@validate_str_setter def lib_root(self, value: str): self._lib_root = value @property def", "import os import platform import socket import sysconfig from typing", "None: self.endpoint = endpoint if hostname is not None: self.hostname", "__init__(self): self.api_key = os.environ.get('BUGSNAG_API_KEY', None) self.release_stage = os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\") self.notify_release_stages", "this thread's instance of the RequestConfiguration. \"\"\" _request_info.set(None) def __init__(self):", "is not None: self.asynchronous = asynchronous if auto_notify is not", "an option is of an incorrect type. \"\"\" if api_key", "to make API requests. Implement the Delivery interface to customize", "return self._params_filters @params_filters.setter # type: ignore @validate_iterable_setter def params_filters(self, value:", "= app_version if asynchronous is not None: self.asynchronous = asynchronous", "value @property def send_code(self): \"\"\" If the source code lines", "Validate and set configuration options. Will warn if an option", "if api_key is not None: self.api_key = api_key if app_type", "import platform import socket import sysconfig from typing import List,", "value @property def project_root(self): \"\"\" The working directory containing the", "not None: self.hostname = hostname if ignore_classes is not None:", "\"\"\" return self._auto_notify @auto_notify.setter # type: ignore @validate_bool_setter def auto_notify(self,", "validate_required_str_setter) from bugsnag.delivery import (create_default_delivery, DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT) from bugsnag.uwsgi import", "= {} self.session_data = {} def get(self, name) -> Any:", "self._ignore_classes = value @property def lib_root(self): \"\"\" The path to", "of the current application \"\"\" return self._app_version @app_version.setter # type:", "staging environments. \"\"\" return self._release_stage @release_stage.setter # type: ignore @validate_str_setter", "asynchronously \"\"\" return self._asynchronous @asynchronous.setter # type: ignore @validate_bool_setter def", "KeyboardInterrupt and Http404 exceptions are ignored by default. \"\"\" return", "self.lib_root = sysconfig.get_path('purelib') self.project_root = os.getcwd() self.app_type = None self.app_version", "@validate_bool_setter def auto_notify(self, value: bool): self._auto_notify = value @property def", "If sessions should be automatically detected and delivered from web", "@property def hostname(self): \"\"\" The host name of the application", "def send_code(self): \"\"\" If the source code lines immediately surrounding", "def auto_notify(self, value: bool): self._auto_notify = value @property def delivery(self):", "# type: ignore except ImportError: from bugsnag.utils import ThreadContextVar _request_info", "= app_type if app_version is not None: self.app_version = app_version", "{} self.session_data = {} def get(self, name) -> Any: \"\"\"", "def auto_capture_sessions(self, value: bool): self._auto_capture_sessions = value @property def auto_notify(self):", "ThreadContextVar _request_info = ThreadContextVar('bugsnag-request', default=None) # type: ignore # noqa:", "self.app_version = None self.params_filters = [\"password\", \"password_confirmation\", \"cookie\", \"authorization\"] self.ignore_classes", "delivery is not None: self.delivery = delivery if endpoint is", "has been renamed to ' + '\"metadata\"', DeprecationWarning) return self.metadata", "'deprecated in favor of referencing properties directly', DeprecationWarning) return getattr(self,", "app_version(self): \"\"\" Release version of the current application \"\"\" return", "def notify_release_stages(self): \"\"\" A list of release_stage values which are", "if hasattr(value, 'deliver') and callable(value.deliver): self._delivery = value else: message", "send_environment(self, value: bool): self._send_environment = value @property def session_endpoint(self): \"\"\"", "type: ignore # noqa: E501 __all__ = ('Configuration', 'RequestConfiguration') class", "def meta_data(self) -> Any: warnings.warn('RequestConfiguration.meta_data has been renamed to '", "self.params_filters = params_filters if project_root is not None: self.project_root =", "'https://sessions.bugsnag.example.co' \"\"\" return self._session_endpoint @session_endpoint.setter # type: ignore @validate_required_str_setter def", "self.environment_data = {} self.session_data = {} def get(self, name) ->", "self.auto_notify = auto_notify if auto_capture_sessions is not None: self.auto_capture_sessions =", "self.session_endpoint = DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions = True self.traceback_exclude_modules = [] self.middleware", "None and all events and sessions are delivered. \"\"\" return", "self._endpoint @endpoint.setter # type: ignore @validate_required_str_setter def endpoint(self, value: str):", "Bugsnag configuration settings. \"\"\" def __init__(self): self.api_key = os.environ.get('BUGSNAG_API_KEY', None)", "if proxy_host is not None: self.proxy_host = proxy_host if release_stage", "one or more configuration settings. \"\"\" for name, value in", "noqa: E501 __all__ = ('Configuration', 'RequestConfiguration') class Configuration: \"\"\" Global", "auto_capture_sessions=None, delivery=None, endpoint=None, hostname=None, ignore_classes=None, lib_root=None, notify_release_stages=None, params_filters=None, project_root=None, proxy_host=None,", "how requests are sent. \"\"\" return self._delivery @delivery.setter # type:", "\"\"\" Event API endpoint. Set this property if using Bugsnag", "None: self.api_key = api_key if app_type is not None: self.app_type", "of the deployed application. This value is used to differentiate", "class Configuration: \"\"\" Global app-level Bugsnag configuration settings. \"\"\" def", "\\ (isinstance(self.notify_release_stages, (tuple, list)) and self.release_stage in self.notify_release_stages) def should_ignore(self,", "return self @property def meta_data(self) -> Any: warnings.warn('RequestConfiguration.meta_data has been", "# type: ignore @validate_bool_setter def auto_notify(self, value: bool): self._auto_notify =", "customize how requests are sent. \"\"\" return self._delivery @delivery.setter #", "@validate_str_setter def project_root(self, value: str): self._project_root = value @property def", "\"\"\" return self._delivery @delivery.setter # type: ignore def delivery(self, value):", "if value: warn_if_running_uwsgi_without_threads() @property def auto_capture_sessions(self): \"\"\" If sessions should", "os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\") self.notify_release_stages = None self.auto_notify = True self.send_code =", "considered a part of the project. This prefix is also", "self._api_key @api_key.setter # type: ignore @validate_required_str_setter def api_key(self, value: str):", "return self._proxy_host @proxy_host.setter # type: ignore @validate_str_setter def proxy_host(self, value:", "value @property def app_type(self): \"\"\" Category for the current application", "value @property def session_endpoint(self): \"\"\" Sessions API endpoint. Set this", "type: ignore @validate_bool_setter def auto_notify(self, value: bool): self._auto_notify = value", "Set one or more configuration settings. \"\"\" for name, value", "lib_root=None, notify_release_stages=None, params_filters=None, project_root=None, proxy_host=None, release_stage=None, send_code=None, send_environment=None, session_endpoint=None, traceback_exclude_modules=None):", "value @property def traceback_exclude_modules(self): \"\"\" Modules which should be stripped", "should be stripped from event tracebacks entirely \"\"\" return self._traceback_exclude_modules", "file paths which contain this prefix are considered a part", "self @property def meta_data(self) -> Any: warnings.warn('RequestConfiguration.meta_data has been renamed", "-> bool: return self.notify_release_stages is None or \\ (isinstance(self.notify_release_stages, (tuple,", "self.send_environment = send_environment if session_endpoint is not None: self.session_endpoint =", "of release_stage values which are permitted to capture and send", "clear(cls): \"\"\" Clear this thread's instance of the RequestConfiguration. \"\"\"", "None if instance is None: instance = RequestConfiguration() _request_info.set(instance) #", "def __init__(self): self.context = None self.grouping_hash = None self.user =", "= _request_info.get() except LookupError: instance = None if instance is", "self._project_root @project_root.setter # type: ignore @validate_str_setter def project_root(self, value: str):", "import (create_default_delivery, DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT) from bugsnag.uwsgi import warn_if_running_uwsgi_without_threads try: from", "ignore @validate_bool_setter def send_environment(self, value: bool): self._send_environment = value @property", "self.project_root = os.getcwd() self.app_type = None self.app_version = None self.params_filters", "default=None) # type: ignore except ImportError: from bugsnag.utils import ThreadContextVar", "@validate_required_str_setter def api_key(self, value: str): self._api_key = value @property def", "= 'https://notify.bugsnag.example.co' \"\"\" return self._endpoint @endpoint.setter # type: ignore @validate_required_str_setter", "sysconfig from typing import List, Any, Tuple, Union import warnings", "is not None: self.send_environment = send_environment if session_endpoint is not", "prefix is also stripped to increase file name readability in", "if endpoint is not None: self.endpoint = endpoint if hostname", "def api_key(self, value: str): self._api_key = value @property def app_type(self):", "@validate_iterable_setter def traceback_exclude_modules(self, value: List[str]): self._traceback_exclude_modules = value def should_notify(self)", "in traceback lines. \"\"\" return self._project_root @project_root.setter # type: ignore", "release_stage(self, value: str): self._release_stage = value @property def send_code(self): \"\"\"", "# type: ignore @validate_str_setter def proxy_host(self, value: str): self._proxy_host =", "self.api_key = api_key if app_type is not None: self.app_type =", "value if value: warn_if_running_uwsgi_without_threads() @property def auto_capture_sessions(self): \"\"\" If sessions", "return self._traceback_exclude_modules @traceback_exclude_modules.setter # type: ignore @validate_iterable_setter def traceback_exclude_modules(self, value:", "request environment should be automatically collected and attached to events", "Any traceback frame which contains lib_root as a prefix is", "release_stage=None, send_code=None, send_environment=None, session_endpoint=None, traceback_exclude_modules=None): \"\"\" Validate and set configuration", "environment should be automatically collected and attached to events \"\"\"", "differentiate events which occur in production vs development or staging", "value: str): self._release_stage = value @property def send_code(self): \"\"\" If", "self._asynchronous @asynchronous.setter # type: ignore @validate_bool_setter def asynchronous(self, value: bool):", "True self.send_code = True self.send_environment = False self.asynchronous = True", "auto_capture_sessions if delivery is not None: self.delivery = delivery if", "= sysconfig.get_path('purelib') self.project_root = os.getcwd() self.app_type = None self.app_version =", "\"\"\" The path to the Python library. Any traceback frame", "names easier to read. \"\"\" return self._lib_root @lib_root.setter # type:", "qualified class names which should be ignored when capturing uncaught", "\"\"\" return self._project_root @project_root.setter # type: ignore @validate_str_setter def project_root(self,", "type: ignore @validate_str_setter def hostname(self, value: str): self._hostname = value", "= auto_notify if auto_capture_sessions is not None: self.auto_capture_sessions = auto_capture_sessions", "type: ignore @validate_str_setter def release_stage(self, value: str): self._release_stage = value", "if params_filters is not None: self.params_filters = params_filters if project_root", "value is used to differentiate events which occur in production", "configuration option \"\"\" warnings.warn('Using get() to retrieve a Configuration property", ">>> config.endpoint = 'https://notify.bugsnag.example.co' \"\"\" return self._endpoint @endpoint.setter # type:", "= value @property def ignore_classes(self): \"\"\" Fully qualified class names", "using Bugsnag On-Premise. >>> config = Configuration() >>> config.session_endpoint =", "@validate_bool_setter def auto_capture_sessions(self, value: bool): self._auto_capture_sessions = value @property def", "host name of the proxy to use to deliver requests,", "type: ignore @validate_required_str_setter def session_endpoint(self, value: str): self._session_endpoint = value", "List[str]): self._notify_release_stages = value @property def params_filters(self): \"\"\" A list", "\"\"\" return self._hostname @hostname.setter # type: ignore @validate_str_setter def hostname(self,", "filtered: * authorization * cookie * password * password_confirmation \"\"\"", "Sessions API endpoint. Set this property if using Bugsnag On-Premise.", "send events and sessions. By default this value is None", "@validate_str_setter def app_version(self, value: str): self._app_version = value @property def", "tracebacks entirely \"\"\" return self._traceback_exclude_modules @traceback_exclude_modules.setter # type: ignore @validate_iterable_setter", "self._traceback_exclude_modules @traceback_exclude_modules.setter # type: ignore @validate_iterable_setter def traceback_exclude_modules(self, value: List[str]):", "Get a single configuration option \"\"\" warnings.warn('Using get() to retrieve", "DefaultMiddleware, MiddlewareStack from bugsnag.utils import (fully_qualified_class_name, validate_str_setter, validate_bool_setter, validate_iterable_setter, validate_required_str_setter)", "name, value in options.items(): setattr(self, name, value) return self @property", "@property def traceback_exclude_modules(self): \"\"\" Modules which should be stripped from", "return self.ignore_classes is not None and \\ fully_qualified_class_name(exception) in self.ignore_classes", "the application source code. Traceback file paths which contain this", "Bugsnag configuration settings. \"\"\" @classmethod def get_instance(cls): \"\"\" Get this", "list of release_stage values which are permitted to capture and", "If the request environment should be automatically collected and attached", "value: bool): self._send_code = value @property def send_environment(self): \"\"\" If", "__init__(self): self.context = None self.grouping_hash = None self.user = {}", "@ignore_classes.setter # type: ignore @validate_iterable_setter def ignore_classes(self, value: Union[List[str], Tuple[str]]):", "None self.grouping_hash = None self.user = {} self.metadata = {}", "return self._endpoint @endpoint.setter # type: ignore @validate_required_str_setter def endpoint(self, value:", "make API requests. Implement the Delivery interface to customize how", "not None: self.session_endpoint = session_endpoint if traceback_exclude_modules is not None:", "self.ignore_classes class RequestConfiguration: \"\"\" Per-request Bugsnag configuration settings. \"\"\" @classmethod", "traceback frame which contains lib_root as a prefix is considered", "config.endpoint = 'https://notify.bugsnag.example.co' \"\"\" return self._endpoint @endpoint.setter # type: ignore", "(isinstance(self.notify_release_stages, (tuple, list)) and self.release_stage in self.notify_release_stages) def should_ignore(self, exception:", "= {} # legacy fields self.user_id = None self.extra_data =", "from bugsnag.uwsgi import warn_if_running_uwsgi_without_threads try: from contextvars import ContextVar _request_info", "= endpoint if hostname is not None: self.hostname = hostname", "is not None: self.app_type = app_type if app_version is not", "if notify_release_stages is not None: self.notify_release_stages = notify_release_stages if params_filters", "def traceback_exclude_modules(self): \"\"\" Modules which should be stripped from event", "API requests. Implement the Delivery interface to customize how requests", "value @property def send_environment(self): \"\"\" If the request environment should", "production vs development or staging environments. \"\"\" return self._release_stage @release_stage.setter", "Implement the Delivery interface to customize how requests are sent.", "as a prefix is considered out-of-project. The prefix is also", "values from being sent in events. By default the following", "if project_root is not None: self.project_root = project_root if proxy_host", "is None or \\ (isinstance(self.notify_release_stages, (tuple, list)) and self.release_stage in", "\"\"\" try: instance = _request_info.get() except LookupError: instance = None", "[\"password\", \"password_confirmation\", \"cookie\", \"authorization\"] self.ignore_classes = [ \"KeyboardInterrupt\", \"django.http.Http404\", \"django.http.response.Http404\",", "RequestConfiguration. \"\"\" try: instance = _request_info.get() except LookupError: instance =", "is None: instance = RequestConfiguration() _request_info.set(instance) # type: ignore return", "@validate_bool_setter def asynchronous(self, value: bool): self._asynchronous = value if value:", "# type: ignore # noqa: E501 __all__ = ('Configuration', 'RequestConfiguration')", "DeprecationWarning) return getattr(self, name) @property def api_key(self): \"\"\" Unique application", "value: List[str]): self._notify_release_stages = value @property def params_filters(self): \"\"\" A", "notify_release_stages if params_filters is not None: self.params_filters = params_filters if", "the current application or task \"\"\" return self._app_type @app_type.setter #", "self._auto_notify = value @property def delivery(self): \"\"\" Transport mechanism used", "hostname(self, value: str): self._hostname = value @property def ignore_classes(self): \"\"\"", "a Configuration property is ' + 'deprecated in favor of", "value in options.items(): setattr(self, name, value) return self @property def", "= os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\") self.notify_release_stages = None self.auto_notify = True self.send_code", "sessions are delivered. \"\"\" return self._notify_release_stages @notify_release_stages.setter # type: ignore", "sent in events. By default the following keys are filtered:", "config = Configuration() >>> config.session_endpoint = 'https://sessions.bugsnag.example.co' \"\"\" return self._session_endpoint", "incorrect type. \"\"\" if api_key is not None: self.api_key =", "# type: ignore @validate_required_str_setter def api_key(self, value: str): self._api_key =", "= params_filters if project_root is not None: self.project_root = project_root", "detected for Heroku applications and included in event device metadata.", "\"authorization\"] self.ignore_classes = [ \"KeyboardInterrupt\", \"django.http.Http404\", \"django.http.response.Http404\", ] self.endpoint =", "notify_release_stages(self, value: List[str]): self._notify_release_stages = value @property def params_filters(self): \"\"\"", "import ThreadContextVar _request_info = ThreadContextVar('bugsnag-request', default=None) # type: ignore #", "to event metadata to prevent the values from being sent", "bool): self._send_code = value @property def send_environment(self): \"\"\" If the", "proxy_host=None, release_stage=None, send_code=None, send_environment=None, session_endpoint=None, traceback_exclude_modules=None): \"\"\" Validate and set", "ignore @validate_iterable_setter def traceback_exclude_modules(self, value: List[str]): self._traceback_exclude_modules = value def", "' + '{0}. This will be an error in a", "= value @property def lib_root(self): \"\"\" The path to the", "@property def proxy_host(self): \"\"\" The host name of the proxy", "self._auto_capture_sessions @auto_capture_sessions.setter # type: ignore @validate_bool_setter def auto_capture_sessions(self, value: bool):", "None self.auto_notify = True self.send_code = True self.send_environment = False", "bool: return self.notify_release_stages is None or \\ (isinstance(self.notify_release_stages, (tuple, list))", "\"\"\" return self._endpoint @endpoint.setter # type: ignore @validate_required_str_setter def endpoint(self,", "bool): self._auto_capture_sessions = value @property def auto_notify(self): \"\"\" If uncaught", "uncaught exceptions and other events. KeyboardInterrupt and Http404 exceptions are", "more configuration settings. \"\"\" for name, value in options.items(): setattr(self,", "self._session_endpoint @session_endpoint.setter # type: ignore @validate_required_str_setter def session_endpoint(self, value: str):", "requests, if any \"\"\" return self._proxy_host @proxy_host.setter # type: ignore", "of the RequestConfiguration. \"\"\" try: instance = _request_info.get() except LookupError:", "self.internal_middleware = MiddlewareStack() self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware) self.proxy_host = None if not", "self.api_key = os.environ.get('BUGSNAG_API_KEY', None) self.release_stage = os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\") self.notify_release_stages =", "The working directory containing the application source code. Traceback file", "typing import List, Any, Tuple, Union import warnings from bugsnag.sessiontracker", "None: self.app_version = app_version if asynchronous is not None: self.asynchronous", "\"\"\" If the request environment should be automatically collected and", "value: str): self._app_version = value @property def asynchronous(self): \"\"\" If", "delivery(self): \"\"\" Transport mechanism used to make API requests. Implement", "keys are filtered: * authorization * cookie * password *", "RequestConfiguration. \"\"\" _request_info.set(None) def __init__(self): self.context = None self.grouping_hash =", "E501 __all__ = ('Configuration', 'RequestConfiguration') class Configuration: \"\"\" Global app-level", "notify_release_stages(self): \"\"\" A list of release_stage values which are permitted", "@classmethod def clear(cls): \"\"\" Clear this thread's instance of the", "increase file name readability in traceback lines. \"\"\" return self._project_root", "= MiddlewareStack() self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware) self.proxy_host = None if not os.getenv(\"DYNO\"):", "considered out-of-project. The prefix is also stripped to make file", "# type: ignore @validate_str_setter def app_version(self, value: str): self._app_version =", "@validate_iterable_setter def params_filters(self, value: List[str]): self._params_filters = value @property def", "using Bugsnag On-Premise. >>> config = Configuration() >>> config.endpoint =", "send_code(self): \"\"\" If the source code lines immediately surrounding traceback", "value @property def app_version(self): \"\"\" Release version of the current", "to the Python library. Any traceback frame which contains lib_root", "asynchronous(self, value: bool): self._asynchronous = value if value: warn_if_running_uwsgi_without_threads() @property", "traceback_exclude_modules(self): \"\"\" Modules which should be stripped from event tracebacks", "= api_key if app_type is not None: self.app_type = app_type", "locations should be sent with events \"\"\" return self._send_code @send_code.setter", "fields self.user_id = None self.extra_data = {} self.request_data = {}", "@property def ignore_classes(self): \"\"\" Fully qualified class names which should", "not None: self.api_key = api_key if app_type is not None:", "deliver requests, if any \"\"\" return self._proxy_host @proxy_host.setter # type:", "\"\"\" Modules which should be stripped from event tracebacks entirely", "is also stripped to increase file name readability in traceback", "of the RequestConfiguration. \"\"\" _request_info.set(None) def __init__(self): self.context = None", "self.project_root = project_root if proxy_host is not None: self.proxy_host =", "is automatically detected for Heroku applications and included in event", "validate_bool_setter, validate_iterable_setter, validate_required_str_setter) from bugsnag.delivery import (create_default_delivery, DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT) from", "lib_root as a prefix is considered out-of-project. The prefix is", "self.session_endpoint = session_endpoint if traceback_exclude_modules is not None: self.traceback_exclude_modules =", "params_filters(self, value: List[str]): self._params_filters = value @property def project_root(self): \"\"\"", "file names easier to read. \"\"\" return self._lib_root @lib_root.setter #", "easier to read. \"\"\" return self._lib_root @lib_root.setter # type: ignore", "should be automatically detected and delivered from web request integrations", "value @property def params_filters(self): \"\"\" A list of filters applied", "traceback_exclude_modules(self, value: List[str]): self._traceback_exclude_modules = value def should_notify(self) -> bool:", "str): self._release_stage = value @property def send_code(self): \"\"\" If the", "self._notify_release_stages = value @property def params_filters(self): \"\"\" A list of", "type: ignore @validate_iterable_setter def params_filters(self, value: List[str]): self._params_filters = value", "Fully qualified class names which should be ignored when capturing", "are considered a part of the project. This prefix is", "send_environment=None, session_endpoint=None, traceback_exclude_modules=None): \"\"\" Validate and set configuration options. Will", "thread's instance of the RequestConfiguration. \"\"\" _request_info.set(None) def __init__(self): self.context", "contain this prefix are considered a part of the project.", "@app_version.setter # type: ignore @validate_str_setter def app_version(self, value: str): self._app_version", "@validate_str_setter def hostname(self, value: str): self._hostname = value @property def", "# type: ignore return instance @classmethod def clear(cls): \"\"\" Clear", "and sessions are delivered. \"\"\" return self._notify_release_stages @notify_release_stages.setter # type:", "@property def asynchronous(self): \"\"\" If API requests should be sent", "ignore @validate_iterable_setter def ignore_classes(self, value: Union[List[str], Tuple[str]]): self._ignore_classes = value", "self.user_id = None self.extra_data = {} self.request_data = {} self.environment_data", "from bugsnag.utils import (fully_qualified_class_name, validate_str_setter, validate_bool_setter, validate_iterable_setter, validate_required_str_setter) from bugsnag.delivery", "be stripped from event tracebacks entirely \"\"\" return self._traceback_exclude_modules @traceback_exclude_modules.setter", "ignore @validate_iterable_setter def notify_release_stages(self, value: List[str]): self._notify_release_stages = value @property", "code lines immediately surrounding traceback locations should be sent with", "from typing import List, Any, Tuple, Union import warnings from", "self.extra_data = {} self.request_data = {} self.environment_data = {} self.session_data", "= DEFAULT_ENDPOINT self.session_endpoint = DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions = True self.traceback_exclude_modules =", "api_key if app_type is not None: self.app_type = app_type if", "event metadata to prevent the values from being sent in", "in self.notify_release_stages) def should_ignore(self, exception: BaseException) -> bool: return self.ignore_classes", "are permitted to capture and send events and sessions. By", "and send events and sessions. By default this value is", "to differentiate events which occur in production vs development or", "bugsnag.utils import ThreadContextVar _request_info = ThreadContextVar('bugsnag-request', default=None) # type: ignore", "ignore @validate_str_setter def project_root(self, value: str): self._project_root = value @property", "ignore @validate_iterable_setter def params_filters(self, value: List[str]): self._params_filters = value @property", "= value @property def project_root(self): \"\"\" The working directory containing", "ignore_classes=None, lib_root=None, notify_release_stages=None, params_filters=None, project_root=None, proxy_host=None, release_stage=None, send_code=None, send_environment=None, session_endpoint=None,", "This will be an error in a future release.') warnings.warn(message.format(type(value).__name__),", "\"\"\" for name, value in options.items(): setattr(self, name, value) return", "self.ignore_classes = [ \"KeyboardInterrupt\", \"django.http.Http404\", \"django.http.response.Http404\", ] self.endpoint = DEFAULT_ENDPOINT", "return self._send_code @send_code.setter # type: ignore @validate_bool_setter def send_code(self, value:", "value: List[str]): self._traceback_exclude_modules = value def should_notify(self) -> bool: return", "= [ \"KeyboardInterrupt\", \"django.http.Http404\", \"django.http.response.Http404\", ] self.endpoint = DEFAULT_ENDPOINT self.session_endpoint", "self._delivery = value else: message = ('delivery should implement Delivery", "a prefix is considered out-of-project. The prefix is also stripped", "None self.app_version = None self.params_filters = [\"password\", \"password_confirmation\", \"cookie\", \"authorization\"]", "from contextvars import ContextVar _request_info = ContextVar('bugsnag-request', default=None) # type:", "= value @property def hostname(self): \"\"\" The host name of", "self.send_environment = False self.asynchronous = True self.delivery = create_default_delivery() self.lib_root", "self.proxy_host = None if not os.getenv(\"DYNO\"): self.hostname = socket.gethostname() else:", "the source code lines immediately surrounding traceback locations should be", "\"\"\" return self._asynchronous @asynchronous.setter # type: ignore @validate_bool_setter def asynchronous(self,", "= value @property def send_code(self): \"\"\" If the source code", "= value @property def delivery(self): \"\"\" Transport mechanism used to", "if using Bugsnag On-Premise. >>> config = Configuration() >>> config.endpoint", "following keys are filtered: * authorization * cookie * password", "@project_root.setter # type: ignore @validate_str_setter def project_root(self, value: str): self._project_root", "value @property def proxy_host(self): \"\"\" The host name of the", ">>> config = Configuration() >>> config.session_endpoint = 'https://sessions.bugsnag.example.co' \"\"\" return", "metadata to prevent the values from being sent in events.", "os.environ.get('BUGSNAG_API_KEY', None) self.release_stage = os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\") self.notify_release_stages = None self.auto_notify", "not None: self.lib_root = lib_root if notify_release_stages is not None:", "ignore except ImportError: from bugsnag.utils import ThreadContextVar _request_info = ThreadContextVar('bugsnag-request',", "Get a single configuration option \"\"\" return getattr(self, name) def", "None: self.send_environment = send_environment if session_endpoint is not None: self.session_endpoint", "and sessions. By default this value is None and all", "type: ignore @validate_required_str_setter def api_key(self, value: str): self._api_key = value", "is not None: self.send_code = send_code if send_environment is not", "any \"\"\" return self._proxy_host @proxy_host.setter # type: ignore @validate_str_setter def", "self._project_root = value @property def proxy_host(self): \"\"\" The host name", "None: self.delivery = delivery if endpoint is not None: self.endpoint", "self._api_key = value @property def app_type(self): \"\"\" Category for the", "@endpoint.setter # type: ignore @validate_required_str_setter def endpoint(self, value: str): self._endpoint", "is not None: self.session_endpoint = session_endpoint if traceback_exclude_modules is not", "from bugsnag.utils import ThreadContextVar _request_info = ThreadContextVar('bugsnag-request', default=None) # type:", "is not None: self.delivery = delivery if endpoint is not", "__all__ = ('Configuration', 'RequestConfiguration') class Configuration: \"\"\" Global app-level Bugsnag", "value @property def notify_release_stages(self): \"\"\" A list of release_stage values", "= project_root if proxy_host is not None: self.proxy_host = proxy_host", "and callable(value.deliver): self._delivery = value else: message = ('delivery should", "\"\"\" return self._session_endpoint @session_endpoint.setter # type: ignore @validate_required_str_setter def session_endpoint(self,", "value: str): self._session_endpoint = value @property def traceback_exclude_modules(self): \"\"\" Modules", "@property def lib_root(self): \"\"\" The path to the Python library.", "self.lib_root = lib_root if notify_release_stages is not None: self.notify_release_stages =", "return self def get(self, name): \"\"\" Get a single configuration", "getattr(self, name) @property def api_key(self): \"\"\" Unique application identifier \"\"\"", "\"\"\" return self._api_key @api_key.setter # type: ignore @validate_required_str_setter def api_key(self,", "\"password_confirmation\", \"cookie\", \"authorization\"] self.ignore_classes = [ \"KeyboardInterrupt\", \"django.http.Http404\", \"django.http.response.Http404\", ]", "if an option is of an incorrect type. \"\"\" if", "automatically detected for Heroku applications and included in event device", "import ContextVar _request_info = ContextVar('bugsnag-request', default=None) # type: ignore except", "MiddlewareStack() self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware) self.proxy_host = None if not os.getenv(\"DYNO\"): self.hostname", "\"\"\" Set one or more configuration settings. \"\"\" for name,", "self._send_environment @send_environment.setter # type: ignore @validate_bool_setter def send_environment(self, value: bool):", "\"django.http.Http404\", \"django.http.response.Http404\", ] self.endpoint = DEFAULT_ENDPOINT self.session_endpoint = DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions", "of filters applied to event metadata to prevent the values", "project. This prefix is also stripped to increase file name", "applied to event metadata to prevent the values from being", "event device metadata. \"\"\" return self._hostname @hostname.setter # type: ignore", "self._endpoint = value @property def hostname(self): \"\"\" The host name", "\"\"\" Sessions API endpoint. Set this property if using Bugsnag", "ignore_classes if lib_root is not None: self.lib_root = lib_root if", "= lib_root if notify_release_stages is not None: self.notify_release_stages = notify_release_stages", "value: str): self._endpoint = value @property def hostname(self): \"\"\" The", "None if not os.getenv(\"DYNO\"): self.hostname = socket.gethostname() else: self.hostname =", "session_endpoint(self, value: str): self._session_endpoint = value @property def traceback_exclude_modules(self): \"\"\"", "server. This value is automatically detected for Heroku applications and", "in production vs development or staging environments. \"\"\" return self._release_stage", "auto_notify=None, auto_capture_sessions=None, delivery=None, endpoint=None, hostname=None, ignore_classes=None, lib_root=None, notify_release_stages=None, params_filters=None, project_root=None,", "requests are sent. \"\"\" return self._delivery @delivery.setter # type: ignore", "is None and all events and sessions are delivered. \"\"\"", "* password_confirmation \"\"\" return self._params_filters @params_filters.setter # type: ignore @validate_iterable_setter", "value is None and all events and sessions are delivered.", "def asynchronous(self, value: bool): self._asynchronous = value if value: warn_if_running_uwsgi_without_threads()", "from event tracebacks entirely \"\"\" return self._traceback_exclude_modules @traceback_exclude_modules.setter # type:", ">>> config.session_endpoint = 'https://sessions.bugsnag.example.co' \"\"\" return self._session_endpoint @session_endpoint.setter # type:", "return self._release_stage @release_stage.setter # type: ignore @validate_str_setter def release_stage(self, value:", "fully_qualified_class_name(exception) in self.ignore_classes class RequestConfiguration: \"\"\" Per-request Bugsnag configuration settings.", "if not os.getenv(\"DYNO\"): self.hostname = socket.gethostname() else: self.hostname = None", "this thread's instance of the RequestConfiguration. \"\"\" try: instance =", "app_type(self): \"\"\" Category for the current application or task \"\"\"", "host name of the application server. This value is automatically", "name) -> Any: \"\"\" Get a single configuration option \"\"\"", "self.hostname = socket.gethostname() else: self.hostname = None self.runtime_versions = {\"python\":", "if using Bugsnag On-Premise. >>> config = Configuration() >>> config.session_endpoint", "_request_info.set(None) def __init__(self): self.context = None self.grouping_hash = None self.user", "to customize how requests are sent. \"\"\" return self._delivery @delivery.setter", "app-level Bugsnag configuration settings. \"\"\" def __init__(self): self.api_key = os.environ.get('BUGSNAG_API_KEY',", "endpoint(self): \"\"\" Event API endpoint. Set this property if using", "= os.getcwd() self.app_type = None self.app_version = None self.params_filters =", "@property def notify_release_stages(self): \"\"\" A list of release_stage values which", "vs development or staging environments. \"\"\" return self._release_stage @release_stage.setter #", "project_root=None, proxy_host=None, release_stage=None, send_code=None, send_environment=None, session_endpoint=None, traceback_exclude_modules=None): \"\"\" Validate and", "params_filters(self): \"\"\" A list of filters applied to event metadata", "application or task \"\"\" return self._app_type @app_type.setter # type: ignore", "import warnings from bugsnag.sessiontracker import SessionMiddleware from bugsnag.middleware import DefaultMiddleware,", "None: self.app_type = app_type if app_version is not None: self.app_version", "type: ignore @validate_str_setter def lib_root(self, value: str): self._lib_root = value", "This value is automatically detected for Heroku applications and included", "\"\"\" The working directory containing the application source code. Traceback", "(tuple, list)) and self.release_stage in self.notify_release_stages) def should_ignore(self, exception: BaseException)", "return self._hostname @hostname.setter # type: ignore @validate_str_setter def hostname(self, value:", "ignore @validate_str_setter def hostname(self, value: str): self._hostname = value @property", "and set configuration options. Will warn if an option is", "ignore_classes(self, value: Union[List[str], Tuple[str]]): self._ignore_classes = value @property def lib_root(self):", "web request integrations \"\"\" return self._auto_capture_sessions @auto_capture_sessions.setter # type: ignore", "is used to differentiate events which occur in production vs", "= None if not os.getenv(\"DYNO\"): self.hostname = socket.gethostname() else: self.hostname", "config = Configuration() >>> config.endpoint = 'https://notify.bugsnag.example.co' \"\"\" return self._endpoint", "api_key(self, value: str): self._api_key = value @property def app_type(self): \"\"\"", "return self._api_key @api_key.setter # type: ignore @validate_required_str_setter def api_key(self, value:", "with events \"\"\" return self._send_code @send_code.setter # type: ignore @validate_bool_setter", "import sysconfig from typing import List, Any, Tuple, Union import", "def app_type(self, value: str): self._app_type = value @property def app_version(self):", "# type: ignore @validate_required_str_setter def endpoint(self, value: str): self._endpoint =", "@api_key.setter # type: ignore @validate_required_str_setter def api_key(self, value: str): self._api_key", "instance of the RequestConfiguration. \"\"\" _request_info.set(None) def __init__(self): self.context =", "not None: self.app_type = app_type if app_version is not None:", "\"\"\" return self._ignore_classes @ignore_classes.setter # type: ignore @validate_iterable_setter def ignore_classes(self,", "Configuration: \"\"\" Global app-level Bugsnag configuration settings. \"\"\" def __init__(self):", "authorization * cookie * password * password_confirmation \"\"\" return self._params_filters", "endpoint=None, hostname=None, ignore_classes=None, lib_root=None, notify_release_stages=None, params_filters=None, project_root=None, proxy_host=None, release_stage=None, send_code=None,", "self.delivery = delivery if endpoint is not None: self.endpoint =", "of the project. This prefix is also stripped to increase", "value: str): self._api_key = value @property def app_type(self): \"\"\" Category", "@validate_iterable_setter def notify_release_stages(self, value: List[str]): self._notify_release_stages = value @property def", "hasattr(value, 'deliver') and callable(value.deliver): self._delivery = value else: message =", "out-of-project. The prefix is also stripped to make file names", "type: ignore @validate_str_setter def project_root(self, value: str): self._project_root = value", "= True self.send_environment = False self.asynchronous = True self.delivery =", "\"\"\" A list of release_stage values which are permitted to", "# noqa: E501 __all__ = ('Configuration', 'RequestConfiguration') class Configuration: \"\"\"", "MiddlewareStack() self.internal_middleware = MiddlewareStack() self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware) self.proxy_host = None if", "Any: \"\"\" Get a single configuration option \"\"\" return getattr(self,", "hostname if ignore_classes is not None: self.ignore_classes = ignore_classes if", "@traceback_exclude_modules.setter # type: ignore @validate_iterable_setter def traceback_exclude_modules(self, value: List[str]): self._traceback_exclude_modules", "not None: self.notify_release_stages = notify_release_stages if params_filters is not None:", "app_version=None, asynchronous=None, auto_notify=None, auto_capture_sessions=None, delivery=None, endpoint=None, hostname=None, ignore_classes=None, lib_root=None, notify_release_stages=None,", "and reported \"\"\" return self._auto_notify @auto_notify.setter # type: ignore @validate_bool_setter", "{} # legacy fields self.user_id = None self.extra_data = {}", "type: ignore @validate_iterable_setter def ignore_classes(self, value: Union[List[str], Tuple[str]]): self._ignore_classes =", "default=None) # type: ignore # noqa: E501 __all__ = ('Configuration',", "* authorization * cookie * password * password_confirmation \"\"\" return", "self.auto_notify = True self.send_code = True self.send_environment = False self.asynchronous", "@lib_root.setter # type: ignore @validate_str_setter def lib_root(self, value: str): self._lib_root", "\"\"\" Clear this thread's instance of the RequestConfiguration. \"\"\" _request_info.set(None)", "_request_info.get() except LookupError: instance = None if instance is None:", "\"\"\" return self._params_filters @params_filters.setter # type: ignore @validate_iterable_setter def params_filters(self,", "if instance is None: instance = RequestConfiguration() _request_info.set(instance) # type:", "sent asynchronously \"\"\" return self._asynchronous @asynchronous.setter # type: ignore @validate_bool_setter", "@property def endpoint(self): \"\"\" Event API endpoint. Set this property", "endpoint(self, value: str): self._endpoint = value @property def hostname(self): \"\"\"", "bool: return self.ignore_classes is not None and \\ fully_qualified_class_name(exception) in", "configuration options. Will warn if an option is of an", "delivery=None, endpoint=None, hostname=None, ignore_classes=None, lib_root=None, notify_release_stages=None, params_filters=None, project_root=None, proxy_host=None, release_stage=None,", "self._params_filters = value @property def project_root(self): \"\"\" The working directory", "True self.delivery = create_default_delivery() self.lib_root = sysconfig.get_path('purelib') self.project_root = os.getcwd()", "The path to the Python library. Any traceback frame which", "application identifier \"\"\" return self._api_key @api_key.setter # type: ignore @validate_required_str_setter", "\"\"\" Get this thread's instance of the RequestConfiguration. \"\"\" try:", "self.traceback_exclude_modules = [] self.middleware = MiddlewareStack() self.internal_middleware = MiddlewareStack() self.internal_middleware.append(DefaultMiddleware)", "= value if value: warn_if_running_uwsgi_without_threads() @property def auto_capture_sessions(self): \"\"\" If", "This value is used to differentiate events which occur in", "def ignore_classes(self): \"\"\" Fully qualified class names which should be", "type: ignore @validate_str_setter def proxy_host(self, value: str): self._proxy_host = value", "try: from contextvars import ContextVar _request_info = ContextVar('bugsnag-request', default=None) #", "stripped to increase file name readability in traceback lines. \"\"\"", "configuration settings. \"\"\" def __init__(self): self.api_key = os.environ.get('BUGSNAG_API_KEY', None) self.release_stage", "not None: self.delivery = delivery if endpoint is not None:", "if release_stage is not None: self.release_stage = release_stage if send_code", "stripped to make file names easier to read. \"\"\" return", "and self.release_stage in self.notify_release_stages) def should_ignore(self, exception: BaseException) -> bool:", "and all events and sessions are delivered. \"\"\" return self._notify_release_stages", "[] self.middleware = MiddlewareStack() self.internal_middleware = MiddlewareStack() self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware) self.proxy_host", "type: ignore @validate_bool_setter def auto_capture_sessions(self, value: bool): self._auto_capture_sessions = value", "None: self.ignore_classes = ignore_classes if lib_root is not None: self.lib_root", "return instance @classmethod def clear(cls): \"\"\" Clear this thread's instance", "the Delivery interface to customize how requests are sent. \"\"\"", "None and \\ fully_qualified_class_name(exception) in self.ignore_classes class RequestConfiguration: \"\"\" Per-request", "or more configuration settings. \"\"\" for name, value in options.items():", "ignore @validate_required_str_setter def api_key(self, value: str): self._api_key = value @property", "socket.gethostname() else: self.hostname = None self.runtime_versions = {\"python\": platform.python_version()} def", "proxy_host(self): \"\"\" The host name of the proxy to use", "@validate_required_str_setter def endpoint(self, value: str): self._endpoint = value @property def", "= value @property def asynchronous(self): \"\"\" If API requests should", "application source code. Traceback file paths which contain this prefix", "None or \\ (isinstance(self.notify_release_stages, (tuple, list)) and self.release_stage in self.notify_release_stages)", "* password * password_confirmation \"\"\" return self._params_filters @params_filters.setter # type:", "self.app_type = app_type if app_version is not None: self.app_version =", "of an incorrect type. \"\"\" if api_key is not None:", "Global app-level Bugsnag configuration settings. \"\"\" def __init__(self): self.api_key =", "value: bool): self._auto_notify = value @property def delivery(self): \"\"\" Transport", "self._send_environment = value @property def session_endpoint(self): \"\"\" Sessions API endpoint.", "ignore def delivery(self, value): if hasattr(value, 'deliver') and callable(value.deliver): self._delivery", "ImportError: from bugsnag.utils import ThreadContextVar _request_info = ThreadContextVar('bugsnag-request', default=None) #", "def delivery(self, value): if hasattr(value, 'deliver') and callable(value.deliver): self._delivery =", "\"\"\" Transport mechanism used to make API requests. Implement the", "auto_notify(self, value: bool): self._auto_notify = value @property def delivery(self): \"\"\"", "def asynchronous(self): \"\"\" If API requests should be sent asynchronously", "self.app_version = app_version if asynchronous is not None: self.asynchronous =", "api_key=None, app_type=None, app_version=None, asynchronous=None, auto_notify=None, auto_capture_sessions=None, delivery=None, endpoint=None, hostname=None, ignore_classes=None,", "for the current application or task \"\"\" return self._app_type @app_type.setter", "self.middleware = MiddlewareStack() self.internal_middleware = MiddlewareStack() self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware) self.proxy_host =", "@delivery.setter # type: ignore def delivery(self, value): if hasattr(value, 'deliver')", "session_endpoint=None, traceback_exclude_modules=None): \"\"\" Validate and set configuration options. Will warn", "return self._app_type @app_type.setter # type: ignore @validate_str_setter def app_type(self, value:", "= value @property def app_version(self): \"\"\" Release version of the", "str): self._hostname = value @property def ignore_classes(self): \"\"\" Fully qualified", "in events. By default the following keys are filtered: *", "Will warn if an option is of an incorrect type.", "capture and send events and sessions. By default this value", "instance = _request_info.get() except LookupError: instance = None if instance", "capturing uncaught exceptions and other events. KeyboardInterrupt and Http404 exceptions", "name) @property def api_key(self): \"\"\" Unique application identifier \"\"\" return", "sessions. By default this value is None and all events", "@property def project_root(self): \"\"\" The working directory containing the application", "'deliver') and callable(value.deliver): self._delivery = value else: message = ('delivery", "send_code if send_environment is not None: self.send_environment = send_environment if", "use to deliver requests, if any \"\"\" return self._proxy_host @proxy_host.setter", "a single configuration option \"\"\" return getattr(self, name) def configure(self,", "automatically collected and attached to events \"\"\" return self._send_environment @send_environment.setter", "self.hostname = hostname if ignore_classes is not None: self.ignore_classes =", "source code. Traceback file paths which contain this prefix are", "ignore @validate_required_str_setter def session_endpoint(self, value: str): self._session_endpoint = value @property", "@notify_release_stages.setter # type: ignore @validate_iterable_setter def notify_release_stages(self, value: List[str]): self._notify_release_stages", "type. \"\"\" if api_key is not None: self.api_key = api_key", "= value else: message = ('delivery should implement Delivery interface,", "warnings from bugsnag.sessiontracker import SessionMiddleware from bugsnag.middleware import DefaultMiddleware, MiddlewareStack", "except LookupError: instance = None if instance is None: instance", "Per-request Bugsnag configuration settings. \"\"\" @classmethod def get_instance(cls): \"\"\" Get", "self._proxy_host @proxy_host.setter # type: ignore @validate_str_setter def proxy_host(self, value: str):", "a future release.') warnings.warn(message.format(type(value).__name__), RuntimeWarning) @property def endpoint(self): \"\"\" Event", "name, value) return self @property def meta_data(self) -> Any: warnings.warn('RequestConfiguration.meta_data", "ignore @validate_str_setter def app_version(self, value: str): self._app_version = value @property", "LookupError: instance = None if instance is None: instance =", "attached to events \"\"\" return self._send_environment @send_environment.setter # type: ignore", "\"KeyboardInterrupt\", \"django.http.Http404\", \"django.http.response.Http404\", ] self.endpoint = DEFAULT_ENDPOINT self.session_endpoint = DEFAULT_SESSIONS_ENDPOINT", "# type: ignore @validate_bool_setter def send_code(self, value: bool): self._send_code =", "= [\"password\", \"password_confirmation\", \"cookie\", \"authorization\"] self.ignore_classes = [ \"KeyboardInterrupt\", \"django.http.Http404\",", "not None and \\ fully_qualified_class_name(exception) in self.ignore_classes class RequestConfiguration: \"\"\"", "(create_default_delivery, DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT) from bugsnag.uwsgi import warn_if_running_uwsgi_without_threads try: from contextvars", "= {} self.request_data = {} self.environment_data = {} self.session_data =", "class RequestConfiguration: \"\"\" Per-request Bugsnag configuration settings. \"\"\" @classmethod def", "is not None: self.proxy_host = proxy_host if release_stage is not", "None: self.lib_root = lib_root if notify_release_stages is not None: self.notify_release_stages", "DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions = True self.traceback_exclude_modules = [] self.middleware = MiddlewareStack()", "paths which contain this prefix are considered a part of", "and other events. KeyboardInterrupt and Http404 exceptions are ignored by", "ignore @validate_bool_setter def auto_capture_sessions(self, value: bool): self._auto_capture_sessions = value @property", "self._app_version @app_version.setter # type: ignore @validate_str_setter def app_version(self, value: str):", "\"\"\" The host name of the proxy to use to", "password_confirmation \"\"\" return self._params_filters @params_filters.setter # type: ignore @validate_iterable_setter def", "send_environment(self): \"\"\" If the request environment should be automatically collected", "value: str): self._lib_root = value @property def notify_release_stages(self): \"\"\" A", "params_filters=None, project_root=None, proxy_host=None, release_stage=None, send_code=None, send_environment=None, session_endpoint=None, traceback_exclude_modules=None): \"\"\" Validate", "@send_environment.setter # type: ignore @validate_bool_setter def send_environment(self, value: bool): self._send_environment", "ignore @validate_str_setter def proxy_host(self, value: str): self._proxy_host = value @property", "self.send_code = True self.send_environment = False self.asynchronous = True self.delivery", "if session_endpoint is not None: self.session_endpoint = session_endpoint if traceback_exclude_modules", "str): self._app_version = value @property def asynchronous(self): \"\"\" If API", "Delivery interface to customize how requests are sent. \"\"\" return", "is not None: self.auto_notify = auto_notify if auto_capture_sessions is not", "self._hostname @hostname.setter # type: ignore @validate_str_setter def hostname(self, value: str):", "def auto_capture_sessions(self): \"\"\" If sessions should be automatically detected and", "ignore @validate_str_setter def app_type(self, value: str): self._app_type = value @property", "import DefaultMiddleware, MiddlewareStack from bugsnag.utils import (fully_qualified_class_name, validate_str_setter, validate_bool_setter, validate_iterable_setter,", "= send_code if send_environment is not None: self.send_environment = send_environment", "self.user = {} self.metadata = {} # legacy fields self.user_id", "-> bool: return self.ignore_classes is not None and \\ fully_qualified_class_name(exception)", "self.notify_release_stages = notify_release_stages if params_filters is not None: self.params_filters =", "= None self.user = {} self.metadata = {} # legacy", "Traceback file paths which contain this prefix are considered a", "names which should be ignored when capturing uncaught exceptions and", "task \"\"\" return self._app_type @app_type.setter # type: ignore @validate_str_setter def", "lib_root(self, value: str): self._lib_root = value @property def notify_release_stages(self): \"\"\"", "which are permitted to capture and send events and sessions.", "**options): \"\"\" Set one or more configuration settings. \"\"\" for", "asynchronous=None, auto_notify=None, auto_capture_sessions=None, delivery=None, endpoint=None, hostname=None, ignore_classes=None, lib_root=None, notify_release_stages=None, params_filters=None,", "if send_environment is not None: self.send_environment = send_environment if session_endpoint", "api_key is not None: self.api_key = api_key if app_type is", "value @property def asynchronous(self): \"\"\" If API requests should be", "to make file names easier to read. \"\"\" return self._lib_root", "API endpoint. Set this property if using Bugsnag On-Premise. >>>", "self._proxy_host = value @property def release_stage(self): \"\"\" The development phase", "warn if an option is of an incorrect type. \"\"\"", "DEFAULT_SESSIONS_ENDPOINT) from bugsnag.uwsgi import warn_if_running_uwsgi_without_threads try: from contextvars import ContextVar", "ignore @validate_bool_setter def auto_notify(self, value: bool): self._auto_notify = value @property", "self._params_filters @params_filters.setter # type: ignore @validate_iterable_setter def params_filters(self, value: List[str]):", "\"\"\" If sessions should be automatically detected and delivered from", "return self._notify_release_stages @notify_release_stages.setter # type: ignore @validate_iterable_setter def notify_release_stages(self, value:", "settings. \"\"\" def __init__(self): self.api_key = os.environ.get('BUGSNAG_API_KEY', None) self.release_stage =", "type: ignore @validate_bool_setter def asynchronous(self, value: bool): self._asynchronous = value", "name): \"\"\" Get a single configuration option \"\"\" warnings.warn('Using get()", "stripped from event tracebacks entirely \"\"\" return self._traceback_exclude_modules @traceback_exclude_modules.setter #", "def delivery(self): \"\"\" Transport mechanism used to make API requests.", "def endpoint(self, value: str): self._endpoint = value @property def hostname(self):", "None: self.project_root = project_root if proxy_host is not None: self.proxy_host", "bugsnag.utils import (fully_qualified_class_name, validate_str_setter, validate_bool_setter, validate_iterable_setter, validate_required_str_setter) from bugsnag.delivery import", "delivery if endpoint is not None: self.endpoint = endpoint if", "from bugsnag.sessiontracker import SessionMiddleware from bugsnag.middleware import DefaultMiddleware, MiddlewareStack from", "config.session_endpoint = 'https://sessions.bugsnag.example.co' \"\"\" return self._session_endpoint @session_endpoint.setter # type: ignore", "self._delivery @delivery.setter # type: ignore def delivery(self, value): if hasattr(value,", "@validate_str_setter def proxy_host(self, value: str): self._proxy_host = value @property def", "auto_notify(self): \"\"\" If uncaught exceptions should be automatically captured and", "If uncaught exceptions should be automatically captured and reported \"\"\"", "def traceback_exclude_modules(self, value: List[str]): self._traceback_exclude_modules = value def should_notify(self) ->", "type: ignore except ImportError: from bugsnag.utils import ThreadContextVar _request_info =", "default the following keys are filtered: * authorization * cookie", "value @property def delivery(self): \"\"\" Transport mechanism used to make", "read. \"\"\" return self._lib_root @lib_root.setter # type: ignore @validate_str_setter def", "value is automatically detected for Heroku applications and included in", "exceptions should be automatically captured and reported \"\"\" return self._auto_notify", "hostname(self): \"\"\" The host name of the application server. This", "= {} self.metadata = {} # legacy fields self.user_id =", "is not None: self.params_filters = params_filters if project_root is not", "warnings.warn('RequestConfiguration.meta_data has been renamed to ' + '\"metadata\"', DeprecationWarning) return", "def app_version(self): \"\"\" Release version of the current application \"\"\"", "list)) and self.release_stage in self.notify_release_stages) def should_ignore(self, exception: BaseException) ->", "the RequestConfiguration. \"\"\" _request_info.set(None) def __init__(self): self.context = None self.grouping_hash", "by default. \"\"\" return self._ignore_classes @ignore_classes.setter # type: ignore @validate_iterable_setter", "def hostname(self, value: str): self._hostname = value @property def ignore_classes(self):", "value: List[str]): self._params_filters = value @property def project_root(self): \"\"\" The", "{\"python\": platform.python_version()} def configure(self, api_key=None, app_type=None, app_version=None, asynchronous=None, auto_notify=None, auto_capture_sessions=None,", "self._traceback_exclude_modules = value def should_notify(self) -> bool: return self.notify_release_stages is", "prevent the values from being sent in events. By default", "will be an error in a future release.') warnings.warn(message.format(type(value).__name__), RuntimeWarning)", "not None: self.ignore_classes = ignore_classes if lib_root is not None:", "hostname is not None: self.hostname = hostname if ignore_classes is", "ignore_classes(self): \"\"\" Fully qualified class names which should be ignored", "in options.items(): setattr(self, name, value) return self @property def meta_data(self)", "None: self.auto_notify = auto_notify if auto_capture_sessions is not None: self.auto_capture_sessions", "list of filters applied to event metadata to prevent the", "bool): self._send_environment = value @property def session_endpoint(self): \"\"\" Sessions API", "to read. \"\"\" return self._lib_root @lib_root.setter # type: ignore @validate_str_setter", "from being sent in events. By default the following keys", "should_notify(self) -> bool: return self.notify_release_stages is None or \\ (isinstance(self.notify_release_stages,", "if app_type is not None: self.app_type = app_type if app_version", "device metadata. \"\"\" return self._hostname @hostname.setter # type: ignore @validate_str_setter", "instance is None: instance = RequestConfiguration() _request_info.set(instance) # type: ignore", "List[str]): self._params_filters = value @property def project_root(self): \"\"\" The working", "bool): self._asynchronous = value if value: warn_if_running_uwsgi_without_threads() @property def auto_capture_sessions(self):", "single configuration option \"\"\" warnings.warn('Using get() to retrieve a Configuration", "@validate_bool_setter def send_environment(self, value: bool): self._send_environment = value @property def", "hostname=None, ignore_classes=None, lib_root=None, notify_release_stages=None, params_filters=None, project_root=None, proxy_host=None, release_stage=None, send_code=None, send_environment=None,", "integrations \"\"\" return self._auto_capture_sessions @auto_capture_sessions.setter # type: ignore @validate_bool_setter def", "should_ignore(self, exception: BaseException) -> bool: return self.ignore_classes is not None", "ignore return instance @classmethod def clear(cls): \"\"\" Clear this thread's", "@validate_bool_setter def send_code(self, value: bool): self._send_code = value @property def", "session_endpoint is not None: self.session_endpoint = session_endpoint if traceback_exclude_modules is", "\\ fully_qualified_class_name(exception) in self.ignore_classes class RequestConfiguration: \"\"\" Per-request Bugsnag configuration", "type: ignore def delivery(self, value): if hasattr(value, 'deliver') and callable(value.deliver):", "current application or task \"\"\" return self._app_type @app_type.setter # type:", "asynchronous if auto_notify is not None: self.auto_notify = auto_notify if", "is considered out-of-project. The prefix is also stripped to make", "of the application server. This value is automatically detected for", "@auto_notify.setter # type: ignore @validate_bool_setter def auto_notify(self, value: bool): self._auto_notify", "validate_str_setter, validate_bool_setter, validate_iterable_setter, validate_required_str_setter) from bugsnag.delivery import (create_default_delivery, DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT)", "True self.traceback_exclude_modules = [] self.middleware = MiddlewareStack() self.internal_middleware = MiddlewareStack()", "def get(self, name): \"\"\" Get a single configuration option \"\"\"", "@app_type.setter # type: ignore @validate_str_setter def app_type(self, value: str): self._app_type", "def send_environment(self, value: bool): self._send_environment = value @property def session_endpoint(self):", "DEFAULT_ENDPOINT, DEFAULT_SESSIONS_ENDPOINT) from bugsnag.uwsgi import warn_if_running_uwsgi_without_threads try: from contextvars import", "session_endpoint(self): \"\"\" Sessions API endpoint. Set this property if using", "ignore @validate_str_setter def lib_root(self, value: str): self._lib_root = value @property", "] self.endpoint = DEFAULT_ENDPOINT self.session_endpoint = DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions = True", "containing the application source code. Traceback file paths which contain", "app_type(self, value: str): self._app_type = value @property def app_version(self): \"\"\"", "# type: ignore @validate_bool_setter def asynchronous(self, value: bool): self._asynchronous =", "name of the application server. This value is automatically detected", "included in event device metadata. \"\"\" return self._hostname @hostname.setter #", "name readability in traceback lines. \"\"\" return self._project_root @project_root.setter #", "deployed application. This value is used to differentiate events which", "# type: ignore def delivery(self, value): if hasattr(value, 'deliver') and", "self._asynchronous = value if value: warn_if_running_uwsgi_without_threads() @property def auto_capture_sessions(self): \"\"\"", "events. By default the following keys are filtered: * authorization", "self.context = None self.grouping_hash = None self.user = {} self.metadata", "environments. \"\"\" return self._release_stage @release_stage.setter # type: ignore @validate_str_setter def", "app_version if asynchronous is not None: self.asynchronous = asynchronous if", "application. This value is used to differentiate events which occur", "development or staging environments. \"\"\" return self._release_stage @release_stage.setter # type:", "option is of an incorrect type. \"\"\" if api_key is", "of referencing properties directly', DeprecationWarning) return getattr(self, name) @property def", "None self.extra_data = {} self.request_data = {} self.environment_data = {}", "sysconfig.get_path('purelib') self.project_root = os.getcwd() self.app_type = None self.app_version = None", "def auto_notify(self): \"\"\" If uncaught exceptions should be automatically captured", "None: self.auto_capture_sessions = auto_capture_sessions if delivery is not None: self.delivery", "and Http404 exceptions are ignored by default. \"\"\" return self._ignore_classes", "_request_info = ThreadContextVar('bugsnag-request', default=None) # type: ignore # noqa: E501", "if traceback_exclude_modules is not None: self.traceback_exclude_modules = traceback_exclude_modules return self", "ignore @validate_required_str_setter def endpoint(self, value: str): self._endpoint = value @property", "Heroku applications and included in event device metadata. \"\"\" return", "the Python library. Any traceback frame which contains lib_root as", "Bugsnag On-Premise. >>> config = Configuration() >>> config.session_endpoint = 'https://sessions.bugsnag.example.co'", "exceptions and other events. KeyboardInterrupt and Http404 exceptions are ignored", "value: bool): self._send_environment = value @property def session_endpoint(self): \"\"\" Sessions", "# type: ignore @validate_required_str_setter def session_endpoint(self, value: str): self._session_endpoint =", "The host name of the proxy to use to deliver", "lib_root if notify_release_stages is not None: self.notify_release_stages = notify_release_stages if", "is of an incorrect type. \"\"\" if api_key is not", "proxy_host is not None: self.proxy_host = proxy_host if release_stage is", "be sent asynchronously \"\"\" return self._asynchronous @asynchronous.setter # type: ignore", "configure(self, **options): \"\"\" Set one or more configuration settings. \"\"\"", "not None: self.params_filters = params_filters if project_root is not None:", "self.release_stage = os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\") self.notify_release_stages = None self.auto_notify = True", "def __init__(self): self.api_key = os.environ.get('BUGSNAG_API_KEY', None) self.release_stage = os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\")", "= None self.runtime_versions = {\"python\": platform.python_version()} def configure(self, api_key=None, app_type=None,", "the proxy to use to deliver requests, if any \"\"\"", "the application server. This value is automatically detected for Heroku", "self.send_code = send_code if send_environment is not None: self.send_environment =", "events which occur in production vs development or staging environments.", "project_root if proxy_host is not None: self.proxy_host = proxy_host if", "and \\ fully_qualified_class_name(exception) in self.ignore_classes class RequestConfiguration: \"\"\" Per-request Bugsnag", "is not None: self.app_version = app_version if asynchronous is not", "# type: ignore @validate_str_setter def release_stage(self, value: str): self._release_stage =", "to events \"\"\" return self._send_environment @send_environment.setter # type: ignore @validate_bool_setter", "if send_code is not None: self.send_code = send_code if send_environment", "None) self.release_stage = os.environ.get(\"BUGSNAG_RELEASE_STAGE\", \"production\") self.notify_release_stages = None self.auto_notify =", "development phase of the deployed application. This value is used", "@send_code.setter # type: ignore @validate_bool_setter def send_code(self, value: bool): self._send_code", "auto_capture_sessions(self, value: bool): self._auto_capture_sessions = value @property def auto_notify(self): \"\"\"", "bugsnag.uwsgi import warn_if_running_uwsgi_without_threads try: from contextvars import ContextVar _request_info =", "type: ignore @validate_iterable_setter def traceback_exclude_modules(self, value: List[str]): self._traceback_exclude_modules = value", "ignored by default. \"\"\" return self._ignore_classes @ignore_classes.setter # type: ignore", "\"\"\" return self._send_environment @send_environment.setter # type: ignore @validate_bool_setter def send_environment(self,", "contains lib_root as a prefix is considered out-of-project. The prefix", "return self._delivery @delivery.setter # type: ignore def delivery(self, value): if", "= ThreadContextVar('bugsnag-request', default=None) # type: ignore # noqa: E501 __all__", "@session_endpoint.setter # type: ignore @validate_required_str_setter def session_endpoint(self, value: str): self._session_endpoint", "* cookie * password * password_confirmation \"\"\" return self._params_filters @params_filters.setter", "= {\"python\": platform.python_version()} def configure(self, api_key=None, app_type=None, app_version=None, asynchronous=None, auto_notify=None,", "value else: message = ('delivery should implement Delivery interface, got", "\"\"\" return self._lib_root @lib_root.setter # type: ignore @validate_str_setter def lib_root(self,", "= traceback_exclude_modules return self def get(self, name): \"\"\" Get a", "Configuration() >>> config.session_endpoint = 'https://sessions.bugsnag.example.co' \"\"\" return self._session_endpoint @session_endpoint.setter #", "@property def send_code(self): \"\"\" If the source code lines immediately", "self.params_filters = [\"password\", \"password_confirmation\", \"cookie\", \"authorization\"] self.ignore_classes = [ \"KeyboardInterrupt\",", "type: ignore return instance @classmethod def clear(cls): \"\"\" Clear this", "which should be ignored when capturing uncaught exceptions and other", "By default this value is None and all events and", "\"\"\" Per-request Bugsnag configuration settings. \"\"\" @classmethod def get_instance(cls): \"\"\"", "the deployed application. This value is used to differentiate events", "List, Any, Tuple, Union import warnings from bugsnag.sessiontracker import SessionMiddleware", "# type: ignore @validate_iterable_setter def notify_release_stages(self, value: List[str]): self._notify_release_stages =", "# type: ignore @validate_str_setter def hostname(self, value: str): self._hostname =", "self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware) self.proxy_host = None if not os.getenv(\"DYNO\"): self.hostname =", "= True self.send_code = True self.send_environment = False self.asynchronous =", "ignore # noqa: E501 __all__ = ('Configuration', 'RequestConfiguration') class Configuration:", "app_type is not None: self.app_type = app_type if app_version is", "\"\"\" Get a single configuration option \"\"\" warnings.warn('Using get() to", "Configuration property is ' + 'deprecated in favor of referencing", "self.delivery = create_default_delivery() self.lib_root = sysconfig.get_path('purelib') self.project_root = os.getcwd() self.app_type", "@property def release_stage(self): \"\"\" The development phase of the deployed", "not None: self.auto_capture_sessions = auto_capture_sessions if delivery is not None:", "def send_code(self, value: bool): self._send_code = value @property def send_environment(self):", "to retrieve a Configuration property is ' + 'deprecated in", "delivery(self, value): if hasattr(value, 'deliver') and callable(value.deliver): self._delivery = value", "None: self.asynchronous = asynchronous if auto_notify is not None: self.auto_notify", "\"\"\" Global app-level Bugsnag configuration settings. \"\"\" def __init__(self): self.api_key", "set configuration options. Will warn if an option is of", "'RequestConfiguration') class Configuration: \"\"\" Global app-level Bugsnag configuration settings. \"\"\"", "not None: self.traceback_exclude_modules = traceback_exclude_modules return self def get(self, name):", "is not None: self.api_key = api_key if app_type is not", "project_root is not None: self.project_root = project_root if proxy_host is", "return self._app_version @app_version.setter # type: ignore @validate_str_setter def app_version(self, value:", "str): self._proxy_host = value @property def release_stage(self): \"\"\" The development", "\"\"\" return self._auto_capture_sessions @auto_capture_sessions.setter # type: ignore @validate_bool_setter def auto_capture_sessions(self,", "value @property def ignore_classes(self): \"\"\" Fully qualified class names which", "phase of the deployed application. This value is used to", "\"\"\" if api_key is not None: self.api_key = api_key if", "@hostname.setter # type: ignore @validate_str_setter def hostname(self, value: str): self._hostname", "= create_default_delivery() self.lib_root = sysconfig.get_path('purelib') self.project_root = os.getcwd() self.app_type =", "def release_stage(self): \"\"\" The development phase of the deployed application.", "# legacy fields self.user_id = None self.extra_data = {} self.request_data", "type: ignore @validate_iterable_setter def notify_release_stages(self, value: List[str]): self._notify_release_stages = value", "self._app_type @app_type.setter # type: ignore @validate_str_setter def app_type(self, value: str):", "working directory containing the application source code. Traceback file paths", "app_type=None, app_version=None, asynchronous=None, auto_notify=None, auto_capture_sessions=None, delivery=None, endpoint=None, hostname=None, ignore_classes=None, lib_root=None,", "the project. This prefix is also stripped to increase file", "if asynchronous is not None: self.asynchronous = asynchronous if auto_notify", "@property def send_environment(self): \"\"\" If the request environment should be", "@asynchronous.setter # type: ignore @validate_bool_setter def asynchronous(self, value: bool): self._asynchronous", "\"\"\" If the source code lines immediately surrounding traceback locations", "socket import sysconfig from typing import List, Any, Tuple, Union", "setattr(self, name, value) return self @property def meta_data(self) -> Any:", "self._app_version = value @property def asynchronous(self): \"\"\" If API requests", "\"\"\" return self._release_stage @release_stage.setter # type: ignore @validate_str_setter def release_stage(self,", "are sent. \"\"\" return self._delivery @delivery.setter # type: ignore def", "not None: self.release_stage = release_stage if send_code is not None:", "bugsnag.middleware import DefaultMiddleware, MiddlewareStack from bugsnag.utils import (fully_qualified_class_name, validate_str_setter, validate_bool_setter,", "to increase file name readability in traceback lines. \"\"\" return", "instance = RequestConfiguration() _request_info.set(instance) # type: ignore return instance @classmethod", "source code lines immediately surrounding traceback locations should be sent", "options. Will warn if an option is of an incorrect", "traceback locations should be sent with events \"\"\" return self._send_code", "is not None: self.notify_release_stages = notify_release_stages if params_filters is not", "not os.getenv(\"DYNO\"): self.hostname = socket.gethostname() else: self.hostname = None self.runtime_versions", "and attached to events \"\"\" return self._send_environment @send_environment.setter # type:", "collected and attached to events \"\"\" return self._send_environment @send_environment.setter #", "os import platform import socket import sysconfig from typing import", "ignored when capturing uncaught exceptions and other events. KeyboardInterrupt and", "applications and included in event device metadata. \"\"\" return self._hostname", "sent with events \"\"\" return self._send_code @send_code.setter # type: ignore", "('delivery should implement Delivery interface, got ' + '{0}. This", "def configure(self, **options): \"\"\" Set one or more configuration settings.", "frame which contains lib_root as a prefix is considered out-of-project.", "= {} def get(self, name) -> Any: \"\"\" Get a", "configuration settings. \"\"\" for name, value in options.items(): setattr(self, name,", "also stripped to make file names easier to read. \"\"\"", "None: self.notify_release_stages = notify_release_stages if params_filters is not None: self.params_filters", "@validate_str_setter def release_stage(self, value: str): self._release_stage = value @property def", "project_root(self, value: str): self._project_root = value @property def proxy_host(self): \"\"\"", "\"\"\" return self._app_version @app_version.setter # type: ignore @validate_str_setter def app_version(self,", "# type: ignore @validate_bool_setter def auto_capture_sessions(self, value: bool): self._auto_capture_sessions =", "= [] self.middleware = MiddlewareStack() self.internal_middleware = MiddlewareStack() self.internal_middleware.append(DefaultMiddleware) self.internal_middleware.append(SessionMiddleware)", "lines. \"\"\" return self._project_root @project_root.setter # type: ignore @validate_str_setter def", "\"\"\" Unique application identifier \"\"\" return self._api_key @api_key.setter # type:", "\"\"\" return self._proxy_host @proxy_host.setter # type: ignore @validate_str_setter def proxy_host(self,", "entirely \"\"\" return self._traceback_exclude_modules @traceback_exclude_modules.setter # type: ignore @validate_iterable_setter def", "BaseException) -> bool: return self.ignore_classes is not None and \\", "A list of filters applied to event metadata to prevent", "self.auto_capture_sessions = True self.traceback_exclude_modules = [] self.middleware = MiddlewareStack() self.internal_middleware", "if auto_capture_sessions is not None: self.auto_capture_sessions = auto_capture_sessions if delivery", "warnings.warn('Using get() to retrieve a Configuration property is ' +", "platform.python_version()} def configure(self, api_key=None, app_type=None, app_version=None, asynchronous=None, auto_notify=None, auto_capture_sessions=None, delivery=None,", "Modules which should be stripped from event tracebacks entirely \"\"\"", "# type: ignore @validate_iterable_setter def traceback_exclude_modules(self, value: List[str]): self._traceback_exclude_modules =", "Bugsnag On-Premise. >>> config = Configuration() >>> config.endpoint = 'https://notify.bugsnag.example.co'", "app_version(self, value: str): self._app_version = value @property def asynchronous(self): \"\"\"", "self.asynchronous = asynchronous if auto_notify is not None: self.auto_notify =", "an incorrect type. \"\"\" if api_key is not None: self.api_key", "Event API endpoint. Set this property if using Bugsnag On-Premise.", "used to make API requests. Implement the Delivery interface to", "self._release_stage = value @property def send_code(self): \"\"\" If the source", ">>> config = Configuration() >>> config.endpoint = 'https://notify.bugsnag.example.co' \"\"\" return", "+ 'deprecated in favor of referencing properties directly', DeprecationWarning) return", "@property def auto_notify(self): \"\"\" If uncaught exceptions should be automatically", "Python library. Any traceback frame which contains lib_root as a", "not None: self.auto_notify = auto_notify if auto_capture_sessions is not None:", "str): self._lib_root = value @property def notify_release_stages(self): \"\"\" A list", "= send_environment if session_endpoint is not None: self.session_endpoint = session_endpoint", "event tracebacks entirely \"\"\" return self._traceback_exclude_modules @traceback_exclude_modules.setter # type: ignore", "return self._asynchronous @asynchronous.setter # type: ignore @validate_bool_setter def asynchronous(self, value:", "release_stage if send_code is not None: self.send_code = send_code if", "self.endpoint = endpoint if hostname is not None: self.hostname =", "value @property def hostname(self): \"\"\" The host name of the", "This prefix is also stripped to increase file name readability", "None: self.release_stage = release_stage if send_code is not None: self.send_code", "notify_release_stages=None, params_filters=None, project_root=None, proxy_host=None, release_stage=None, send_code=None, send_environment=None, session_endpoint=None, traceback_exclude_modules=None): \"\"\"", "def should_notify(self) -> bool: return self.notify_release_stages is None or \\", "auto_notify is not None: self.auto_notify = auto_notify if auto_capture_sessions is", "auto_capture_sessions is not None: self.auto_capture_sessions = auto_capture_sessions if delivery is", "from bugsnag.middleware import DefaultMiddleware, MiddlewareStack from bugsnag.utils import (fully_qualified_class_name, validate_str_setter,", "send_code(self, value: bool): self._send_code = value @property def send_environment(self): \"\"\"", "Tuple, Union import warnings from bugsnag.sessiontracker import SessionMiddleware from bugsnag.middleware", "= DEFAULT_SESSIONS_ENDPOINT self.auto_capture_sessions = True self.traceback_exclude_modules = [] self.middleware =", "Tuple[str]]): self._ignore_classes = value @property def lib_root(self): \"\"\" The path", "try: instance = _request_info.get() except LookupError: instance = None if", "{} def get(self, name) -> Any: \"\"\" Get a single", "On-Premise. >>> config = Configuration() >>> config.session_endpoint = 'https://sessions.bugsnag.example.co' \"\"\"", "{} self.request_data = {} self.environment_data = {} self.session_data = {}", "@property def auto_capture_sessions(self): \"\"\" If sessions should be automatically detected", "\"\"\" return self._app_type @app_type.setter # type: ignore @validate_str_setter def app_type(self,", "self._ignore_classes @ignore_classes.setter # type: ignore @validate_iterable_setter def ignore_classes(self, value: Union[List[str],", "RequestConfiguration: \"\"\" Per-request Bugsnag configuration settings. \"\"\" @classmethod def get_instance(cls):", "None self.params_filters = [\"password\", \"password_confirmation\", \"cookie\", \"authorization\"] self.ignore_classes = [", "= value @property def notify_release_stages(self): \"\"\" A list of release_stage", "events and sessions are delivered. \"\"\" return self._notify_release_stages @notify_release_stages.setter #", "should implement Delivery interface, got ' + '{0}. This will", "# type: ignore @validate_bool_setter def send_environment(self, value: bool): self._send_environment =", "release_stage is not None: self.release_stage = release_stage if send_code is", "def proxy_host(self, value: str): self._proxy_host = value @property def release_stage(self):", "ContextVar _request_info = ContextVar('bugsnag-request', default=None) # type: ignore except ImportError:", "readability in traceback lines. \"\"\" return self._project_root @project_root.setter # type:", "@validate_required_str_setter def session_endpoint(self, value: str): self._session_endpoint = value @property def", "lines immediately surrounding traceback locations should be sent with events", "or \\ (isinstance(self.notify_release_stages, (tuple, list)) and self.release_stage in self.notify_release_stages) def" ]
[ "with global_logger(logger): if type in (None, \"ADDED\", \"MODIFIED\"): reconcile_secret(name, namespace,", "if now match will inject the secret. with global_logger(logger): if", "or modified later, do a full reconcilation to # ensure", "will inject the secret. with global_logger(logger): if type in (None,", "**_): obj = event[\"object\"] namespace = obj[\"metadata\"][\"namespace\"] name = obj[\"metadata\"][\"name\"]", "now match will inject the secret. with global_logger(logger): if type", "is added or modified later, do a full reconcilation to", "being None, the # secret is added or modified later,", "from .functions import global_logger, reconcile_secret @kopf.on.event(\"\", \"v1\", \"secrets\") def injector_secret_event(type,", "reconcilation to # ensure that if now match will inject", "the secret. with global_logger(logger): if type in (None, \"ADDED\", \"MODIFIED\"):", "do a full reconcilation to # ensure that if now", "inject the secret. with global_logger(logger): if type in (None, \"ADDED\",", "name = obj[\"metadata\"][\"name\"] # If secret already exists, indicated by", "kopf from .functions import global_logger, reconcile_secret @kopf.on.event(\"\", \"v1\", \"secrets\") def", "global_logger, reconcile_secret @kopf.on.event(\"\", \"v1\", \"secrets\") def injector_secret_event(type, event, logger, **_):", ".functions import global_logger, reconcile_secret @kopf.on.event(\"\", \"v1\", \"secrets\") def injector_secret_event(type, event,", "import kopf from .functions import global_logger, reconcile_secret @kopf.on.event(\"\", \"v1\", \"secrets\")", "# secret is added or modified later, do a full", "secret already exists, indicated by type being None, the #", "obj[\"metadata\"][\"name\"] # If secret already exists, indicated by type being", "added or modified later, do a full reconcilation to #", "modified later, do a full reconcilation to # ensure that", "event, logger, **_): obj = event[\"object\"] namespace = obj[\"metadata\"][\"namespace\"] name", "obj = event[\"object\"] namespace = obj[\"metadata\"][\"namespace\"] name = obj[\"metadata\"][\"name\"] #", "logger, **_): obj = event[\"object\"] namespace = obj[\"metadata\"][\"namespace\"] name =", "event[\"object\"] namespace = obj[\"metadata\"][\"namespace\"] name = obj[\"metadata\"][\"name\"] # If secret", "later, do a full reconcilation to # ensure that if", "= obj[\"metadata\"][\"namespace\"] name = obj[\"metadata\"][\"name\"] # If secret already exists,", "obj[\"metadata\"][\"namespace\"] name = obj[\"metadata\"][\"name\"] # If secret already exists, indicated", "ensure that if now match will inject the secret. with", "that if now match will inject the secret. with global_logger(logger):", "exists, indicated by type being None, the # secret is", "secret. with global_logger(logger): if type in (None, \"ADDED\", \"MODIFIED\"): reconcile_secret(name,", "import global_logger, reconcile_secret @kopf.on.event(\"\", \"v1\", \"secrets\") def injector_secret_event(type, event, logger,", "@kopf.on.event(\"\", \"v1\", \"secrets\") def injector_secret_event(type, event, logger, **_): obj =", "reconcile_secret @kopf.on.event(\"\", \"v1\", \"secrets\") def injector_secret_event(type, event, logger, **_): obj", "by type being None, the # secret is added or", "indicated by type being None, the # secret is added", "already exists, indicated by type being None, the # secret", "injector_secret_event(type, event, logger, **_): obj = event[\"object\"] namespace = obj[\"metadata\"][\"namespace\"]", "to # ensure that if now match will inject the", "match will inject the secret. with global_logger(logger): if type in", "namespace = obj[\"metadata\"][\"namespace\"] name = obj[\"metadata\"][\"name\"] # If secret already", "If secret already exists, indicated by type being None, the", "the # secret is added or modified later, do a", "def injector_secret_event(type, event, logger, **_): obj = event[\"object\"] namespace =", "a full reconcilation to # ensure that if now match", "= event[\"object\"] namespace = obj[\"metadata\"][\"namespace\"] name = obj[\"metadata\"][\"name\"] # If", "\"v1\", \"secrets\") def injector_secret_event(type, event, logger, **_): obj = event[\"object\"]", "secret is added or modified later, do a full reconcilation", "full reconcilation to # ensure that if now match will", "type being None, the # secret is added or modified", "= obj[\"metadata\"][\"name\"] # If secret already exists, indicated by type", "# ensure that if now match will inject the secret.", "# If secret already exists, indicated by type being None,", "None, the # secret is added or modified later, do", "global_logger(logger): if type in (None, \"ADDED\", \"MODIFIED\"): reconcile_secret(name, namespace, obj)", "\"secrets\") def injector_secret_event(type, event, logger, **_): obj = event[\"object\"] namespace" ]
[ "True) else: return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True) def reduceRegion(image): theReducer = getReducer(reducer)", "name } ########## ee.Image ########## def imageToMapId(image, visParams): eeImage =", "endDate) eeCollection = eeCollection.filter(eeFilterDate) reducedImage = ee.Image(reduceIC(eeCollection, reducer)) return imageToMapId(reducedImage,", "matchID, visParams): fc = ee.FeatureCollection(featureCollection) single = fc.filter(ee.Filter.equals(field, matchID)) mapId", "'(nir - red) / (nir + red)', 'EVI': '2.5 *", "f2017s2 = sentinel2.filterDate(startDate, endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) m2017s2 = f2017s2.map(cloudScoreS2)", ".getInfo() ########## Degradation########## def getDegradationTileUrlByDateS1(geometry, date, visParams): imDate = datetime.datetime.strptime(date,", "[0.8, 0.6])) def cloudScoreS2(img): rescale = img.divide(10000) score = cloudScore(rescale).multiply(100).rename('cloudscore')", "= getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry}) start =", "pixel. arrayImage2D = img.select(bands).toArray().toArray(1) # apply correction factors and reproject", "eeFirstImage.updateMask(mask) values = imageToMapId(masked, visParams) else: values = imageToMapId(eeFirstImage, visParams)", "colorPalette} eviImage = ee.Image(eeCollection.map(calcNDWI).mean()) return imageToMapId(eviImage, visParams) def filteredImageByIndexToMapId(startDate, endDate,", "= image.reduceRegion( theReducer, geometry=geometry, scale=scale, maxPixels=1e6) return ee.Feature(None, { 'index':", "eviImage = ee.Image(eeCollection.map(calcNDVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVIToMapId(startDate, endDate): def", "img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1))) score = score.min(blue_rescale) # Clouds are reasonably bright", "ee.Reducer.sum() else: return ee.Reducer.median() def reduceIC(imageCollection, reducer): reducerName = reducer.lower()", "endDate): eeCollection = eeCollection.filterDate(startDate, endDate) eeCollection.filterMetadata( 'CLOUD_COVER', 'less_than', metadataCloudCoverMax )", "in the blue band. blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1))) score =", "return imageCollection.median() def safeParseJSON(val): if isinstance(val, dict): return val else:", "-1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDWI).mean()) return imageToMapId(eviImage, visParams) def", "return values ########## ee.FeatureCollection ########## def getFeatureCollectionTileUrl(featureCollection, field, matchID, visParams):", "'2.5 * (nir - red) / (nir + 2.4 *", "= {'bands': ['VV', 'VH', 'ratioVVVH'], 'min': [-15, -25, .40], 'max':", "'min'): return ee.Reducer.min() elif (reducerName == 'max'): return ee.Reducer.max() elif", "geometry = ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) collection = ee.ImageCollection([])", "endDate): skipCloudMask = False eeCollection = ee.ImageCollection(assetId) lowerAsset = assetId.lower()", "- datetime.timedelta(days=1) aftDate = imDate + datetime.timedelta(days=1) if isinstance(geometry[0], list):", "= img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start') indexImage = ee.Image().set(", "score = score.min(rescale(img, 'img.B4 + img.B3 + img.B2', [0.2, 0.8]))", "band. blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1))) score = score.min(blue_rescale) # Clouds", "eeMosaicImage = ee.Algorithms.Landsat.simpleComposite( eeCollection, simpleCompositeVariable, 10, 40, True ) return", ".40], 'max': [0, -10, 1], 'gamma': 1.6} indexImage = ee.Image().set(", "startDate and endDate: return ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart, True) else: return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart,", "popDict.get('population-count').getInfo() pop = int(pop) return { 'minElev': minElev, 'maxElev': maxElev,", "'shadow', 'cirrus']).Not()) def toIndex(image): bands = bandsByCollection[name] return image.expression(indexes[indexName], {", "'LANDSAT/LT04/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T2_TOA': ['B1', 'B2',", "= imageToMapId(masked, visParams) else: values = imageToMapId(eeFirstImage, visParams) except EEException", "+ swir1)', 'NDWI': '(green - nir) / (green + nir)',", "using angle band vv = img.select('VV') vh = img.select('VH') vv_vh", "indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage def getClipped(image):", "# Clouds are reasonably bright in all infrared bands. infrared", "= ee.ImageCollection(assetId) if (startDate and endDate): eeFilterDate = ee.Filter.date(startDate, endDate)", "= img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1))) score = score.min(blue_rescale) # Clouds are reasonably", "end).first() selectedImage = ee.Image(selectedImage) mapparams = selectedImage.getMapId(visParams) return mapparams['tile_fetcher'].url_format def", "if indexName != None: indexCollection = ee.ImageCollection(assetId).filterDate( startDate, endDate).select(indexName) else:", "'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDVI).mean()) return", "return keep.addBands(componentsImage) def getLandSatMergedCollection(): sensorBandDictLandsatTOA = {'L8': [1, 2, 3,", "\"end\": endDate.strftime('%Y-%m-%d'), \"targetBands\": ['RED', 'GREEN', 'BLUE', 'SWIR1', 'NIR'], \"region\": geometry,", "= ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start')", "(i.nir - i.red) / (i.nir + 6.0 * i.red -", "def s2MaskClouds(img): qa = img.select('QA60') # Bits 10 and 11", "= ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) collection = ee.ImageCollection([]) for", "ine: imageToMapId(eeFirstImage, visParams) return values ########## ee.FeatureCollection ########## def getFeatureCollectionTileUrl(featureCollection,", "'NIR'], \"region\": geometry, \"sensors\": {\"l4\": False, \"l5\": False, \"l7\": False,", "score = score.min(temp_rescale) # However, clouds are not snow. ndsi", "ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8))) score = score.min(ndsi_rescale).multiply(100).byte() mask = score.lt(cloudThresh).rename(['cloudMask']) img =", "imageToMapId(eviImage, visParams) def filteredImageEVI2ToMapId(startDate, endDate): def calcEVI2(img): return img.expression('2.5 *", "list): geometry = ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) sentinel1Data =", "# apply correction factors and reproject array to geographic image", "imageToMapId(eeMosaicImage, visParams) def filteredSentinelComposite(visParams, startDate, endDate, metadataCloudCoverMax): def cloudScore(img): def", "ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams = unmasked.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPoint(geometry, start, end,", "'B7'] } indexes = { 'NDVI': '(nir - red) /", "image.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage def", "isinstance(coords[0], list) or isinstance(coords[0], tuple): geometry = ee.Geometry.Polygon(coords) else: geometry", "date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") befDate = imDate -", ".select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds) le7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\", "if (startDate and endDate): eeCollection = eeCollection.filterDate(startDate, endDate) eeCollection.filterMetadata( 'CLOUD_COVER',", "Series ########## def getTimeSeriesByCollectionAndIndex(assetId, indexName, scale, coords, startDate, endDate, reducer):", "11 are clouds and cirrus, respectively. cloudBitMask = int(math.pow(2, 10))", "'mode'): return imageCollection.mode() elif (reducerName == 'mosaic'): return imageCollection.mosaic() elif", "\\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds) le7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA')", "'red', 'nir', 'swir1', 'swir2'] # linear regression coefficients for adjustment", "== 'mosaic'): return imageCollection.mosaic() elif (reducerName == 'first'): return imageCollection.first()", "10, 12]} bandNamesLandsatTOA = ['blue', 'green', 'red', 'nir', 'swir1', 'temp',", "5, 6], 'L4': [0, 1, 2, 3, 4, 5, 6],", "'badPixels': 15, 'cloud': 16, 'shadow': 256, 'snow': 1024, 'cirrus': 4096", "+ red + 0.5)) * (1 + 0.5)' } def", "def getIndex(image): theReducer = getReducer(reducer) if indexName != None: indexValue", "int(math.pow(2, 11)) # clear if both flags set to zero.", "ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": start,", "theReducer = getReducer(reducer) if indexName != None: indexValue = image.reduceRegion(", "ee.ImageCollection('COPERNICUS/S2') \\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) \\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA) \\ .map(bandPassAdjustment)", "3, 4, 5, 7], 'L5': [0, 1, 2, 3, 4,", "ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage lsd = sentinel1Data.map(myimageMapper, True)", "startDate, endDate): skipCloudMask = False eeCollection = ee.ImageCollection(assetId) lowerAsset =", "else: try: return json.loads(val) except Exception as e: try: return", "bias = ee.Array([[-0.00411], [-0.00093], [0.00094], [-0.00029], [-0.00015], [-0.00097]]) # Make", "'temp', 'swir2'] metadataCloudCoverMax = 100 lt4 = ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\ .filterMetadata('CLOUD_COVER',", "ee.Image(eeCollection.map(calcNDVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVIToMapId(startDate, endDate): def calcEVI(img): return", "-1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI2).mean()) return imageToMapId(eviImage, visParams) def", "int(math.pow(2, 10)) cirrusBitMask = int(math.pow(2, 11)) # clear if both", "= eeCollection.filter(eeFilterDate) reducedImage = ee.Image(reduceIC(eeCollection, reducer)) return imageToMapId(reducedImage, visParams) #", "img.addBands(score) sentinel2 = ee.ImageCollection('COPERNICUS/S2') f2017s2 = sentinel2.filterDate(startDate, endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE', 'less_than',", "= None if isinstance(coords[0], list): geometry = ee.Geometry.Polygon(coords) else: geometry", "= reducer.lower() if(reducerName == 'min'): return ee.Reducer.min() elif (reducerName ==", "+ 1)', {'i': img}).rename(['EVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate,", "img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start')) def bandPassAdjustment(img): keep = img.select(['temp']) bands = ['blue',", "temperature. temp_rescale = img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300))) score = score.min(temp_rescale) # However,", "elev.reduceRegion( ee.Reducer.minMax(), extentGeom, 1000, maxPixels=500000000) minElev = minmaxElev.get('elevation_min').getInfo() maxElev =", "False, \"l8\": True} }) selectedImage = landsatData.first() unmasked = ee.Image(selectedImage).multiply(10000).toInt16().unmask()", "filteredImageEVIToMapId(startDate, endDate) elif (lowerIndex == 'evi2'): return filteredImageEVI2ToMapId(startDate, endDate) elif", "\\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '505050,E8E8E8,00FF33,003300'", "== 'ndwi'): return filteredImageNDWIToMapId(startDate, endDate) def filteredImageCompositeToMapId(assetId, visParams, startDate, endDate,", "'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDWI).mean()) return", "again? def firstCloudFreeImageInMosaicToMapId(assetId, visParams, startDate, endDate): skipCloudMask = False eeCollection", "= ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID', sID)) mask = scored.select(['cloud']).lte(20) masked = eeFirstImage.updateMask(mask)", "os.path.exists(ee_key_path): credentials = ee.ServiceAccountCredentials(ee_account, ee_key_path) ee.Initialize(credentials) else: ee.Initialize() except Exception", "\"l7\": True, \"l8\": True} }) def myImageMapper(img): theReducer = ee.Reducer.mean()", "[image.get('system:time_start'), reduced.get('index')] }) geometry = None if isinstance(coords[0], list) or", "return indexImage lsd = sentinel1Data.map(myimageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values", "reduceIC(imageCollection, reducer): reducerName = reducer.lower() if(reducerName == 'min'): return imageCollection.min()", "return { 'bands': eeImage.bandNames().getInfo(), 'imageName': name } ########## ee.Image ##########", "if indexName != None: indexValue = image.reduceRegion( theReducer, geometry, scale).get(indexName)", "= eeCollection.filter(eeFilterDate) eeFirstImage = ee.Image(eeCollection.mosaic()) try: if(skipCloudMask == False): sID", "minmaxElev = elev.reduceRegion( ee.Reducer.minMax(), extentGeom, 1000, maxPixels=500000000) minElev = minmaxElev.get('elevation_min').getInfo()", "= imDate - datetime.timedelta(days=1) aftDate = imDate + datetime.timedelta(days=1) if", "True, \"l7\": True, \"l8\": True} }) def myImageMapper(img): theReducer =", "6.0 * red - 7.5 * blue + 1)', 'EVI2':", "ee_account and ee_key_path and os.path.exists(ee_key_path): credentials = ee.ServiceAccountCredentials(ee_account, ee_key_path) ee.Initialize(credentials)", "return ee.Feature(None, { 'index': reduced.get('index'), 'timeIndex': [image.get('system:time_start'), reduced.get('index')] }) geometry", "########## def imageToMapId(image, visParams): eeImage = ee.Image(image) mapId = eeImage.getMapId(visParams)", "in lowerAsset): skipCloudMask = False elif (\"lt5\" in lowerAsset): skipCloudMask", "blue + 1)', 'EVI2': '2.5 * (nir - red) /", "try: if ee_account and ee_key_path and os.path.exists(ee_key_path): credentials = ee.ServiceAccountCredentials(ee_account,", "scale=scale, maxPixels=1e6) return ee.Feature(None, { 'index': reduced.get('index'), 'timeIndex': [image.get('system:time_start'), reduced.get('index')]", "myImageMapper(img): theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry, 30) date", "score.min(rescale(img, 'img.B4 + img.B3 + img.B2', [0.2, 0.8])) score =", "= eeFirstImage.updateMask(mask) values = imageToMapId(masked, visParams) else: values = imageToMapId(eeFirstImage,", "0, 2).getMapId(visParams) return mapId['tile_fetcher'].url_format ########## Pre defined ee.ImageCollection ########## #", "[0, -10, 1], 'gamma': 1.6} indexImage = ee.Image().set( 'indexValue', [ee.Number(date),", "eeCollection = eeCollection.filter(eeFilterDate) eeFirstImage = ee.Image(eeCollection.mosaic()) try: if(skipCloudMask == False):", "imageCollectionToMapId(assetId, visParams, reducer, startDate, endDate): eeCollection = ee.ImageCollection(assetId) if (startDate", "i.red) / (i.nir + i.red)', {'i': img}).rename(['NDVI']) \\ .set('system:time_start', img.get('system:time_start'))", "return toIndex(image).set('system:time_start', time) # if startDate and endDate: return ee.ImageCollection(name).filterDate(startDate,", "indexes = { 'NDVI': '(nir - red) / (nir +", "getReducer(reducer) reduced = image.reduceRegion( theReducer, geometry=geometry, scale=scale, maxPixels=1e6) return ee.Feature(None,", "= image.reduceRegion(theReducer, geometry, scale) date = image.get('system:time_start') indexImage = ee.Image().set(", "sentinel2.filterDate(startDate, endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) m2017s2 = f2017s2.map(cloudScoreS2) m2017s3 =", "reducer, startDate, endDate): eeCollection = ee.ImageCollection(assetId) if (startDate and endDate):", "'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI).mean()) return imageToMapId(eviImage, visParams)", "= aftDate.strftime('%Y-%m-%d') selectedImage = sentinel1Data.filterDate(start, end).first() selectedImage = ee.Image(selectedImage) mapparams", "extentGeom = ee.Geometry.Polygon(extent) elev = ee.Image('USGS/GTOPO30') minmaxElev = elev.reduceRegion( ee.Reducer.minMax(),", "2, 3, 7, 11, 10, 12]} bandNamesLandsatTOA = ['blue', 'green',", "def reduceRegion(image): theReducer = getReducer(reducer) reduced = image.reduceRegion( theReducer, geometry=geometry,", "= ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds) lt5", "image.select(bands[5]), }).clamp(-1, 1).rename(['index']) def toIndexWithTimeStart(image): time = image.get('system:time_start') image =", "img.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue] ) return indexImage", "/ (nir + red + 0.5)) * (1 + 0.5)'", "'green': image.select(bands[1]), 'red': image.select(bands[2]), 'nir': image.select(bands[3]), 'swir1': image.select(bands[4]), 'swir2': image.select(bands[5]),", "'gamma': 1.6} indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage", "[-0.00093], [0.00094], [-0.00029], [-0.00015], [-0.00097]]) # Make an Array Image,", "= sentinel1Data.filterDate(start, end).first() selectedImage = ee.Image(selectedImage) mapparams = selectedImage.getMapId(visParams) return", "- i.red) / (i.nir + i.red)', {'i': img}).rename(['NDVI']) \\ .set('system:time_start',", "} def create(name): def maskClouds(image): def isSet(types): \"\"\" https://landsat.usgs.gov/collectionqualityband \"\"\"", "maxPixels=500000000) pop = popDict.get('population-count').getInfo() pop = int(pop) return { 'minElev':", "= vh.divide(vv).rename('VH/VV') return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1 = sentinel1.filterDate(startDate,", "imageCollection.min() elif (reducerName == 'max'): return imageCollection.max() elif (reducerName ==", "startDate, endDate, reducer): geometry = None indexCollection = None if", "visParams) def filteredImageEVI2ToMapId(startDate, endDate): def calcEVI2(img): return img.expression('2.5 * (i.nir", "= ee.ImageCollection(assetId) lowerAsset = assetId.lower() if(\"b2\" not in visParams[\"bands\"].lower()): skipCloudMask", "scale, coords, startDate, endDate, reducer): geometry = None indexCollection =", "Exception as e: return {} ########## Helper routes ########## def", "'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDVI).mean()) return imageToMapId(eviImage, visParams)", "= 100 lt4 = ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\", "eviImage = ee.Image(eeCollection.map(calcNDMI).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDWIToMapId(startDate, endDate): def", "else: geometry = ee.Geometry.Point(geometry) sentinel1Data = getS1({ \"targetBands\": ['VV', 'VH',", "deduce whats being returned. return { 'url': mapId['tile_fetcher'].url_format } ##########", "mapparams = selectedImage.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPointS1(geometry, start, end): if", "ee.ImageCollection(name).first() else: eeImage = ee.Image(name) return { 'bands': eeImage.bandNames().getInfo(), 'imageName':", "[0.982], [1.001], [1.001], [0.996]]) bias = ee.Array([[-0.00411], [-0.00093], [0.00094], [-0.00029],", "ndsi = img.normalizedDifference(['green', 'swir1']) ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8))) score =", "endDate) eeCollection.filterMetadata( 'CLOUD_COVER', 'less_than', metadataCloudCoverMax ) eeMosaicImage = ee.Algorithms.Landsat.simpleComposite( eeCollection,", "def calcNDWI(img): return img.expression('(i.green - i.nir) / (i.green + i.nir)',", "geometry = ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) landsatData = getLandsat({", "calcEVI2(img): return img.expression('2.5 * (i.nir - i.red) / (i.nir +", "elif (reducerName == 'max'): return imageCollection.max() elif (reducerName == 'mean'):", "imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") befDate = imDate - datetime.timedelta(days=1) aftDate", "== 'min'): return imageCollection.min() elif (reducerName == 'max'): return imageCollection.max()", "(nir + swir1)', 'NDWI': '(green - nir) / (green +", "* (i.nir - i.red) / (i.nir + 2.4 * i.red", "endDate, metadataCloudCoverMax, simpleCompositeVariable): eeCollection = ee.ImageCollection(assetId) if (startDate and endDate):", "\"l5\": True, \"l7\": True, \"l8\": True} }) def myImageMapper(img): theReducer", "6], 'L7': [0, 1, 2, 3, 4, 5, 7], 'L5':", "vh = img.select('VH') vv_vh = vv.divide(vh).rename('VV/VH') vh_vv = vh.divide(vv).rename('VH/VV') return", "indexValue]) return indexImage lsd = sentinel1Data.map(myimageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue')", "5, 6], 'S2': [1, 2, 3, 7, 11, 10, 12]}", "'GREEN', 'BLUE', 'SWIR1', 'NIR'], \"region\": geometry, \"sensors\": {\"l4\": False, \"l5\":", "rescale(img, 'img.B8 + img.B11 + img.B12', [0.3, 0.8])) ndsi =", "def getDegradationPlotsByPoint(geometry, start, end, band): if isinstance(geometry[0], list): geometry =", "ee.Image(eeCollection.map(calcEVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVI2ToMapId(startDate, endDate): def calcEVI2(img): return", "- datetime.timedelta(days=1) endDate = imDate + datetime.timedelta(days=1) if isinstance(geometry[0], list):", "+ img.B2', [0.2, 0.8])) score = score.min( rescale(img, 'img.B8 +", "= sentinel1Data.map(myimageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return", "factors and reproject array to geographic image componentsImage = ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias))", "are reasonably bright in the blue band. blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide(", "to deduce whats being returned. return { 'url': mapId['tile_fetcher'].url_format }", "selectedImage = sentinel1Data.filterDate(start, end).first() selectedImage = ee.Image(selectedImage) mapparams = selectedImage.getMapId(visParams)", "['RED', 'GREEN', 'BLUE', 'SWIR1', 'NIR'], \"region\": geometry, \"sensors\": {\"l4\": False,", "single = fc.filter(ee.Filter.equals(field, matchID)) mapId = ee.Image().paint(single, 0, 2).getMapId(visParams) return", "= ee.Image(eeCollection.map(calcEVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVI2ToMapId(startDate, endDate): def calcEVI2(img):", "img.select('QA60') # Bits 10 and 11 are clouds and cirrus,", "in visParams[\"bands\"].lower()): skipCloudMask = True elif (\"lc8\" in lowerAsset): skipCloudMask", "snow. ndsi = img.normalizedDifference(['green', 'swir1']) ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8))) score", "== 'min'): return ee.Reducer.min() elif (reducerName == 'max'): return ee.Reducer.max()", "return imageCollection.mean() elif (reducerName == 'mode'): return imageCollection.mode() elif (reducerName", "= img.get('system:time_start') visParams = {'bands': ['VV', 'VH', 'ratioVVVH'], 'min': [-15,", "'cloud': 16, 'shadow': 256, 'snow': 1024, 'cirrus': 4096 } anySet", "def filteredSentinelSARComposite(visParams, startDate, endDate): def toNatural(img): return ee.Image(10).pow(img.divide(10)) def addRatioBands(img):", "metadataCloudCoverMax = 100 lt4 = ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax)", "Image, with a 2-D Array per pixel. arrayImage2D = img.select(bands).toArray().toArray(1)", "(reducerName == 'mosaic'): return imageCollection.mosaic() elif (reducerName == 'first'): return", "indexValue] ) return indexImage lsd = landsatData.map(myImageMapper, True) indexCollection2 =", "ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\ .map(reduceRegion) \\ .filterMetadata('index', 'not_equals', None) \\ .aggregate_array('timeIndex') \\", "ee.Geometry.Polygon(extent) elev = ee.Image('USGS/GTOPO30') minmaxElev = elev.reduceRegion( ee.Reducer.minMax(), extentGeom, 1000,", "imageCollection.first() elif (reducerName == 'sum'): return imageCollection.sum() else: return imageCollection.median()", "return URL so the routes are easier to deduce whats", "filteredImageNDWIToMapId(startDate, endDate): def calcNDWI(img): return img.expression('(i.green - i.nir) / (i.green", "'L4': [0, 1, 2, 3, 4, 5, 6], 'S2': [1,", "score = score.min(blue_rescale) # Clouds are reasonably bright in all", "########## def imageCollectionToMapId(assetId, visParams, reducer, startDate, endDate): eeCollection = ee.ImageCollection(assetId)", "ee.ImageCollection ########## def imageCollectionToMapId(assetId, visParams, reducer, startDate, endDate): eeCollection =", "img.expression('(i.nir - i.swir1) / (i.nir + i.swir1)', {'i': img}).rename(['NDMI']) \\", "imDate + datetime.timedelta(days=1) if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else:", "filteredImageEVI2ToMapId(startDate, endDate): def calcEVI2(img): return img.expression('2.5 * (i.nir - i.red)", "score = cloudScore(rescale).multiply(100).rename('cloudscore') return img.addBands(score) sentinel2 = ee.ImageCollection('COPERNICUS/S2') f2017s2 =", "'mode'): return ee.Reducer.mode() elif (reducerName == 'first'): return ee.Reducer.first() elif", "'LANDSAT/LT05/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T1_TOA': ['B1', 'B2',", "else: geometry = ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": start, \"end\":", "return img.addBands(score) def s2MaskClouds(img): qa = img.select('QA60') # Bits 10", "= 'ETM' elif (\"lt5\" in lowerAsset): sID = 'TM' scored", "ndsi = img.normalizedDifference(['B3', 'B11']) return score.min(rescale(ndsi, 'img', [0.8, 0.6])) def", "mapparams['tile_fetcher'].url_format def getDegradationPlotsByPointS1(geometry, start, end): if isinstance(geometry[0], list): geometry =", "datetime.datetime.strptime(date, \"%Y-%m-%d\") startDate = imDate - datetime.timedelta(days=1) endDate = imDate", "{ 'LANDSAT/LC08/C01/T1_TOA': ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LC08/C01/T2_TOA': ['B2',", "\"\"\" https://landsat.usgs.gov/collectionqualityband \"\"\" typeByValue = { 'badPixels': 15, 'cloud': 16,", "indexCollection = ee.ImageCollection(assetId).filterDate( startDate, endDate).select(indexName) else: indexCollection = ee.ImageCollection( assetId).filterDate(startDate,", "visParams = {'opacity': 1, 'max': 1, 'min': -1, 'palette': colorPalette}", "}) selectedImage = landsatData.first() unmasked = ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams = unmasked.getMapId(visParams)", "isSet(types): \"\"\" https://landsat.usgs.gov/collectionqualityband \"\"\" typeByValue = { 'badPixels': 15, 'cloud':", "'B7'], 'LANDSAT/LT04/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T2_TOA': ['B1',", "img.normalizedDifference(['green', 'swir1']) ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8))) score = score.min(ndsi_rescale).multiply(100).byte() mask", "'green', 'red', 'nir', 'swir1', 'swir2'] # linear regression coefficients for", "return imageToMapId(eviImage, visParams) def filteredImageNDMIToMapId(startDate, endDate): def calcNDMI(img): return img.expression('(i.nir", "def cloudScoreS2(img): rescale = img.divide(10000) score = cloudScore(rescale).multiply(100).rename('cloudscore') return img.addBands(score)", "{\"l4\": False, \"l5\": False, \"l7\": False, \"l8\": True} }) selectedImage", "list): geometry = ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) if indexName", "swir1) / (nir + swir1)', 'NDWI': '(green - nir) /", "f2017s2.map(cloudScoreS2) m2017s3 = m2017s2.median() return imageToMapId(m2017s3, visParams) def filteredSentinelSARComposite(visParams, startDate,", "colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI2).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDMIToMapId(startDate, endDate):", "cloudScoreS2(img): rescale = img.divide(10000) score = cloudScore(rescale).multiply(100).rename('cloudscore') return img.addBands(score) sentinel2", "sentinel1.map(addRatioBands) median = sentinel1.median() return imageToMapId(median, visParams) ########## Time Series", "11, 10, 12]} bandNamesLandsatTOA = ['blue', 'green', 'red', 'nir', 'swir1',", "else: indexValue = image.reduceRegion(theReducer, geometry, scale) date = image.get('system:time_start') indexImage", "{ 'bands': eeImage.bandNames().getInfo(), 'imageName': name } ########## ee.Image ########## def", "print(e) def getReducer(reducer): reducerName = reducer.lower() if(reducerName == 'min'): return", "reducedImage = ee.Image(reduceIC(eeCollection, reducer)) return imageToMapId(reducedImage, visParams) # TODO, should", "red - 7.5 * blue + 1)', 'EVI2': '2.5 *", "'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDWI).mean()) return imageToMapId(eviImage, visParams) def filteredImageByIndexToMapId(startDate,", "- nir) / (green + nir)', 'NBR': '(nir - swir2)", "'B7'], 'LANDSAT/LT04/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'] } indexes", "sentinel1Data = getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry }).filterDate(start,", "le7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds)", "vv = img.select('VV') vh = img.select('VH') vv_vh = vv.divide(vh).rename('VV/VH') vh_vv", "else: indexCollection = ee.ImageCollection( assetId).filterDate(startDate, endDate) def getIndex(image): theReducer =", "filteredImageNDMIToMapId(startDate, endDate) elif (lowerIndex == 'ndwi'): return filteredImageNDWIToMapId(startDate, endDate) def", "in all infrared bands. infrared = img.select('nir').add( img.select('swir1')).add(img.select('swir2')) infrared_rescale =", "= score.min(infrared_rescale) # Clouds are reasonably cool in temperature. temp_rescale", "+ 0.5)' } def create(name): def maskClouds(image): def isSet(types): \"\"\"", "theReducer, geometry=geometry, scale=scale, maxPixels=1e6) return ee.Feature(None, { 'index': reduced.get('index'), 'timeIndex':", "4, 5, 6], 'L4': [0, 1, 2, 3, 4, 5,", "return img.expression('(i.nir - i.swir1) / (i.nir + i.swir1)', {'i': img}).rename(['NDMI'])", "'CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) m2017s2 = f2017s2.map(cloudScoreS2) m2017s3 = m2017s2.median() return", "= image.reduceRegion( theReducer, geometry, scale).get(indexName) else: indexValue = image.reduceRegion(theReducer, geometry,", "'LANDSAT/LC08/C01/T1_TOA': ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LC08/C01/T2_TOA': ['B2', 'B3',", "field, matchID, visParams): fc = ee.FeatureCollection(featureCollection) single = fc.filter(ee.Filter.equals(field, matchID))", "= clippedcollection.map(getIndex) indexCollection2 = indexCollection1.aggregate_array('indexValue') return indexCollection2.getInfo() def getTimeSeriesByIndex(indexName, scale,", "= False eeCollection = ee.ImageCollection(assetId) lowerAsset = assetId.lower() if(\"b2\" not", "'VH', 'VV/VH'], 'region': geometry }).filterDate(start, end) def myimageMapper(img): theReducer =", "+ img.B12', [0.3, 0.8])) ndsi = img.normalizedDifference(['B3', 'B11']) return score.min(rescale(ndsi,", "= ee.ImageCollection([]) for name in bandsByCollection: collection = collection.merge(create(name)) return", "= score.min(temp_rescale) # However, clouds are not snow. ndsi =", "in bandsByCollection: collection = collection.merge(create(name)) return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\ .map(reduceRegion) \\", "########## ee.FeatureCollection ########## def getFeatureCollectionTileUrl(featureCollection, field, matchID, visParams): fc =", "bright in the blue band. blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1))) score", "= lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values ########## Stats ##########", "imageCollection.mosaic() elif (reducerName == 'first'): return imageCollection.first() elif (reducerName ==", "= img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start') visParams = {'bands':", "ee.Reducer.first() elif (reducerName == 'last'): return ee.Reducer.last() elif (reducerName ==", "5, 7], 'L5': [0, 1, 2, 3, 4, 5, 6],", "ee.Array([[-0.00411], [-0.00093], [0.00094], [-0.00029], [-0.00015], [-0.00097]]) # Make an Array", "True, \"l5\": True, \"l7\": True, \"l8\": True} }) def myImageMapper(img):", "sentinel1Data.filterDate(start, end).first() selectedImage = ee.Image(selectedImage) mapparams = selectedImage.getMapId(visParams) return mapparams['tile_fetcher'].url_format", "elif (\"lt5\" in lowerAsset): skipCloudMask = False else: skipCloudMask =", "= ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1 = sentinel1.filterDate(startDate, endDate) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\", "1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDMI).mean()) return imageToMapId(eviImage,", "Pre defined ee.ImageCollection ########## # Index Image Collection def lsMaskClouds(img,", "img.divide(10000) score = cloudScore(rescale).multiply(100).rename('cloudscore') return img.addBands(score) sentinel2 = ee.ImageCollection('COPERNICUS/S2') f2017s2", "} indexes = { 'NDVI': '(nir - red) / (nir", "imageToMapId(image, visParams): eeImage = ee.Image(image) mapId = eeImage.getMapId(visParams) # TODO,", "= img.normalizedDifference(['green', 'swir1']) ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8))) score = score.min(ndsi_rescale).multiply(100).byte()", "= sentinel1.map(addRatioBands) median = sentinel1.median() return imageToMapId(median, visParams) ########## Time", "visParams) return values ########## ee.FeatureCollection ########## def getFeatureCollectionTileUrl(featureCollection, field, matchID,", "} ########## ee.Image ########## def imageToMapId(image, visParams): eeImage = ee.Image(image)", "'cirrus']).Not()) def toIndex(image): bands = bandsByCollection[name] return image.expression(indexes[indexName], { 'blue':", "= ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8))) score = score.min(ndsi_rescale).multiply(100).byte() mask = score.lt(cloudThresh).rename(['cloudMask']) img", "if both flags set to zero. clear = qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0))", "= sentinel1.filterDate(startDate, endDate) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \\", "-25, .40], 'max': [0, -10, 1], 'gamma': 1.6} indexImage =", "(i.nir + 6.0 * i.red - 7.5 * i.blue +", "endDate) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW'))", "scored = ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID', sID)) mask = scored.select(['cloud']).lte(20) masked =", "if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry)", "= img.select('VV') vh = img.select('VH') vv_vh = vv.divide(vh).rename('VV/VH') vh_vv =", "+ red)', 'EVI': '2.5 * (nir - red) / (nir", "'img.B4 + img.B3 + img.B2', [0.2, 0.8])) score = score.min(", "== 'max'): return imageCollection.max() elif (reducerName == 'mean'): return imageCollection.mean()", ".filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds) s2 = ee.ImageCollection('COPERNICUS/S2') \\", "lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values ########## Stats ########## def", "'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDWI).mean()) return imageToMapId(eviImage, visParams)", "else: ee.Initialize() except Exception as e: print(e) def getReducer(reducer): reducerName", "indexCollection1.aggregate_array('indexValue') return indexCollection2.getInfo() def getTimeSeriesByIndex(indexName, scale, coords, startDate, endDate, reducer):", "scale).get(indexName) else: indexValue = image.reduceRegion(theReducer, geometry, scale) date = image.get('system:time_start')", "ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) collection = ee.ImageCollection([]) for name", "time) # if startDate and endDate: return ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart, True)", "= ee.Image(eeCollection.map(calcNDWI).mean()) return imageToMapId(eviImage, visParams) def filteredImageByIndexToMapId(startDate, endDate, index): lowerIndex", "= ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\":", "img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '505050,E8E8E8,00FF33,003300' visParams =", "ee.Image(reduceIC(eeCollection, reducer)) return imageToMapId(reducedImage, visParams) # TODO, should we allow", "visParams): eeImage = ee.Image(image) mapId = eeImage.getMapId(visParams) # TODO, just", "= score.min(blue_rescale) # Clouds are reasonably bright in all visible", "ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\ .arrayProject([0]).arrayFlatten([bands]).float() # .set('system:time_start',img.get('system:time_start')); return keep.addBands(componentsImage) def getLandSatMergedCollection(): sensorBandDictLandsatTOA", "= m2017s2.median() return imageToMapId(m2017s3, visParams) def filteredSentinelSARComposite(visParams, startDate, endDate): def", ".select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds) lt5 = ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\", "+ i.nir)', {'i': img}).rename(['NDWI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate,", ".map(reduceRegion) \\ .filterMetadata('index', 'not_equals', None) \\ .aggregate_array('timeIndex') \\ .getInfo() ##########", "(i.nir - i.red) / (i.nir + 2.4 * i.red +", "typeByValue = { 'badPixels': 15, 'cloud': 16, 'shadow': 256, 'snow':", "10)) cirrusBitMask = int(math.pow(2, 11)) # clear if both flags", "img.select('VV') vh = img.select('VH') vv_vh = vv.divide(vh).rename('VV/VH') vh_vv = vh.divide(vv).rename('VH/VV')", "0.5)' } def create(name): def maskClouds(image): def isSet(types): \"\"\" https://landsat.usgs.gov/collectionqualityband", "False): sID = '' if (\"lc8\" in lowerAsset): sID =", "'TM' scored = ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID', sID)) mask = scored.select(['cloud']).lte(20) masked", "'nir', 'swir1', 'temp', 'swir2'] metadataCloudCoverMax = 100 lt4 = ee.ImageCollection('LANDSAT/LT4_L1T_TOA')", "= ee.Image(eeCollection.mosaic()) try: if(skipCloudMask == False): sID = '' if", "m2017s2.median() return imageToMapId(m2017s3, visParams) def filteredSentinelSARComposite(visParams, startDate, endDate): def toNatural(img):", "getDegradationPlotsByPointS1(geometry, start, end): if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else:", "Exception as e: print(e) def getReducer(reducer): reducerName = reducer.lower() if(reducerName", "e: return {} ########## Helper routes ########## def listAvailableBands(name, assetType):", "elif (reducerName == 'first'): return ee.Reducer.first() elif (reducerName == 'last'):", "routes ########## def listAvailableBands(name, assetType): eeImage = None if assetType", "3, 4, 5, 9, 6], 'L7': [0, 1, 2, 3,", "= 'TM' scored = ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID', sID)) mask = scored.select(['cloud']).lte(20)", "\\ .filter(ee.Filter.eq('instrumentMode', 'IW')) sentinel1 = sentinel1.map(toNatural) sentinel1 = sentinel1.map(addRatioBands) median", "# TODO, should we allow user to select first cloud", "[0.2, 0.8])) score = score.min( rescale(img, 'img.B8 + img.B11 +", "= img.updateMask(mask) return img.addBands(score) def s2MaskClouds(img): qa = img.select('QA60') #", "\\ .getInfo() ########## Degradation########## def getDegradationTileUrlByDateS1(geometry, date, visParams): imDate =", "30) date = img.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]", "(lowerIndex == 'ndvi'): return filteredImageNDVIToMapId(startDate, endDate) elif (lowerIndex == 'evi'):", "(reducerName == 'max'): return ee.Reducer.max() elif (reducerName == 'mean'): return", "def getClipped(image): return image.clip(geometry) clippedcollection = indexCollection.map(getClipped) indexCollection1 = clippedcollection.map(getIndex)", "'B5', 'B7'], 'LANDSAT/LT04/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'] }", "img.select('nir').add( img.select('swir1')).add(img.select('swir2')) infrared_rescale = infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3))) score = score.min(infrared_rescale) #", "= ee.Geometry.Point(coords) if indexName != None: indexCollection = ee.ImageCollection(assetId).filterDate( startDate,", "= vv.divide(vh).rename('VV/VH') vh_vv = vh.divide(vv).rename('VH/VV') return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD')", "img.select('green')).add(img.select('blue')) visible_rescale = visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2))) score = score.min(visible_rescale) # Clouds", "'((nir - red) / (nir + red + 0.5)) *", "ciesinPopGrid = ee.Image('CIESIN/GPWv4/population-count/2020') popDict = ciesinPopGrid.reduceRegion( ee.Reducer.sum(), extentGeom, maxPixels=500000000) pop", "reducer): reducerName = reducer.lower() if(reducerName == 'min'): return imageCollection.min() elif", "(nir + swir2)', 'LSAVI': '((nir - red) / (nir +", "collection = collection.merge(create(name)) return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\ .map(reduceRegion) \\ .filterMetadata('index', 'not_equals',", "calcNDMI(img): return img.expression('(i.nir - i.swir1) / (i.nir + i.swir1)', {'i':", "(i.nir + 2.4 * i.red + 1)', {'i': img}).rename(['EVI2']) \\", "= getReducer(reducer) if indexName != None: indexValue = image.reduceRegion( theReducer,", "return img.expression('(i.nir - i.red) / (i.nir + i.red)', {'i': img}).rename(['NDVI'])", "/ (nir + 2.4 * red + 1)', 'NDMI': '(nir", "eeCollection = eeCollection.filterDate(startDate, endDate) eeCollection.filterMetadata( 'CLOUD_COVER', 'less_than', metadataCloudCoverMax ) eeMosaicImage", "[0.996]]) bias = ee.Array([[-0.00411], [-0.00093], [0.00094], [-0.00029], [-0.00015], [-0.00097]]) #", "+ 6.0 * i.red - 7.5 * i.blue + 1)',", "{ 'badPixels': 15, 'cloud': 16, 'shadow': 256, 'snow': 1024, 'cirrus':", "- red) / (nir + red + 0.5)) * (1", "= ee.Image().paint(single, 0, 2).getMapId(visParams) return mapId['tile_fetcher'].url_format ########## Pre defined ee.ImageCollection", "visParams): fc = ee.FeatureCollection(featureCollection) single = fc.filter(ee.Filter.equals(field, matchID)) mapId =", "ee.Feature(None, { 'index': reduced.get('index'), 'timeIndex': [image.get('system:time_start'), reduced.get('index')] }) geometry =", "= ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\ .arrayProject([0]).arrayFlatten([bands]).float() # .set('system:time_start',img.get('system:time_start')); return keep.addBands(componentsImage) def getLandSatMergedCollection():", "lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values def getDegradationTileUrlByDate(geometry, date, visParams):", "return ee.Reducer.sum() else: return ee.Reducer.median() def reduceIC(imageCollection, reducer): reducerName =", "as e: try: return json.loads(val.replace(\"'\", \"\\\"\")) except Exception as e:", "'img.B2', [0.1, 0.3])) score = score.min(rescale(img, 'img.B4 + img.B3 +", "elif (reducerName == 'max'): return ee.Reducer.max() elif (reducerName == 'mean'):", "\\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) \\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA) \\ .map(bandPassAdjustment) return", "\"sensors\": {\"l4\": False, \"l5\": False, \"l7\": False, \"l8\": True} })", "9, 6], 'L7': [0, 1, 2, 3, 4, 5, 7],", "[0, 1, 2, 3, 4, 5, 7], 'L5': [0, 1,", "'B7'], 'LANDSAT/LE07/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T1_TOA': ['B1',", "{'i': img}).rename(['EVI2']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette", "visParams, startDate, endDate, metadataCloudCoverMax, simpleCompositeVariable): eeCollection = ee.ImageCollection(assetId) if (startDate", "1, 'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI2).mean())", "lc8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds)", "isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) sentinel1Data", "== 'mode'): return ee.Reducer.mode() elif (reducerName == 'first'): return ee.Reducer.first()", "(reducerName == 'first'): return ee.Reducer.first() elif (reducerName == 'last'): return", "elif (reducerName == 'sum'): return imageCollection.sum() else: return imageCollection.median() def", "startDate, endDate, reducer): bandsByCollection = { 'LANDSAT/LC08/C01/T1_TOA': ['B2', 'B3', 'B4',", "first cloud free image again? def firstCloudFreeImageInMosaicToMapId(assetId, visParams, startDate, endDate):", "1024, 'cirrus': 4096 } anySet = ee.Image(0) for Type in", "= index.lower() if (lowerIndex == 'ndvi'): return filteredImageNDVIToMapId(startDate, endDate) elif", "visParams) def filteredSentinelSARComposite(visParams, startDate, endDate): def toNatural(img): return ee.Image(10).pow(img.divide(10)) def", "* (i.nir - i.red) / (i.nir + 6.0 * i.red", "reasonably bright in the blue band. blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1)))", "collection.merge(create(name)) return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\ .map(reduceRegion) \\ .filterMetadata('index', 'not_equals', None) \\", "= selectedImage.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPointS1(geometry, start, end): if isinstance(geometry[0],", "eeImage.bandNames().getInfo(), 'imageName': name } ########## ee.Image ########## def imageToMapId(image, visParams):", "endDate) colorPalette = '505050,E8E8E8,00FF33,003300' visParams = {'opacity': 1, 'max': 1,", "else: skipCloudMask = True if (startDate and endDate): eeFilterDate =", "score = score.min(visible_rescale) # Clouds are reasonably bright in all", "visParams) ########## Time Series ########## def getTimeSeriesByCollectionAndIndex(assetId, indexName, scale, coords,", "ee.Initialize() except Exception as e: print(e) def getReducer(reducer): reducerName =", "score = ee.Image(1.0) # Clouds are reasonably bright in the", "img}).subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) score = ee.Image(1.0) score = score.min(rescale(img, 'img.B2',", "= ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage lsd = sentinel1Data.map(myimageMapper,", "indexValue = image.reduceRegion(theReducer, geometry, scale) date = image.get('system:time_start') indexImage =", "[0, 1, 2, 3, 4, 5, 6], 'S2': [1, 2,", "geometry, \"sensors\": {\"l4\": False, \"l5\": False, \"l7\": False, \"l8\": True}", "return imageToMapId(m2017s3, visParams) def filteredSentinelSARComposite(visParams, startDate, endDate): def toNatural(img): return", "visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") befDate = imDate - datetime.timedelta(days=1)", "EEException as ine: imageToMapId(eeFirstImage, visParams) return values ########## ee.FeatureCollection ##########", "= getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams = {'opacity': 1,", "cirrusBitMask = int(math.pow(2, 11)) # clear if both flags set", "'url': mapId['tile_fetcher'].url_format } ########## ee.ImageCollection ########## def imageCollectionToMapId(assetId, visParams, reducer,", "'(nir - swir1) / (nir + swir1)', 'NDWI': '(green -", "metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds) le7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than',", "- red) / (nir + 2.4 * red + 1)',", "qa = img.select('QA60') # Bits 10 and 11 are clouds", "endDate) elif (lowerIndex == 'evi'): return filteredImageEVIToMapId(startDate, endDate) elif (lowerIndex", "(lowerIndex == 'ndwi'): return filteredImageNDWIToMapId(startDate, endDate) def filteredImageCompositeToMapId(assetId, visParams, startDate,", "time = image.get('system:time_start') image = maskClouds(image) return toIndex(image).set('system:time_start', time) #", "'green', 'red', 'nir', 'swir1', 'temp', 'swir2'] metadataCloudCoverMax = 100 lt4", "ee.Image(10).pow(img.divide(10)) def addRatioBands(img): # not using angle band vv =", "eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'c9c0bf,435ebf,eee8aa,006400' visParams = {'opacity':", "'VH', 'ratioVVVH'], 'min': [-15, -25, .40], 'max': [0, -10, 1],", "def calcEVI2(img): return img.expression('2.5 * (i.nir - i.red) / (i.nir", "# However, clouds are not snow. ndsi = img.normalizedDifference(['green', 'swir1'])", "['B2', 'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LC08/C01/T2_TOA': ['B2', 'B3', 'B4',", "= infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3))) score = score.min(infrared_rescale) # Clouds are reasonably", "pop = popDict.get('population-count').getInfo() pop = int(pop) return { 'minElev': minElev,", "'LANDSAT/LC08/C01/T2_TOA': ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LE07/C01/T1_TOA': ['B1', 'B2',", "imageToMapId(eviImage, visParams) def filteredImageNDMIToMapId(startDate, endDate): def calcNDMI(img): return img.expression('(i.nir -", "img.get('system:time_start')) def bandPassAdjustment(img): keep = img.select(['temp']) bands = ['blue', 'green',", "def isSet(types): \"\"\" https://landsat.usgs.gov/collectionqualityband \"\"\" typeByValue = { 'badPixels': 15,", "an Array Image, with a 2-D Array per pixel. arrayImage2D", "visParams[\"bands\"].lower()): skipCloudMask = True elif (\"lc8\" in lowerAsset): skipCloudMask =", "i.red) / (i.nir + 6.0 * i.red - 7.5 *", "= img.select('nir').add( img.select('swir1')).add(img.select('swir2')) infrared_rescale = infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3))) score = score.min(infrared_rescale)", "elif (lowerIndex == 'evi'): return filteredImageEVIToMapId(startDate, endDate) elif (lowerIndex ==", "'red', 'nir', 'swir1', 'temp', 'swir2'] metadataCloudCoverMax = 100 lt4 =", "skipCloudMask = False elif (\"le7\" in lowerAsset): skipCloudMask = False", "eeCollection.filter(eeFilterDate) eeFirstImage = ee.Image(eeCollection.mosaic()) try: if(skipCloudMask == False): sID =", "'B5', 'B7'], 'LANDSAT/LT04/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T2_TOA':", "{ 'blue': image.select(bands[0]), 'green': image.select(bands[1]), 'red': image.select(bands[2]), 'nir': image.select(bands[3]), 'swir1':", "def getTimeSeriesByCollectionAndIndex(assetId, indexName, scale, coords, startDate, endDate, reducer): geometry =", "just return URL so the routes are easier to deduce", "are not snow. ndsi = img.normalizedDifference(['green', 'swir1']) ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide(", "img.normalizedDifference(['B3', 'B11']) return score.min(rescale(ndsi, 'img', [0.8, 0.6])) def cloudScoreS2(img): rescale", "return imageToMapId(eeMosaicImage, visParams) def filteredSentinelComposite(visParams, startDate, endDate, metadataCloudCoverMax): def cloudScore(img):", "1, 'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDVI).mean())", "'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7']", "Bits 10 and 11 are clouds and cirrus, respectively. cloudBitMask", "arrayImage2D = img.select(bands).toArray().toArray(1) # apply correction factors and reproject array", "\\ .arrayProject([0]).arrayFlatten([bands]).float() # .set('system:time_start',img.get('system:time_start')); return keep.addBands(componentsImage) def getLandSatMergedCollection(): sensorBandDictLandsatTOA =", "ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) if indexName != None: indexCollection", "'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI2).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDMIToMapId(startDate,", "endDate): def calcEVI2(img): return img.expression('2.5 * (i.nir - i.red) /", "endDate): def calcNDWI(img): return img.expression('(i.green - i.nir) / (i.green +", "(i.nir + i.red)', {'i': img}).rename(['NDVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection =", "reduceRegion(image): theReducer = getReducer(reducer) reduced = image.reduceRegion( theReducer, geometry=geometry, scale=scale,", "visParams) def filteredImageNDMIToMapId(startDate, endDate): def calcNDMI(img): return img.expression('(i.nir - i.swir1)", "red) / (nir + 6.0 * red - 7.5 *", "lowerAsset): sID = 'TM' scored = ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID', sID)) mask", "else: values = imageToMapId(eeFirstImage, visParams) except EEException as ine: imageToMapId(eeFirstImage,", "score.min(rescale(img, 'img.B2', [0.1, 0.3])) score = score.min(rescale(img, 'img.B4 + img.B3", "= getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'c9c0bf,435ebf,eee8aa,006400' visParams = {'opacity': 1,", "as e: print(e) def getReducer(reducer): reducerName = reducer.lower() if(reducerName ==", "linear regression coefficients for adjustment gain = ee.Array([[0.977], [1.005], [0.982],", "keep.addBands(componentsImage) def getLandSatMergedCollection(): sensorBandDictLandsatTOA = {'L8': [1, 2, 3, 4,", "+ 0.5)) * (1 + 0.5)' } def create(name): def", "1, 'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDMI).mean())", "= 'OLI_TIRS' elif (\"le7\" in lowerAsset): sID = 'ETM' elif", "1)', 'EVI2': '2.5 * (nir - red) / (nir +", "import sys import json from ee.ee_exception import EEException from gee.inputs", "are reasonably cool in temperature. temp_rescale = img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300))) score", "\\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000'", "coefficients for adjustment gain = ee.Array([[0.977], [1.005], [0.982], [1.001], [1.001],", "* blue + 1)', 'EVI2': '2.5 * (nir - red)", "'EVI': '2.5 * (nir - red) / (nir + 6.0", "imageToMapId(eviImage, visParams) def filteredImageEVIToMapId(startDate, endDate): def calcEVI(img): return img.expression('2.5 *", "vv.divide(vh).rename('VV/VH') vh_vv = vh.divide(vv).rename('VH/VV') return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1", "- i.swir1) / (i.nir + i.swir1)', {'i': img}).rename(['NDMI']) \\ .set('system:time_start',", "gee.inputs import getLandsat, getS1 ########## Helper functions ########## def initialize(ee_account='',", "metadataCloudCoverMax ) eeMosaicImage = ee.Algorithms.Landsat.simpleComposite( eeCollection, simpleCompositeVariable, 10, 40, True", "eeCollection, simpleCompositeVariable, 10, 40, True ) return imageToMapId(eeMosaicImage, visParams) def", "ee.Number(290).subtract(ee.Number(300))) score = score.min(temp_rescale) # However, clouds are not snow.", "\\ .select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds) s2 = ee.ImageCollection('COPERNICUS/S2') \\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax)", "set to zero. clear = qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0)) return img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start'))", "1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI2).mean()) return imageToMapId(eviImage,", "= ee.Image('USGS/GTOPO30') minmaxElev = elev.reduceRegion( ee.Reducer.minMax(), extentGeom, 1000, maxPixels=500000000) minElev", "1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDWI).mean()) return imageToMapId(eviImage,", "clippedcollection.map(getIndex) indexCollection2 = indexCollection1.aggregate_array('indexValue') return indexCollection2.getInfo() def getTimeSeriesByIndex(indexName, scale, coords,", "band): if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry =", "= False else: skipCloudMask = True if (startDate and endDate):", "= ee.Geometry.Polygon(extent) elev = ee.Image('USGS/GTOPO30') minmaxElev = elev.reduceRegion( ee.Reducer.minMax(), extentGeom,", "'B5', 'B7'], 'LANDSAT/LE07/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T1_TOA':", "both flags set to zero. clear = qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0)) return", "'mean'): return ee.Reducer.mean() elif (reducerName == 'mode'): return ee.Reducer.mode() elif", "= ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams = unmasked.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPoint(geometry, start,", "geometry, scale) date = image.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date),", "are easier to deduce whats being returned. return { 'url':", "# Bits 10 and 11 are clouds and cirrus, respectively.", "= assetId.lower() if(\"b2\" not in visParams[\"bands\"].lower()): skipCloudMask = True elif", "'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI).mean()) return", "[-15, -25, .40], 'max': [0, -10, 1], 'gamma': 1.6} indexImage", "i.red)', {'i': img}).rename(['NDVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate)", "befDate.strftime('%Y-%m-%d') end = aftDate.strftime('%Y-%m-%d') selectedImage = sentinel1Data.filterDate(start, end).first() selectedImage =", "swir2)', 'LSAVI': '((nir - red) / (nir + red +", "6.0 * i.red - 7.5 * i.blue + 1)', {'i':", "ee.Geometry.Point(geometry) sentinel1Data = getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry})", ") eeMosaicImage = ee.Algorithms.Landsat.simpleComposite( eeCollection, simpleCompositeVariable, 10, 40, True )", "'SWIR1', 'NIR'], \"region\": geometry, \"sensors\": {\"l4\": False, \"l5\": False, \"l7\":", "anySet return image.updateMask(isSet(['badPixels', 'cloud', 'shadow', 'cirrus']).Not()) def toIndex(image): bands =", "create(name): def maskClouds(image): def isSet(types): \"\"\" https://landsat.usgs.gov/collectionqualityband \"\"\" typeByValue =", "ee.Number(0.8).subtract(ee.Number(0.3))) score = score.min(infrared_rescale) # Clouds are reasonably cool in", "startDate, endDate).select(indexName) else: indexCollection = ee.ImageCollection( assetId).filterDate(startDate, endDate) def getIndex(image):", "indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue] ) return indexImage lsd", "+ 1)', {'i': img}).rename(['EVI2']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate,", "colorPalette = 'c9c0bf,435ebf,eee8aa,006400' visParams = {'opacity': 1, 'max': 1, 'min':", "(reducerName == 'mean'): return ee.Reducer.mean() elif (reducerName == 'mode'): return", "+ swir2)', 'LSAVI': '((nir - red) / (nir + red", "Clouds are reasonably bright in all visible bands. visible =", "/ (nir + swir1)', 'NDWI': '(green - nir) / (green", "and os.path.exists(ee_key_path): credentials = ee.ServiceAccountCredentials(ee_account, ee_key_path) ee.Initialize(credentials) else: ee.Initialize() except", "= ee.ImageCollection('COPERNICUS/S2') \\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) \\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA) \\", "} ########## ee.ImageCollection ########## def imageCollectionToMapId(assetId, visParams, reducer, startDate, endDate):", "== 'ndmi'): return filteredImageNDMIToMapId(startDate, endDate) elif (lowerIndex == 'ndwi'): return", "= ee.ImageCollection(assetId) if (startDate and endDate): eeCollection = eeCollection.filterDate(startDate, endDate)", "else: return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True) def reduceRegion(image): theReducer = getReducer(reducer) reduced", "'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'],", "clippedcollection = indexCollection.map(getClipped) indexCollection1 = clippedcollection.map(getIndex) indexCollection2 = indexCollection1.aggregate_array('indexValue') return", "'LANDSAT/LT04/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'] } indexes =", "list) or isinstance(coords[0], tuple): geometry = ee.Geometry.Polygon(coords) else: geometry =", "blue band. blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1))) score = score.min(blue_rescale) #", "and endDate): eeCollection = eeCollection.filterDate(startDate, endDate) eeCollection.filterMetadata( 'CLOUD_COVER', 'less_than', metadataCloudCoverMax", "(nir + red)', 'EVI': '2.5 * (nir - red) /", "True, \"l8\": True} }) def myImageMapper(img): theReducer = ee.Reducer.mean() indexValue", "indexCollection2.getInfo() return values ########## Stats ########## def getStatistics(extent): extentGeom =", "= indexCollection.map(getClipped) indexCollection1 = clippedcollection.map(getIndex) indexCollection2 = indexCollection1.aggregate_array('indexValue') return indexCollection2.getInfo()", "= None indexCollection = None if isinstance(coords[0], list): geometry =", "reducer.lower() if(reducerName == 'min'): return ee.Reducer.min() elif (reducerName == 'max'):", "cloudThresh=10): score = ee.Image(1.0) # Clouds are reasonably bright in", "from ee.ee_exception import EEException from gee.inputs import getLandsat, getS1 ##########", "= ee.ImageCollection( assetId).filterDate(startDate, endDate) def getIndex(image): theReducer = getReducer(reducer) if", "end) def myimageMapper(img): theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry,", "(reducerName == 'mean'): return imageCollection.mean() elif (reducerName == 'mode'): return", "theReducer, geometry, scale).get(indexName) else: indexValue = image.reduceRegion(theReducer, geometry, scale) date", "in lowerAsset): sID = 'TM' scored = ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID', sID))", "eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '505050,E8E8E8,00FF33,003300' visParams = {'opacity':", "getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'c9c0bf,435ebf,eee8aa,006400' visParams = {'opacity': 1, 'max':", "return filteredImageNDVIToMapId(startDate, endDate) elif (lowerIndex == 'evi'): return filteredImageEVIToMapId(startDate, endDate)", "eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams = {'opacity':", "= collection.merge(create(name)) return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\ .map(reduceRegion) \\ .filterMetadata('index', 'not_equals', None)", "'indexValue', [ee.Number(date), indexValue]) return indexImage lsd = sentinel1Data.map(myimageMapper, True) indexCollection2", "[-0.00097]]) # Make an Array Image, with a 2-D Array", "minmaxElev.get('elevation_max').getInfo() ciesinPopGrid = ee.Image('CIESIN/GPWv4/population-count/2020') popDict = ciesinPopGrid.reduceRegion( ee.Reducer.sum(), extentGeom, maxPixels=500000000)", "['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T2_TOA': ['B1', 'B2', 'B3',", "* i.blue + 1)', {'i': img}).rename(['EVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection", "+ 1)', 'EVI2': '2.5 * (nir - red) / (nir", "4, 5, 9, 6], 'L7': [0, 1, 2, 3, 4,", "endDate): def calcEVI(img): return img.expression('2.5 * (i.nir - i.red) /", "eeImage = ee.ImageCollection(name).first() else: eeImage = ee.Image(name) return { 'bands':", "eeCollection.filterMetadata( 'CLOUD_COVER', 'less_than', metadataCloudCoverMax ) eeMosaicImage = ee.Algorithms.Landsat.simpleComposite( eeCollection, simpleCompositeVariable,", "# if startDate and endDate: return ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart, True) else:", "+ 1)', 'NDMI': '(nir - swir1) / (nir + swir1)',", "eeImage = None if assetType == \"imageCollection\": eeImage = ee.ImageCollection(name).first()", "i.nir) / (i.green + i.nir)', {'i': img}).rename(['NDWI']) \\ .set('system:time_start', img.get('system:time_start'))", "}).clamp(-1, 1).rename(['index']) def toIndexWithTimeStart(image): time = image.get('system:time_start') image = maskClouds(image)", "ee.Image(name) return { 'bands': eeImage.bandNames().getInfo(), 'imageName': name } ########## ee.Image", "endDate.strftime('%Y-%m-%d'), \"targetBands\": ['RED', 'GREEN', 'BLUE', 'SWIR1', 'NIR'], \"region\": geometry, \"sensors\":", "imDate - datetime.timedelta(days=1) endDate = imDate + datetime.timedelta(days=1) if isinstance(geometry[0],", "datetime import os import ee import math import sys import", "endDate) colorPalette = '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams = {'opacity': 1, 'max': 1,", "in lowerAsset): sID = 'ETM' elif (\"lt5\" in lowerAsset): sID", "whats being returned. return { 'url': mapId['tile_fetcher'].url_format } ########## ee.ImageCollection", "zero. clear = qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0)) return img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start')) def bandPassAdjustment(img):", "ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True) def reduceRegion(image): theReducer = getReducer(reducer) reduced = image.reduceRegion(", "3, 4, 5, 6], 'L4': [0, 1, 2, 3, 4,", "= imageToMapId(eeFirstImage, visParams) except EEException as ine: imageToMapId(eeFirstImage, visParams) return", "mapId['tile_fetcher'].url_format } ########## ee.ImageCollection ########## def imageCollectionToMapId(assetId, visParams, reducer, startDate,", "sentinel1.map(toNatural) sentinel1 = sentinel1.map(addRatioBands) median = sentinel1.median() return imageToMapId(median, visParams)", "{ 'NDVI': '(nir - red) / (nir + red)', 'EVI':", "-1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI).mean()) return imageToMapId(eviImage, visParams) def", "the blue band. blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1))) score = score.min(blue_rescale)", "}).filterDate(start, end) def myimageMapper(img): theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer,", "clouds and cirrus, respectively. cloudBitMask = int(math.pow(2, 10)) cirrusBitMask =", "for adjustment gain = ee.Array([[0.977], [1.005], [0.982], [1.001], [1.001], [0.996]])", "= int(pop) return { 'minElev': minElev, 'maxElev': maxElev, 'pop': pop", "visParams) def filteredImageNDWIToMapId(startDate, endDate): def calcNDWI(img): return img.expression('(i.green - i.nir)", "imageToMapId(masked, visParams) else: values = imageToMapId(eeFirstImage, visParams) except EEException as", "def filteredImageNDMIToMapId(startDate, endDate): def calcNDMI(img): return img.expression('(i.nir - i.swir1) /", "metadataCloudCoverMax, simpleCompositeVariable): eeCollection = ee.ImageCollection(assetId) if (startDate and endDate): eeCollection", "'' if (\"lc8\" in lowerAsset): sID = 'OLI_TIRS' elif (\"le7\"", "def filteredImageEVI2ToMapId(startDate, endDate): def calcEVI2(img): return img.expression('2.5 * (i.nir -", "lowerAsset): skipCloudMask = False elif (\"le7\" in lowerAsset): skipCloudMask =", "geometry }).filterDate(start, end) def myimageMapper(img): theReducer = ee.Reducer.mean() indexValue =", "image componentsImage = ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\ .arrayProject([0]).arrayFlatten([bands]).float() # .set('system:time_start',img.get('system:time_start')); return keep.addBands(componentsImage)", "startDate = imDate - datetime.timedelta(days=1) endDate = imDate + datetime.timedelta(days=1)", "= landsatData.first() unmasked = ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams = unmasked.getMapId(visParams) return mapparams['tile_fetcher'].url_format", "firstCloudFreeImageInMosaicToMapId(assetId, visParams, startDate, endDate): skipCloudMask = False eeCollection = ee.ImageCollection(assetId)", "sentinel1Data = getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry}) start", "ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds) lt5 =", "datetime.timedelta(days=1) endDate = imDate + datetime.timedelta(days=1) if isinstance(geometry[0], list): geometry", "cloud free image again? def firstCloudFreeImageInMosaicToMapId(assetId, visParams, startDate, endDate): skipCloudMask", "img.select(['temp']) bands = ['blue', 'green', 'red', 'nir', 'swir1', 'swir2'] #", "getTimeSeriesByCollectionAndIndex(assetId, indexName, scale, coords, startDate, endDate, reducer): geometry = None", "ee.Image().paint(single, 0, 2).getMapId(visParams) return mapId['tile_fetcher'].url_format ########## Pre defined ee.ImageCollection ##########", "isinstance(coords[0], tuple): geometry = ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) collection", "ee.Geometry.Point(coords) if indexName != None: indexCollection = ee.ImageCollection(assetId).filterDate( startDate, endDate).select(indexName)", "bandsByCollection: collection = collection.merge(create(name)) return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\ .map(reduceRegion) \\ .filterMetadata('index',", "scale) date = image.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue])", "maxPixels=1e6) return ee.Feature(None, { 'index': reduced.get('index'), 'timeIndex': [image.get('system:time_start'), reduced.get('index')] })", "= { 'LANDSAT/LC08/C01/T1_TOA': ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LC08/C01/T2_TOA':", "getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams = {'opacity': 1, 'max':", "########## ee.ImageCollection ########## def imageCollectionToMapId(assetId, visParams, reducer, startDate, endDate): eeCollection", "indexValue = img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start') visParams =", "geometry = ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": start, \"end\": end,", "7, 11, 10, 12]} bandNamesLandsatTOA = ['blue', 'green', 'red', 'nir',", "defined ee.ImageCollection ########## # Index Image Collection def lsMaskClouds(img, cloudThresh=10):", "= ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage def getClipped(image): return", "ee.Reducer.median() def reduceIC(imageCollection, reducer): reducerName = reducer.lower() if(reducerName == 'min'):", "colorPalette} eviImage = ee.Image(eeCollection.map(calcNDVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVIToMapId(startDate, endDate):", "+ nir)', 'NBR': '(nir - swir2) / (nir + swir2)',", "getIndex(image): theReducer = getReducer(reducer) if indexName != None: indexValue =", "return ee.Reducer.last() elif (reducerName == 'sum'): return ee.Reducer.sum() else: return", "return imageToMapId(eviImage, visParams) def filteredImageNDWIToMapId(startDate, endDate): def calcNDWI(img): return img.expression('(i.green", "return val else: try: return json.loads(val) except Exception as e:", "try: return json.loads(val) except Exception as e: try: return json.loads(val.replace(\"'\",", "endDate).filterBounds(geometry).map(toIndexWithTimeStart, True) else: return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True) def reduceRegion(image): theReducer =", ".filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds) lt5 = ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\", "'ratioVVVH'], 'min': [-15, -25, .40], 'max': [0, -10, 1], 'gamma':", "== 'max'): return ee.Reducer.max() elif (reducerName == 'mean'): return ee.Reducer.mean()", "imageToMapId(m2017s3, visParams) def filteredSentinelSARComposite(visParams, startDate, endDate): def toNatural(img): return ee.Image(10).pow(img.divide(10))", ".set('system:time_start',img.get('system:time_start')); return keep.addBands(componentsImage) def getLandSatMergedCollection(): sensorBandDictLandsatTOA = {'L8': [1, 2,", "filteredImageEVI2ToMapId(startDate, endDate) elif (lowerIndex == 'ndmi'): return filteredImageNDMIToMapId(startDate, endDate) elif", "elif (reducerName == 'mean'): return ee.Reducer.mean() elif (reducerName == 'mode'):", "imageCollection.mode() elif (reducerName == 'mosaic'): return imageCollection.mosaic() elif (reducerName ==", "[0, 1, 2, 3, 4, 5, 6], 'L4': [0, 1,", "['blue', 'green', 'red', 'nir', 'swir1', 'swir2'] # linear regression coefficients", "(lowerIndex == 'evi2'): return filteredImageEVI2ToMapId(startDate, endDate) elif (lowerIndex == 'ndmi'):", "(nir - red) / (nir + 2.4 * red +", "mapparams = unmasked.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPoint(geometry, start, end, band):", "indexName, scale, coords, startDate, endDate, reducer): geometry = None indexCollection", "'mosaic'): return imageCollection.mosaic() elif (reducerName == 'first'): return imageCollection.first() elif", "else: eeImage = ee.Image(name) return { 'bands': eeImage.bandNames().getInfo(), 'imageName': name", "bandNamesLandsatTOA).map(lsMaskClouds) s2 = ee.ImageCollection('COPERNICUS/S2') \\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) \\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'],", "anySet = anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return anySet return image.updateMask(isSet(['badPixels', 'cloud', 'shadow',", "metadataCloudCoverMax): def cloudScore(img): def rescale(img, exp, thresholds): return img.expression(exp, {'img':", "return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPoint(geometry, start, end, band): if isinstance(geometry[0], list):", "########## ee.Image ########## def imageToMapId(image, visParams): eeImage = ee.Image(image) mapId", "def cloudScore(img): def rescale(img, exp, thresholds): return img.expression(exp, {'img': img}).subtract(thresholds[0]).divide(thresholds[1]", "return imageCollection.mode() elif (reducerName == 'mosaic'): return imageCollection.mosaic() elif (reducerName", "1)', {'i': img}).rename(['EVI2']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate)", "- red) / (nir + 6.0 * red - 7.5", "name in bandsByCollection: collection = collection.merge(create(name)) return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\ .map(reduceRegion)", "== 'mean'): return imageCollection.mean() elif (reducerName == 'mode'): return imageCollection.mode()", "########## Helper routes ########## def listAvailableBands(name, assetType): eeImage = None", "as ine: imageToMapId(eeFirstImage, visParams) return values ########## ee.FeatureCollection ########## def", "img.expression(exp, {'img': img}).subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) score = ee.Image(1.0) score =", "sentinel2 = ee.ImageCollection('COPERNICUS/S2') f2017s2 = sentinel2.filterDate(startDate, endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax)", "ee.Reducer.max() elif (reducerName == 'mean'): return ee.Reducer.mean() elif (reducerName ==", "sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1 = sentinel1.filterDate(startDate, endDate) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV'))", "'B6', 'B7'], 'LANDSAT/LE07/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LE07/C01/T2_TOA':", "all visible bands. visible = img.select('red').add( img.select('green')).add(img.select('blue')) visible_rescale = visible.subtract(ee.Number(0.2)).divide(", "ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) sentinel1Data = getS1({ \"targetBands\": ['VV',", "(green + nir)', 'NBR': '(nir - swir2) / (nir +", "'swir2'] metadataCloudCoverMax = 100 lt4 = ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than',", "ee.Reducer.mean() elif (reducerName == 'mode'): return ee.Reducer.mode() elif (reducerName ==", "toIndexWithTimeStart(image): time = image.get('system:time_start') image = maskClouds(image) return toIndex(image).set('system:time_start', time)", "all infrared bands. infrared = img.select('nir').add( img.select('swir1')).add(img.select('swir2')) infrared_rescale = infrared.subtract(ee.Number(0.3)).divide(", "ee.Array([[0.977], [1.005], [0.982], [1.001], [1.001], [0.996]]) bias = ee.Array([[-0.00411], [-0.00093],", "if startDate and endDate: return ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart, True) else: return", "[-0.00015], [-0.00097]]) # Make an Array Image, with a 2-D", "sentinel1Data.map(myimageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values", "{ 'url': mapId['tile_fetcher'].url_format } ########## ee.ImageCollection ########## def imageCollectionToMapId(assetId, visParams,", "# TODO, just return URL so the routes are easier", "return filteredImageEVI2ToMapId(startDate, endDate) elif (lowerIndex == 'ndmi'): return filteredImageNDMIToMapId(startDate, endDate)", "'LSAVI': '((nir - red) / (nir + red + 0.5))", "endDate).select(indexName) else: indexCollection = ee.ImageCollection( assetId).filterDate(startDate, endDate) def getIndex(image): theReducer", "2).getMapId(visParams) return mapId['tile_fetcher'].url_format ########## Pre defined ee.ImageCollection ########## # Index", "ee.Image(1.0) # Clouds are reasonably bright in the blue band.", "imageToMapId(eviImage, visParams) def filteredImageNDWIToMapId(startDate, endDate): def calcNDWI(img): return img.expression('(i.green -", "'mean'): return imageCollection.mean() elif (reducerName == 'mode'): return imageCollection.mode() elif", "visible = img.select('red').add( img.select('green')).add(img.select('blue')) visible_rescale = visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2))) score =", "ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage def getClipped(image): return image.clip(geometry)", "imageToMapId(median, visParams) ########## Time Series ########## def getTimeSeriesByCollectionAndIndex(assetId, indexName, scale,", "'red': image.select(bands[2]), 'nir': image.select(bands[3]), 'swir1': image.select(bands[4]), 'swir2': image.select(bands[5]), }).clamp(-1, 1).rename(['index'])", "s2 = ee.ImageCollection('COPERNICUS/S2') \\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) \\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA)", "isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) landsatData", "assetId.lower() if(\"b2\" not in visParams[\"bands\"].lower()): skipCloudMask = True elif (\"lc8\"", "colorPalette = '505050,E8E8E8,00FF33,003300' visParams = {'opacity': 1, 'max': 1, 'min':", "return imageToMapId(median, visParams) ########## Time Series ########## def getTimeSeriesByCollectionAndIndex(assetId, indexName,", "isinstance(val, dict): return val else: try: return json.loads(val) except Exception", "aftDate.strftime('%Y-%m-%d') selectedImage = sentinel1Data.filterDate(start, end).first() selectedImage = ee.Image(selectedImage) mapparams =", "for Type in types: anySet = anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return anySet", "filteredImageByIndexToMapId(startDate, endDate, index): lowerIndex = index.lower() if (lowerIndex == 'ndvi'):", "infrared bands. infrared = img.select('nir').add( img.select('swir1')).add(img.select('swir2')) infrared_rescale = infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3)))", "'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds) le7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\ .filterMetadata('CLOUD_COVER',", "'evi2'): return filteredImageEVI2ToMapId(startDate, endDate) elif (lowerIndex == 'ndmi'): return filteredImageNDMIToMapId(startDate,", "user to select first cloud free image again? def firstCloudFreeImageInMosaicToMapId(assetId,", "'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LC08/C01/T2_TOA': ['B2', 'B3', 'B4', 'B5', 'B6',", "json from ee.ee_exception import EEException from gee.inputs import getLandsat, getS1", "imDate - datetime.timedelta(days=1) aftDate = imDate + datetime.timedelta(days=1) if isinstance(geometry[0],", "ee.Image(selectedImage) mapparams = selectedImage.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPointS1(geometry, start, end):", "sentinel1 = sentinel1.filterDate(startDate, endDate) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH'))", "endDate): def toNatural(img): return ee.Image(10).pow(img.divide(10)) def addRatioBands(img): # not using", "def getFeatureCollectionTileUrl(featureCollection, field, matchID, visParams): fc = ee.FeatureCollection(featureCollection) single =", "########## Degradation########## def getDegradationTileUrlByDateS1(geometry, date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\")", "'NDVI': '(nir - red) / (nir + red)', 'EVI': '2.5", "in lowerAsset): skipCloudMask = False else: skipCloudMask = True if", "image.expression(indexes[indexName], { 'blue': image.select(bands[0]), 'green': image.select(bands[1]), 'red': image.select(bands[2]), 'nir': image.select(bands[3]),", "Array Image, with a 2-D Array per pixel. arrayImage2D =", "ee_key_path=''): try: if ee_account and ee_key_path and os.path.exists(ee_key_path): credentials =", "ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": startDate.strftime('%Y-%m-%d'), \"end\": endDate.strftime('%Y-%m-%d'), \"targetBands\": ['RED',", "1).rename(['index']) def toIndexWithTimeStart(image): time = image.get('system:time_start') image = maskClouds(image) return", "(\"lc8\" in lowerAsset): sID = 'OLI_TIRS' elif (\"le7\" in lowerAsset):", "# Make an Array Image, with a 2-D Array per", "1], 'gamma': 1.6} indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return", "= befDate.strftime('%Y-%m-%d') end = aftDate.strftime('%Y-%m-%d') selectedImage = sentinel1Data.filterDate(start, end).first() selectedImage", "img.B11 + img.B12', [0.3, 0.8])) ndsi = img.normalizedDifference(['B3', 'B11']) return", "= ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) reducedImage = ee.Image(reduceIC(eeCollection, reducer))", "lt4 = ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds)", "- swir2) / (nir + swir2)', 'LSAVI': '((nir - red)", "* (nir - red) / (nir + 6.0 * red", "imageToMapId(eviImage, visParams) def filteredImageByIndexToMapId(startDate, endDate, index): lowerIndex = index.lower() if", "# Index Image Collection def lsMaskClouds(img, cloudThresh=10): score = ee.Image(1.0)", "{'i': img}).rename(['NDWI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette", "!= None: indexCollection = ee.ImageCollection(assetId).filterDate( startDate, endDate).select(indexName) else: indexCollection =", "\"l8\": True} }) selectedImage = landsatData.first() unmasked = ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams", "coords, startDate, endDate, reducer): geometry = None indexCollection = None", "1, 2, 3, 4, 5, 6], 'S2': [1, 2, 3,", "= ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) sentinel1Data = getS1({ \"targetBands\":", "# Clouds are reasonably bright in all visible bands. visible", "ee.ImageCollection('COPERNICUS/S2') f2017s2 = sentinel2.filterDate(startDate, endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) m2017s2 =", "return imageCollection.min() elif (reducerName == 'max'): return imageCollection.max() elif (reducerName", "'less_than', metadataCloudCoverMax) m2017s2 = f2017s2.map(cloudScoreS2) m2017s3 = m2017s2.median() return imageToMapId(m2017s3,", "getReducer(reducer): reducerName = reducer.lower() if(reducerName == 'min'): return ee.Reducer.min() elif", "indexValue = img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start') indexImage =", "image = maskClouds(image) return toIndex(image).set('system:time_start', time) # if startDate and", "= anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return anySet return image.updateMask(isSet(['badPixels', 'cloud', 'shadow', 'cirrus']).Not())", "\\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds) s2 = ee.ImageCollection('COPERNICUS/S2')", "ee.Algorithms.Landsat.simpleComposite( eeCollection, simpleCompositeVariable, 10, 40, True ) return imageToMapId(eeMosaicImage, visParams)", "ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def filteredImageNDVIToMapId(startDate, endDate): def calcNDVI(img): return img.expression('(i.nir - i.red)", "'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'],", "/ (i.nir + i.red)', {'i': img}).rename(['NDVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection", "'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds) lt5 = ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\ .filterMetadata('CLOUD_COVER',", "visParams, startDate, endDate): skipCloudMask = False eeCollection = ee.ImageCollection(assetId) lowerAsset", "'B4', 'B5', 'B7'] } indexes = { 'NDVI': '(nir -", "1)', {'i': img}).rename(['EVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate)", "assetType): eeImage = None if assetType == \"imageCollection\": eeImage =", "(startDate and endDate): eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate)", "########## # Index Image Collection def lsMaskClouds(img, cloudThresh=10): score =", "= {'L8': [1, 2, 3, 4, 5, 9, 6], 'L7':", "vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1 = sentinel1.filterDate(startDate, endDate) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation',", "def calcNDVI(img): return img.expression('(i.nir - i.red) / (i.nir + i.red)',", "if (\"lc8\" in lowerAsset): sID = 'OLI_TIRS' elif (\"le7\" in", "12]} bandNamesLandsatTOA = ['blue', 'green', 'red', 'nir', 'swir1', 'temp', 'swir2']", "= sentinel2.filterDate(startDate, endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) m2017s2 = f2017s2.map(cloudScoreS2) m2017s3", "endDate, reducer): geometry = None indexCollection = None if isinstance(coords[0],", "score = score.min(rescale(img, 'img.B2', [0.1, 0.3])) score = score.min(rescale(img, 'img.B4", "elif (\"lc8\" in lowerAsset): skipCloudMask = False elif (\"le7\" in", "flags set to zero. clear = qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0)) return img.divide(10000).updateMask(clear).set('system:time_start',", "ee_key_path and os.path.exists(ee_key_path): credentials = ee.ServiceAccountCredentials(ee_account, ee_key_path) ee.Initialize(credentials) else: ee.Initialize()", "bands = ['blue', 'green', 'red', 'nir', 'swir1', 'swir2'] # linear", "= img.select('red').add( img.select('green')).add(img.select('blue')) visible_rescale = visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2))) score = score.min(visible_rescale)", "'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4',", "['VV', 'VH', 'VV/VH'], 'region': geometry }).filterDate(start, end) def myimageMapper(img): theReducer", "2.4 * i.red + 1)', {'i': img}).rename(['EVI2']) \\ .set('system:time_start', img.get('system:time_start'))", "elif (reducerName == 'first'): return imageCollection.first() elif (reducerName == 'sum'):", "def myImageMapper(img): theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry, 30)", "1, 2, 3, 4, 5, 7], 'L5': [0, 1, 2,", "simpleCompositeVariable, 10, 40, True ) return imageToMapId(eeMosaicImage, visParams) def filteredSentinelComposite(visParams,", "= ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": start, \"end\": end, \"targetBands\":", "\\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16'", "mapparams['tile_fetcher'].url_format def getDegradationPlotsByPoint(geometry, start, end, band): if isinstance(geometry[0], list): geometry", "mapId = eeImage.getMapId(visParams) # TODO, just return URL so the", "https://landsat.usgs.gov/collectionqualityband \"\"\" typeByValue = { 'badPixels': 15, 'cloud': 16, 'shadow':", "{'i': img}).rename(['NDMI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette", "visParams) except EEException as ine: imageToMapId(eeFirstImage, visParams) return values ##########", "return image.clip(geometry) clippedcollection = indexCollection.map(getClipped) indexCollection1 = clippedcollection.map(getIndex) indexCollection2 =", "end, band): if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry", "indexImage lsd = landsatData.map(myImageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values =", "= landsatData.map(myImageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return", "values = imageToMapId(masked, visParams) else: values = imageToMapId(eeFirstImage, visParams) except", "score.min(blue_rescale) # Clouds are reasonably bright in all visible bands.", "'L7': [0, 1, 2, 3, 4, 5, 7], 'L5': [0,", "11)) # clear if both flags set to zero. clear", "- i.red) / (i.nir + 2.4 * i.red + 1)',", "ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": start, \"end\": end, \"targetBands\": [band],", "'B7'], 'LANDSAT/LC08/C01/T2_TOA': ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LE07/C01/T1_TOA': ['B1',", "sID)) mask = scored.select(['cloud']).lte(20) masked = eeFirstImage.updateMask(mask) values = imageToMapId(masked,", "mapId['tile_fetcher'].url_format ########## Pre defined ee.ImageCollection ########## # Index Image Collection", "'VH')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) sentinel1 = sentinel1.map(toNatural) sentinel1 = sentinel1.map(addRatioBands)", "cloudBitMask = int(math.pow(2, 10)) cirrusBitMask = int(math.pow(2, 11)) # clear", "= ee.Image(1.0) score = score.min(rescale(img, 'img.B2', [0.1, 0.3])) score =", "[1, 2, 3, 7, 11, 10, 12]} bandNamesLandsatTOA = ['blue',", "* red - 7.5 * blue + 1)', 'EVI2': '2.5", "popDict = ciesinPopGrid.reduceRegion( ee.Reducer.sum(), extentGeom, maxPixels=500000000) pop = popDict.get('population-count').getInfo() pop", "not snow. ndsi = img.normalizedDifference(['green', 'swir1']) ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8)))", "endDate): def calcNDMI(img): return img.expression('(i.nir - i.swir1) / (i.nir +", "def initialize(ee_account='', ee_key_path=''): try: if ee_account and ee_key_path and os.path.exists(ee_key_path):", "= ee.Geometry.Point(geometry) sentinel1Data = getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region':", "Helper routes ########## def listAvailableBands(name, assetType): eeImage = None if", "'less_than', metadataCloudCoverMax) \\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA) \\ .map(bandPassAdjustment) return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def", "return {} ########## Helper routes ########## def listAvailableBands(name, assetType): eeImage", "e: print(e) def getReducer(reducer): reducerName = reducer.lower() if(reducerName == 'min'):", "(\"lt5\" in lowerAsset): sID = 'TM' scored = ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID',", "image.select(bands[4]), 'swir2': image.select(bands[5]), }).clamp(-1, 1).rename(['index']) def toIndexWithTimeStart(image): time = image.get('system:time_start')", "return imageToMapId(reducedImage, visParams) # TODO, should we allow user to", "geometry=geometry, scale=scale, maxPixels=1e6) return ee.Feature(None, { 'index': reduced.get('index'), 'timeIndex': [image.get('system:time_start'),", "# Clouds are reasonably cool in temperature. temp_rescale = img.select('temp').subtract(ee.Number(300)).divide(", "lowerAsset): sID = 'ETM' elif (\"lt5\" in lowerAsset): sID =", "reasonably bright in all infrared bands. infrared = img.select('nir').add( img.select('swir1')).add(img.select('swir2'))", "imageCollection.median() def safeParseJSON(val): if isinstance(val, dict): return val else: try:", "return json.loads(val) except Exception as e: try: return json.loads(val.replace(\"'\", \"\\\"\"))", "True ) return imageToMapId(eeMosaicImage, visParams) def filteredSentinelComposite(visParams, startDate, endDate, metadataCloudCoverMax):", "in lowerAsset): sID = 'OLI_TIRS' elif (\"le7\" in lowerAsset): sID", "skipCloudMask = True if (startDate and endDate): eeFilterDate = ee.Filter.date(startDate,", "bandNamesLandsatTOA = ['blue', 'green', 'red', 'nir', 'swir1', 'temp', 'swir2'] metadataCloudCoverMax", "= ee.ImageCollection(name).first() else: eeImage = ee.Image(name) return { 'bands': eeImage.bandNames().getInfo(),", ".filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) \\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA) \\ .map(bandPassAdjustment) return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2))", "- swir1) / (nir + swir1)', 'NDWI': '(green - nir)", "return ee.Reducer.median() def reduceIC(imageCollection, reducer): reducerName = reducer.lower() if(reducerName ==", "ee.Image(eeCollection.map(calcNDWI).mean()) return imageToMapId(eviImage, visParams) def filteredImageByIndexToMapId(startDate, endDate, index): lowerIndex =", "eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) reducedImage = ee.Image(reduceIC(eeCollection,", "/ (green + nir)', 'NBR': '(nir - swir2) / (nir", "[ee.Number(date), indexValue]) return indexImage lsd = sentinel1Data.map(myimageMapper, True) indexCollection2 =", "'LANDSAT/LE07/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T1_TOA': ['B1', 'B2',", "keep = img.select(['temp']) bands = ['blue', 'green', 'red', 'nir', 'swir1',", "else: return imageCollection.median() def safeParseJSON(val): if isinstance(val, dict): return val", "indexCollection2.getInfo() def getTimeSeriesByIndex(indexName, scale, coords, startDate, endDate, reducer): bandsByCollection =", "end): if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry =", "if(skipCloudMask == False): sID = '' if (\"lc8\" in lowerAsset):", "per pixel. arrayImage2D = img.select(bands).toArray().toArray(1) # apply correction factors and", "= None if assetType == \"imageCollection\": eeImage = ee.ImageCollection(name).first() else:", "endDate) colorPalette = 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams = {'opacity': 1, 'max': 1,", "def imageCollectionToMapId(assetId, visParams, reducer, startDate, endDate): eeCollection = ee.ImageCollection(assetId) if", "indexCollection.map(getClipped) indexCollection1 = clippedcollection.map(getIndex) indexCollection2 = indexCollection1.aggregate_array('indexValue') return indexCollection2.getInfo() def", "ee.FeatureCollection ########## def getFeatureCollectionTileUrl(featureCollection, field, matchID, visParams): fc = ee.FeatureCollection(featureCollection)", "reduced.get('index'), 'timeIndex': [image.get('system:time_start'), reduced.get('index')] }) geometry = None if isinstance(coords[0],", "\\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) sentinel1", "+ i.red)', {'i': img}).rename(['NDVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate,", "in lowerAsset): skipCloudMask = False elif (\"le7\" in lowerAsset): skipCloudMask", "geometry, 30) date = img.get('system:time_start') visParams = {'bands': ['VV', 'VH',", "'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDMI).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDWIToMapId(startDate,", "return ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart, True) else: return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True) def reduceRegion(image):", "ee.Image(0) for Type in types: anySet = anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return", "in temperature. temp_rescale = img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300))) score = score.min(temp_rescale) #", "(lowerIndex == 'ndmi'): return filteredImageNDMIToMapId(startDate, endDate) elif (lowerIndex == 'ndwi'):", "json.loads(val.replace(\"'\", \"\\\"\")) except Exception as e: return {} ########## Helper", "score.lt(cloudThresh).rename(['cloudMask']) img = img.updateMask(mask) return img.addBands(score) def s2MaskClouds(img): qa =", "10 and 11 are clouds and cirrus, respectively. cloudBitMask =", "= img.select('QA60') # Bits 10 and 11 are clouds and", "2, 3, 4, 5, 6], 'L4': [0, 1, 2, 3,", "= img.select(['temp']) bands = ['blue', 'green', 'red', 'nir', 'swir1', 'swir2']", "30) date = img.get('system:time_start') visParams = {'bands': ['VV', 'VH', 'ratioVVVH'],", "values = indexCollection2.getInfo() return values def getDegradationTileUrlByDate(geometry, date, visParams): imDate", "img.select('swir1')).add(img.select('swir2')) infrared_rescale = infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3))) score = score.min(infrared_rescale) # Clouds", "{'bands': ['VV', 'VH', 'ratioVVVH'], 'min': [-15, -25, .40], 'max': [0,", "median = sentinel1.median() return imageToMapId(median, visParams) ########## Time Series ##########", "'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDMI).mean()) return imageToMapId(eviImage, visParams)", "rescale = img.divide(10000) score = cloudScore(rescale).multiply(100).rename('cloudscore') return img.addBands(score) sentinel2 =", "None) \\ .aggregate_array('timeIndex') \\ .getInfo() ########## Degradation########## def getDegradationTileUrlByDateS1(geometry, date,", "minElev = minmaxElev.get('elevation_min').getInfo() maxElev = minmaxElev.get('elevation_max').getInfo() ciesinPopGrid = ee.Image('CIESIN/GPWv4/population-count/2020') popDict", "temp_rescale = img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300))) score = score.min(temp_rescale) # However, clouds", "img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300))) score = score.min(temp_rescale) # However, clouds are not", "sID = '' if (\"lc8\" in lowerAsset): sID = 'OLI_TIRS'", "adjustment gain = ee.Array([[0.977], [1.005], [0.982], [1.001], [1.001], [0.996]]) bias", "= False elif (\"lt5\" in lowerAsset): skipCloudMask = False else:", "calcNDWI(img): return img.expression('(i.green - i.nir) / (i.green + i.nir)', {'i':", "(reducerName == 'sum'): return ee.Reducer.sum() else: return ee.Reducer.median() def reduceIC(imageCollection,", "img}).rename(['EVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette =", "list): geometry = ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) landsatData =", "'EVI2': '2.5 * (nir - red) / (nir + 2.4", "score = score.min( rescale(img, 'img.B8 + img.B11 + img.B12', [0.3,", "getReducer(reducer) if indexName != None: indexValue = image.reduceRegion( theReducer, geometry,", "(lowerIndex == 'evi'): return filteredImageEVIToMapId(startDate, endDate) elif (lowerIndex == 'evi2'):", "'first'): return imageCollection.first() elif (reducerName == 'sum'): return imageCollection.sum() else:", "calcNDVI(img): return img.expression('(i.nir - i.red) / (i.nir + i.red)', {'i':", "= img.divide(10000) score = cloudScore(rescale).multiply(100).rename('cloudscore') return img.addBands(score) sentinel2 = ee.ImageCollection('COPERNICUS/S2')", "img.select('red').add( img.select('green')).add(img.select('blue')) visible_rescale = visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2))) score = score.min(visible_rescale) #", "import math import sys import json from ee.ee_exception import EEException", "'timeIndex': [image.get('system:time_start'), reduced.get('index')] }) geometry = None if isinstance(coords[0], list)", "= maskClouds(image) return toIndex(image).set('system:time_start', time) # if startDate and endDate:", "def addRatioBands(img): # not using angle band vv = img.select('VV')", "None indexCollection = None if isinstance(coords[0], list): geometry = ee.Geometry.Polygon(coords)", "eeImage = ee.Image(image) mapId = eeImage.getMapId(visParams) # TODO, just return", "(reducerName == 'sum'): return imageCollection.sum() else: return imageCollection.median() def safeParseJSON(val):", "indexValue]) return indexImage def getClipped(image): return image.clip(geometry) clippedcollection = indexCollection.map(getClipped)", "ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds) lc8 =", "}) geometry = None if isinstance(coords[0], list) or isinstance(coords[0], tuple):", "########## Time Series ########## def getTimeSeriesByCollectionAndIndex(assetId, indexName, scale, coords, startDate,", "s2MaskClouds(img): qa = img.select('QA60') # Bits 10 and 11 are", "- 7.5 * i.blue + 1)', {'i': img}).rename(['EVI']) \\ .set('system:time_start',", "img.expression('2.5 * (i.nir - i.red) / (i.nir + 6.0 *", "reducer)) return imageToMapId(reducedImage, visParams) # TODO, should we allow user", "visible bands. visible = img.select('red').add( img.select('green')).add(img.select('blue')) visible_rescale = visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2)))", "'first'): return ee.Reducer.first() elif (reducerName == 'last'): return ee.Reducer.last() elif", "\"l7\": False, \"l8\": True} }) selectedImage = landsatData.first() unmasked =", "image.updateMask(isSet(['badPixels', 'cloud', 'shadow', 'cirrus']).Not()) def toIndex(image): bands = bandsByCollection[name] return", "sID = 'TM' scored = ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID', sID)) mask =", "imageCollection.mean() elif (reducerName == 'mode'): return imageCollection.mode() elif (reducerName ==", "endDate) eeCollection = eeCollection.filter(eeFilterDate) eeFirstImage = ee.Image(eeCollection.mosaic()) try: if(skipCloudMask ==", "ee.Number(0.6).subtract(ee.Number(0.8))) score = score.min(ndsi_rescale).multiply(100).byte() mask = score.lt(cloudThresh).rename(['cloudMask']) img = img.updateMask(mask)", "False elif (\"le7\" in lowerAsset): skipCloudMask = False elif (\"lt5\"", "== \"imageCollection\": eeImage = ee.ImageCollection(name).first() else: eeImage = ee.Image(name) return", "True elif (\"lc8\" in lowerAsset): skipCloudMask = False elif (\"le7\"", "} anySet = ee.Image(0) for Type in types: anySet =", "sID = 'ETM' elif (\"lt5\" in lowerAsset): sID = 'TM'", "metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds) lt5 = ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than',", "= ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds) lc8", "reducer.lower() if(reducerName == 'min'): return imageCollection.min() elif (reducerName == 'max'):", "endDate) elif (lowerIndex == 'ndwi'): return filteredImageNDWIToMapId(startDate, endDate) def filteredImageCompositeToMapId(assetId,", "img.expression('2.5 * (i.nir - i.red) / (i.nir + 2.4 *", "imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") startDate = imDate - datetime.timedelta(days=1) endDate", "indexValue = image.reduceRegion( theReducer, geometry, scale).get(indexName) else: indexValue = image.reduceRegion(theReducer,", "ee_key_path) ee.Initialize(credentials) else: ee.Initialize() except Exception as e: print(e) def", "True if (startDate and endDate): eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection", "return filteredImageNDMIToMapId(startDate, endDate) elif (lowerIndex == 'ndwi'): return filteredImageNDWIToMapId(startDate, endDate)", "swir2) / (nir + swir2)', 'LSAVI': '((nir - red) /", "'not_equals', None) \\ .aggregate_array('timeIndex') \\ .getInfo() ########## Degradation########## def getDegradationTileUrlByDateS1(geometry,", "= ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": startDate.strftime('%Y-%m-%d'), \"end\": endDate.strftime('%Y-%m-%d'), \"targetBands\":", "= { 'badPixels': 15, 'cloud': 16, 'shadow': 256, 'snow': 1024,", "sID = 'OLI_TIRS' elif (\"le7\" in lowerAsset): sID = 'ETM'", "lsd = sentinel1Data.map(myimageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo()", "{'i': img}).rename(['EVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette", "componentsImage = ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\ .arrayProject([0]).arrayFlatten([bands]).float() # .set('system:time_start',img.get('system:time_start')); return keep.addBands(componentsImage) def", "lsMaskClouds(img, cloudThresh=10): score = ee.Image(1.0) # Clouds are reasonably bright", "extentGeom, maxPixels=500000000) pop = popDict.get('population-count').getInfo() pop = int(pop) return {", "def filteredImageNDVIToMapId(startDate, endDate): def calcNDVI(img): return img.expression('(i.nir - i.red) /", "startDate, endDate, metadataCloudCoverMax): def cloudScore(img): def rescale(img, exp, thresholds): return", "easier to deduce whats being returned. return { 'url': mapId['tile_fetcher'].url_format", "visParams) def filteredImageEVIToMapId(startDate, endDate): def calcEVI(img): return img.expression('2.5 * (i.nir", "nir) / (green + nir)', 'NBR': '(nir - swir2) /", "True} }) def myImageMapper(img): theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer,", ".set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams", "'swir1', 'swir2'] # linear regression coefficients for adjustment gain =", "Image Collection def lsMaskClouds(img, cloudThresh=10): score = ee.Image(1.0) # Clouds", "image.get('system:time_start') image = maskClouds(image) return toIndex(image).set('system:time_start', time) # if startDate", "return img.addBands(score) sentinel2 = ee.ImageCollection('COPERNICUS/S2') f2017s2 = sentinel2.filterDate(startDate, endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE',", ".arrayProject([0]).arrayFlatten([bands]).float() # .set('system:time_start',img.get('system:time_start')); return keep.addBands(componentsImage) def getLandSatMergedCollection(): sensorBandDictLandsatTOA = {'L8':", "= getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '505050,E8E8E8,00FF33,003300' visParams = {'opacity': 1,", "eviImage = ee.Image(eeCollection.map(calcEVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVI2ToMapId(startDate, endDate): def", "free image again? def firstCloudFreeImageInMosaicToMapId(assetId, visParams, startDate, endDate): skipCloudMask =", "= indexCollection1.aggregate_array('indexValue') return indexCollection2.getInfo() def getTimeSeriesByIndex(indexName, scale, coords, startDate, endDate,", "infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3))) score = score.min(infrared_rescale) # Clouds are reasonably cool", "img.updateMask(mask) return img.addBands(score) def s2MaskClouds(img): qa = img.select('QA60') # Bits", "{\"l4\": True, \"l5\": True, \"l7\": True, \"l8\": True} }) def", "EEException from gee.inputs import getLandsat, getS1 ########## Helper functions ##########", "def filteredImageByIndexToMapId(startDate, endDate, index): lowerIndex = index.lower() if (lowerIndex ==", "bands. infrared = img.select('nir').add( img.select('swir1')).add(img.select('swir2')) infrared_rescale = infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3))) score", "'B7'], 'LANDSAT/LT05/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T2_TOA': ['B1',", "i.blue + 1)', {'i': img}).rename(['EVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection =", "Clouds are reasonably bright in all infrared bands. infrared =", "bandsByCollection = { 'LANDSAT/LC08/C01/T1_TOA': ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'],", "'sum'): return imageCollection.sum() else: return imageCollection.median() def safeParseJSON(val): if isinstance(val,", "skipCloudMask = False eeCollection = ee.ImageCollection(assetId) lowerAsset = assetId.lower() if(\"b2\"", "ee.Reducer.last() elif (reducerName == 'sum'): return ee.Reducer.sum() else: return ee.Reducer.median()", "'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return anySet return image.updateMask(isSet(['badPixels', 'cloud', 'shadow', 'cirrus']).Not()) def toIndex(image):", "= ee.Image().set( 'indexValue', [ee.Number(date), indexValue] ) return indexImage lsd =", "TODO, just return URL so the routes are easier to", "getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams = {'opacity': 1, 'max':", "/ (nir + 6.0 * red - 7.5 * blue", "score = score.min(infrared_rescale) # Clouds are reasonably cool in temperature.", "eviImage = ee.Image(eeCollection.map(calcEVI2).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDMIToMapId(startDate, endDate): def", "{'img': img}).subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) score = ee.Image(1.0) score = score.min(rescale(img,", "== 'evi'): return filteredImageEVIToMapId(startDate, endDate) elif (lowerIndex == 'evi2'): return", "(nir - red) / (nir + 6.0 * red -", "return values def getDegradationTileUrlByDate(geometry, date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\")", "i.red - 7.5 * i.blue + 1)', {'i': img}).rename(['EVI']) \\", "toIndex(image): bands = bandsByCollection[name] return image.expression(indexes[indexName], { 'blue': image.select(bands[0]), 'green':", "if(reducerName == 'min'): return imageCollection.min() elif (reducerName == 'max'): return", "img.get('system:time_start') visParams = {'bands': ['VV', 'VH', 'ratioVVVH'], 'min': [-15, -25,", "img.expression('(i.green - i.nir) / (i.green + i.nir)', {'i': img}).rename(['NDWI']) \\", "(\"lc8\" in lowerAsset): skipCloudMask = False elif (\"le7\" in lowerAsset):", "- i.red) / (i.nir + 6.0 * i.red - 7.5", "# linear regression coefficients for adjustment gain = ee.Array([[0.977], [1.005],", "4, 5, 7], 'L5': [0, 1, 2, 3, 4, 5,", "visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") startDate = imDate - datetime.timedelta(days=1)", "\\ .filterMetadata('index', 'not_equals', None) \\ .aggregate_array('timeIndex') \\ .getInfo() ########## Degradation##########", "Exception as e: try: return json.loads(val.replace(\"'\", \"\\\"\")) except Exception as", "a 2-D Array per pixel. arrayImage2D = img.select(bands).toArray().toArray(1) # apply", "ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds) le7 =", "Collection def lsMaskClouds(img, cloudThresh=10): score = ee.Image(1.0) # Clouds are", "img.B3 + img.B2', [0.2, 0.8])) score = score.min( rescale(img, 'img.B8", "= img.select(bands).toArray().toArray(1) # apply correction factors and reproject array to", "i.swir1) / (i.nir + i.swir1)', {'i': img}).rename(['NDMI']) \\ .set('system:time_start', img.get('system:time_start'))", "indexCollection2.getInfo() return values def getDegradationTileUrlByDate(geometry, date, visParams): imDate = datetime.datetime.strptime(date,", "10, 40, True ) return imageToMapId(eeMosaicImage, visParams) def filteredSentinelComposite(visParams, startDate,", "credentials = ee.ServiceAccountCredentials(ee_account, ee_key_path) ee.Initialize(credentials) else: ee.Initialize() except Exception as", "}) def myImageMapper(img): theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry,", "eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) eeFirstImage = ee.Image(eeCollection.mosaic())", "= f2017s2.map(cloudScoreS2) m2017s3 = m2017s2.median() return imageToMapId(m2017s3, visParams) def filteredSentinelSARComposite(visParams,", "return score.min(rescale(ndsi, 'img', [0.8, 0.6])) def cloudScoreS2(img): rescale = img.divide(10000)", "score.min(infrared_rescale) # Clouds are reasonably cool in temperature. temp_rescale =", "ee.Image(image) mapId = eeImage.getMapId(visParams) # TODO, just return URL so", "cloudScore(rescale).multiply(100).rename('cloudscore') return img.addBands(score) sentinel2 = ee.ImageCollection('COPERNICUS/S2') f2017s2 = sentinel2.filterDate(startDate, endDate).filterMetadata(", "nir)', 'NBR': '(nir - swir2) / (nir + swir2)', 'LSAVI':", "getStatistics(extent): extentGeom = ee.Geometry.Polygon(extent) elev = ee.Image('USGS/GTOPO30') minmaxElev = elev.reduceRegion(", "'evi'): return filteredImageEVIToMapId(startDate, endDate) elif (lowerIndex == 'evi2'): return filteredImageEVI2ToMapId(startDate,", "vh.divide(vv).rename('VH/VV') return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1 = sentinel1.filterDate(startDate, endDate)", "if(reducerName == 'min'): return ee.Reducer.min() elif (reducerName == 'max'): return", "end = aftDate.strftime('%Y-%m-%d') selectedImage = sentinel1Data.filterDate(start, end).first() selectedImage = ee.Image(selectedImage)", "anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return anySet return image.updateMask(isSet(['badPixels', 'cloud', 'shadow', 'cirrus']).Not()) def", "startDate, endDate): def toNatural(img): return ee.Image(10).pow(img.divide(10)) def addRatioBands(img): # not", ".filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds) lc8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\", "def create(name): def maskClouds(image): def isSet(types): \"\"\" https://landsat.usgs.gov/collectionqualityband \"\"\" typeByValue", "filteredImageNDVIToMapId(startDate, endDate) elif (lowerIndex == 'evi'): return filteredImageEVIToMapId(startDate, endDate) elif", "eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams = {'opacity':", "def getDegradationTileUrlByDateS1(geometry, date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") befDate =", "eeCollection = ee.ImageCollection(assetId) if (startDate and endDate): eeFilterDate = ee.Filter.date(startDate,", "filteredImageNDVIToMapId(startDate, endDate): def calcNDVI(img): return img.expression('(i.nir - i.red) / (i.nir", "(startDate and endDate): eeCollection = eeCollection.filterDate(startDate, endDate) eeCollection.filterMetadata( 'CLOUD_COVER', 'less_than',", "# clear if both flags set to zero. clear =", "theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry, 30) date =", "+ 6.0 * red - 7.5 * blue + 1)',", "imageToMapId(reducedImage, visParams) # TODO, should we allow user to select", "pop = int(pop) return { 'minElev': minElev, 'maxElev': maxElev, 'pop':", "(reducerName == 'mode'): return imageCollection.mode() elif (reducerName == 'mosaic'): return", "theReducer = getReducer(reducer) reduced = image.reduceRegion( theReducer, geometry=geometry, scale=scale, maxPixels=1e6)", "\"\"\" typeByValue = { 'badPixels': 15, 'cloud': 16, 'shadow': 256,", "image.select(bands[2]), 'nir': image.select(bands[3]), 'swir1': image.select(bands[4]), 'swir2': image.select(bands[5]), }).clamp(-1, 1).rename(['index']) def", "= int(math.pow(2, 10)) cirrusBitMask = int(math.pow(2, 11)) # clear if", "= score.lt(cloudThresh).rename(['cloudMask']) img = img.updateMask(mask) return img.addBands(score) def s2MaskClouds(img): qa", "ee.ee_exception import EEException from gee.inputs import getLandsat, getS1 ########## Helper", "# Clouds are reasonably bright in the blue band. blue_rescale", "return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPointS1(geometry, start, end): if isinstance(geometry[0], list): geometry", "respectively. cloudBitMask = int(math.pow(2, 10)) cirrusBitMask = int(math.pow(2, 11)) #", "= eeImage.getMapId(visParams) # TODO, just return URL so the routes", "False else: skipCloudMask = True if (startDate and endDate): eeFilterDate", "sensorBandDictLandsatTOA = {'L8': [1, 2, 3, 4, 5, 9, 6],", "return anySet return image.updateMask(isSet(['badPixels', 'cloud', 'shadow', 'cirrus']).Not()) def toIndex(image): bands", "ee.Number(0.3).subtract(ee.Number(0.1))) score = score.min(blue_rescale) # Clouds are reasonably bright in", "2, 3, 4, 5, 6], 'S2': [1, 2, 3, 7,", "-1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDMI).mean()) return imageToMapId(eviImage, visParams) def", "import json from ee.ee_exception import EEException from gee.inputs import getLandsat,", "anySet = ee.Image(0) for Type in types: anySet = anySet.Or(image.select(", "* i.red + 1)', {'i': img}).rename(['EVI2']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection", "functions ########## def initialize(ee_account='', ee_key_path=''): try: if ee_account and ee_key_path", "img.addBands(score) def s2MaskClouds(img): qa = img.select('QA60') # Bits 10 and", "(i.green + i.nir)', {'i': img}).rename(['NDWI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection =", "getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry}) start = befDate.strftime('%Y-%m-%d')", "return mapId['tile_fetcher'].url_format ########## Pre defined ee.ImageCollection ########## # Index Image", "isinstance(coords[0], list): geometry = ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) if", "visParams) def filteredImageByIndexToMapId(startDate, endDate, index): lowerIndex = index.lower() if (lowerIndex", "'swir2': image.select(bands[5]), }).clamp(-1, 1).rename(['index']) def toIndexWithTimeStart(image): time = image.get('system:time_start') image", "befDate = imDate - datetime.timedelta(days=1) aftDate = imDate + datetime.timedelta(days=1)", "addRatioBands(img): # not using angle band vv = img.select('VV') vh", "infrared_rescale = infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3))) score = score.min(infrared_rescale) # Clouds are", "datetime.timedelta(days=1) if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry =", "so the routes are easier to deduce whats being returned.", "= score.min( rescale(img, 'img.B8 + img.B11 + img.B12', [0.3, 0.8]))", "img}).rename(['NDVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette =", "= indexCollection2.getInfo() return values def getDegradationTileUrlByDate(geometry, date, visParams): imDate =", "endDate): eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) eeFirstImage =", "getDegradationTileUrlByDateS1(geometry, date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") befDate = imDate", "bandNamesLandsatTOA).map(lsMaskClouds) lc8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L8'],", "ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1 = sentinel1.filterDate(startDate, endDate) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation',", "endDate): eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) reducedImage =", "try: if(skipCloudMask == False): sID = '' if (\"lc8\" in", "from gee.inputs import getLandsat, getS1 ########## Helper functions ########## def", "score = ee.Image(1.0) score = score.min(rescale(img, 'img.B2', [0.1, 0.3])) score", "'img.B8 + img.B11 + img.B12', [0.3, 0.8])) ndsi = img.normalizedDifference(['B3',", "image.reduceRegion(theReducer, geometry, scale) date = image.get('system:time_start') indexImage = ee.Image().set( 'indexValue',", "'0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams = {'opacity': 1, 'max': 1, 'min': -1, 'palette':", "= fc.filter(ee.Filter.equals(field, matchID)) mapId = ee.Image().paint(single, 0, 2).getMapId(visParams) return mapId['tile_fetcher'].url_format", "= visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2))) score = score.min(visible_rescale) # Clouds are reasonably", "masked = eeFirstImage.updateMask(mask) values = imageToMapId(masked, visParams) else: values =", "reducerName = reducer.lower() if(reducerName == 'min'): return ee.Reducer.min() elif (reducerName", "def calcNDMI(img): return img.expression('(i.nir - i.swir1) / (i.nir + i.swir1)',", "ee import math import sys import json from ee.ee_exception import", "[0.00094], [-0.00029], [-0.00015], [-0.00097]]) # Make an Array Image, with", "= ee.ImageCollection(assetId).filterDate( startDate, endDate).select(indexName) else: indexCollection = ee.ImageCollection( assetId).filterDate(startDate, endDate)", "16, 'shadow': 256, 'snow': 1024, 'cirrus': 4096 } anySet =", "'L5': [0, 1, 2, 3, 4, 5, 6], 'L4': [0,", "img.select('VH') vv_vh = vv.divide(vh).rename('VV/VH') vh_vv = vh.divide(vv).rename('VH/VV') return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1", "colorPalette = 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams = {'opacity': 1, 'max': 1, 'min':", "image again? def firstCloudFreeImageInMosaicToMapId(assetId, visParams, startDate, endDate): skipCloudMask = False", "= image.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage", "def getDegradationPlotsByPointS1(geometry, start, end): if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry)", "\"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry }).filterDate(start, end) def myimageMapper(img):", "return indexImage lsd = landsatData.map(myImageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values", "'imageName': name } ########## ee.Image ########## def imageToMapId(image, visParams): eeImage", "def safeParseJSON(val): if isinstance(val, dict): return val else: try: return", "mapId = ee.Image().paint(single, 0, 2).getMapId(visParams) return mapId['tile_fetcher'].url_format ########## Pre defined", "= ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds) s2", "= True elif (\"lc8\" in lowerAsset): skipCloudMask = False elif", "visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2))) score = score.min(visible_rescale) # Clouds are reasonably bright", "ee.ImageCollection( assetId).filterDate(startDate, endDate) def getIndex(image): theReducer = getReducer(reducer) if indexName", "img}).rename(['NDMI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette =", "getTimeSeriesByIndex(indexName, scale, coords, startDate, endDate, reducer): bandsByCollection = { 'LANDSAT/LC08/C01/T1_TOA':", "thresholds): return img.expression(exp, {'img': img}).subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) score = ee.Image(1.0)", "'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI2).mean()) return imageToMapId(eviImage, visParams)", "imageCollection.sum() else: return imageCollection.median() def safeParseJSON(val): if isinstance(val, dict): return", "maskClouds(image) return toIndex(image).set('system:time_start', time) # if startDate and endDate: return", "'VV')) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) sentinel1 = sentinel1.map(toNatural)", "ee.Initialize(credentials) else: ee.Initialize() except Exception as e: print(e) def getReducer(reducer):", "cool in temperature. temp_rescale = img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300))) score = score.min(temp_rescale)", "elif (lowerIndex == 'ndmi'): return filteredImageNDMIToMapId(startDate, endDate) elif (lowerIndex ==", "'VV/VH'], 'region': geometry }).filterDate(start, end) def myimageMapper(img): theReducer = ee.Reducer.mean()", "and endDate): eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) eeFirstImage", "ee.Geometry.Point(geometry) sentinel1Data = getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry", "eeCollection.filter(eeFilterDate) reducedImage = ee.Image(reduceIC(eeCollection, reducer)) return imageToMapId(reducedImage, visParams) # TODO,", "= getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams = {'opacity': 1,", "########## Stats ########## def getStatistics(extent): extentGeom = ee.Geometry.Polygon(extent) elev =", "gain = ee.Array([[0.977], [1.005], [0.982], [1.001], [1.001], [0.996]]) bias =", "== 'evi2'): return filteredImageEVI2ToMapId(startDate, endDate) elif (lowerIndex == 'ndmi'): return", "reduced.get('index')] }) geometry = None if isinstance(coords[0], list) or isinstance(coords[0],", "None if assetType == \"imageCollection\": eeImage = ee.ImageCollection(name).first() else: eeImage", "'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5',", "types: anySet = anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return anySet return image.updateMask(isSet(['badPixels', 'cloud',", "########## def getStatistics(extent): extentGeom = ee.Geometry.Polygon(extent) elev = ee.Image('USGS/GTOPO30') minmaxElev", "ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start') visParams", "+ img.B11 + img.B12', [0.3, 0.8])) ndsi = img.normalizedDifference(['B3', 'B11'])", "image.select(bands[0]), 'green': image.select(bands[1]), 'red': image.select(bands[2]), 'nir': image.select(bands[3]), 'swir1': image.select(bands[4]), 'swir2':", "[1.001], [1.001], [0.996]]) bias = ee.Array([[-0.00411], [-0.00093], [0.00094], [-0.00029], [-0.00015],", "visParams = {'bands': ['VV', 'VH', 'ratioVVVH'], 'min': [-15, -25, .40],", "True) indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values def", "ee.Image('CIESIN/GPWv4/population-count/2020') popDict = ciesinPopGrid.reduceRegion( ee.Reducer.sum(), extentGeom, maxPixels=500000000) pop = popDict.get('population-count').getInfo()", "and endDate): eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) reducedImage", "\"imageCollection\": eeImage = ee.ImageCollection(name).first() else: eeImage = ee.Image(name) return {", "routes are easier to deduce whats being returned. return {", "cirrus, respectively. cloudBitMask = int(math.pow(2, 10)) cirrusBitMask = int(math.pow(2, 11))", "'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams = {'opacity': 1, 'max': 1, 'min': -1, 'palette':", "if isinstance(coords[0], list): geometry = ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords)", "elif (reducerName == 'mean'): return imageCollection.mean() elif (reducerName == 'mode'):", "score = score.min(ndsi_rescale).multiply(100).byte() mask = score.lt(cloudThresh).rename(['cloudMask']) img = img.updateMask(mask) return", "'B3', 'B4', 'B5', 'B7'] } indexes = { 'NDVI': '(nir", "red + 1)', 'NDMI': '(nir - swir1) / (nir +", "2, 3, 4, 5, 9, 6], 'L7': [0, 1, 2,", "img}).rename(['NDWI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette =", "ee.ImageCollection(assetId) lowerAsset = assetId.lower() if(\"b2\" not in visParams[\"bands\"].lower()): skipCloudMask =", "toIndex(image).set('system:time_start', time) # if startDate and endDate: return ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart,", "Stats ########## def getStatistics(extent): extentGeom = ee.Geometry.Polygon(extent) elev = ee.Image('USGS/GTOPO30')", "and cirrus, respectively. cloudBitMask = int(math.pow(2, 10)) cirrusBitMask = int(math.pow(2,", "15, 'cloud': 16, 'shadow': 256, 'snow': 1024, 'cirrus': 4096 }", "########## Pre defined ee.ImageCollection ########## # Index Image Collection def", "import EEException from gee.inputs import getLandsat, getS1 ########## Helper functions", "\\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds) lt5 = ee.ImageCollection('LANDSAT/LT5_L1T_TOA')", ".filterMetadata('index', 'not_equals', None) \\ .aggregate_array('timeIndex') \\ .getInfo() ########## Degradation########## def", "= imDate - datetime.timedelta(days=1) endDate = imDate + datetime.timedelta(days=1) if", "elif (reducerName == 'mode'): return imageCollection.mode() elif (reducerName == 'mosaic'):", "we allow user to select first cloud free image again?", "def myimageMapper(img): theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry, 30)", "'swir1': image.select(bands[4]), 'swir2': image.select(bands[5]), }).clamp(-1, 1).rename(['index']) def toIndexWithTimeStart(image): time =", "'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVI2ToMapId(startDate,", "return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def filteredImageNDVIToMapId(startDate, endDate): def calcNDVI(img): return img.expression('(i.nir -", "[1, 2, 3, 4, 5, 9, 6], 'L7': [0, 1,", "'B5', 'B7'] } indexes = { 'NDVI': '(nir - red)", "== 'ndvi'): return filteredImageNDVIToMapId(startDate, endDate) elif (lowerIndex == 'evi'): return", "-10, 1], 'gamma': 1.6} indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue])", "= '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams = {'opacity': 1, 'max': 1, 'min': -1,", "'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4',", "bright in all infrared bands. infrared = img.select('nir').add( img.select('swir1')).add(img.select('swir2')) infrared_rescale", "- thresholds[0]) score = ee.Image(1.0) score = score.min(rescale(img, 'img.B2', [0.1,", "e: try: return json.loads(val.replace(\"'\", \"\\\"\")) except Exception as e: return", "\"targetBands\": [band], \"region\": geometry, \"sensors\": {\"l4\": True, \"l5\": True, \"l7\":", "5, 9, 6], 'L7': [0, 1, 2, 3, 4, 5,", "reduced = image.reduceRegion( theReducer, geometry=geometry, scale=scale, maxPixels=1e6) return ee.Feature(None, {", "= ee.Image(selectedImage) mapparams = selectedImage.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPointS1(geometry, start,", "return values ########## Stats ########## def getStatistics(extent): extentGeom = ee.Geometry.Polygon(extent)", "scored.select(['cloud']).lte(20) masked = eeFirstImage.updateMask(mask) values = imageToMapId(masked, visParams) else: values", "= ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds) le7", "def reduceIC(imageCollection, reducer): reducerName = reducer.lower() if(reducerName == 'min'): return", "indexCollection2 = indexCollection1.aggregate_array('indexValue') return indexCollection2.getInfo() def getTimeSeriesByIndex(indexName, scale, coords, startDate,", "\"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry}) start = befDate.strftime('%Y-%m-%d') end", "selectedImage = ee.Image(selectedImage) mapparams = selectedImage.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPointS1(geometry,", "########## def getTimeSeriesByCollectionAndIndex(assetId, indexName, scale, coords, startDate, endDate, reducer): geometry", "date = img.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue] )", "endDate, metadataCloudCoverMax): def cloudScore(img): def rescale(img, exp, thresholds): return img.expression(exp,", "'VH', 'VV/VH'], 'region': geometry}) start = befDate.strftime('%Y-%m-%d') end = aftDate.strftime('%Y-%m-%d')", "True} }) selectedImage = landsatData.first() unmasked = ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams =", "= ee.Image(eeCollection.map(calcNDVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVIToMapId(startDate, endDate): def calcEVI(img):", "bandsByCollection[name] return image.expression(indexes[indexName], { 'blue': image.select(bands[0]), 'green': image.select(bands[1]), 'red': image.select(bands[2]),", "imageToMapId(eeFirstImage, visParams) return values ########## ee.FeatureCollection ########## def getFeatureCollectionTileUrl(featureCollection, field,", "bands. visible = img.select('red').add( img.select('green')).add(img.select('blue')) visible_rescale = visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2))) score", "img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'c9c0bf,435ebf,eee8aa,006400' visParams =", "- i.nir) / (i.green + i.nir)', {'i': img}).rename(['NDWI']) \\ .set('system:time_start',", "= minmaxElev.get('elevation_max').getInfo() ciesinPopGrid = ee.Image('CIESIN/GPWv4/population-count/2020') popDict = ciesinPopGrid.reduceRegion( ee.Reducer.sum(), extentGeom,", "<filename>src/py/gee/utils.py import datetime import os import ee import math import", "as e: return {} ########## Helper routes ########## def listAvailableBands(name,", "elif (reducerName == 'sum'): return ee.Reducer.sum() else: return ee.Reducer.median() def", "Index Image Collection def lsMaskClouds(img, cloudThresh=10): score = ee.Image(1.0) #", "However, clouds are not snow. ndsi = img.normalizedDifference(['green', 'swir1']) ndsi_rescale", "eeCollection = ee.ImageCollection(assetId) lowerAsset = assetId.lower() if(\"b2\" not in visParams[\"bands\"].lower()):", "lowerAsset = assetId.lower() if(\"b2\" not in visParams[\"bands\"].lower()): skipCloudMask = True", "'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LE07/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5',", "landsatData = getLandsat({ \"start\": startDate.strftime('%Y-%m-%d'), \"end\": endDate.strftime('%Y-%m-%d'), \"targetBands\": ['RED', 'GREEN',", "\\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) sentinel1 = sentinel1.map(toNatural) sentinel1", "eeCollection.filterDate(startDate, endDate) eeCollection.filterMetadata( 'CLOUD_COVER', 'less_than', metadataCloudCoverMax ) eeMosaicImage = ee.Algorithms.Landsat.simpleComposite(", "endDate = imDate + datetime.timedelta(days=1) if isinstance(geometry[0], list): geometry =", "imageToMapId(eeFirstImage, visParams) except EEException as ine: imageToMapId(eeFirstImage, visParams) return values", "metadataCloudCoverMax) m2017s2 = f2017s2.map(cloudScoreS2) m2017s3 = m2017s2.median() return imageToMapId(m2017s3, visParams)", "return img.expression('2.5 * (i.nir - i.red) / (i.nir + 6.0", "Array per pixel. arrayImage2D = img.select(bands).toArray().toArray(1) # apply correction factors", "image.reduceRegion( theReducer, geometry, scale).get(indexName) else: indexValue = image.reduceRegion(theReducer, geometry, scale)", "'min': [-15, -25, .40], 'max': [0, -10, 1], 'gamma': 1.6}", "filteredImageNDMIToMapId(startDate, endDate): def calcNDMI(img): return img.expression('(i.nir - i.swir1) / (i.nir", "endDate) elif (lowerIndex == 'ndmi'): return filteredImageNDMIToMapId(startDate, endDate) elif (lowerIndex", "'nir', 'swir1', 'swir2'] # linear regression coefficients for adjustment gain", "def listAvailableBands(name, assetType): eeImage = None if assetType == \"imageCollection\":", "date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") startDate = imDate -", "are clouds and cirrus, respectively. cloudBitMask = int(math.pow(2, 10)) cirrusBitMask", "visParams) else: values = imageToMapId(eeFirstImage, visParams) except EEException as ine:", "date = image.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return", "'OLI_TIRS' elif (\"le7\" in lowerAsset): sID = 'ETM' elif (\"lt5\"", "= ee.Image(1.0) # Clouds are reasonably bright in the blue", "toNatural(img): return ee.Image(10).pow(img.divide(10)) def addRatioBands(img): # not using angle band", "= img.select('VH') vv_vh = vv.divide(vh).rename('VV/VH') vh_vv = vh.divide(vv).rename('VH/VV') return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv)", "values = indexCollection2.getInfo() return values ########## Stats ########## def getStatistics(extent):", "= img.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue] ) return", "False elif (\"lt5\" in lowerAsset): skipCloudMask = False else: skipCloudMask", "'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI2).mean()) return", "the routes are easier to deduce whats being returned. return", "'B4', 'B5', 'B7'], 'LANDSAT/LE07/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'],", "math import sys import json from ee.ee_exception import EEException from", "bands = bandsByCollection[name] return image.expression(indexes[indexName], { 'blue': image.select(bands[0]), 'green': image.select(bands[1]),", "= reducer.lower() if(reducerName == 'min'): return imageCollection.min() elif (reducerName ==", "= score.min(ndsi_rescale).multiply(100).byte() mask = score.lt(cloudThresh).rename(['cloudMask']) img = img.updateMask(mask) return img.addBands(score)", "ee.Reducer.mode() elif (reducerName == 'first'): return ee.Reducer.first() elif (reducerName ==", "metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds) lc8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than',", "'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds) lc8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\ .filterMetadata('CLOUD_COVER',", "reasonably bright in all visible bands. visible = img.select('red').add( img.select('green')).add(img.select('blue'))", "(nir + red + 0.5)) * (1 + 0.5)' }", "def imageToMapId(image, visParams): eeImage = ee.Image(image) mapId = eeImage.getMapId(visParams) #", "'ndvi'): return filteredImageNDVIToMapId(startDate, endDate) elif (lowerIndex == 'evi'): return filteredImageEVIToMapId(startDate,", "'bands': eeImage.bandNames().getInfo(), 'imageName': name } ########## ee.Image ########## def imageToMapId(image,", "= getLandsat({ \"start\": startDate.strftime('%Y-%m-%d'), \"end\": endDate.strftime('%Y-%m-%d'), \"targetBands\": ['RED', 'GREEN', 'BLUE',", "import datetime import os import ee import math import sys", "int(pop) return { 'minElev': minElev, 'maxElev': maxElev, 'pop': pop }", "'index': reduced.get('index'), 'timeIndex': [image.get('system:time_start'), reduced.get('index')] }) geometry = None if", "'swir1', 'temp', 'swir2'] metadataCloudCoverMax = 100 lt4 = ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\", "+ i.swir1)', {'i': img}).rename(['NDMI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate,", "being returned. return { 'url': mapId['tile_fetcher'].url_format } ########## ee.ImageCollection ##########", "date = img.get('system:time_start') visParams = {'bands': ['VV', 'VH', 'ratioVVVH'], 'min':", "'swir2'] # linear regression coefficients for adjustment gain = ee.Array([[0.977],", "['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T1_TOA': ['B1', 'B2', 'B3',", "return ee.Image(10).pow(img.divide(10)) def addRatioBands(img): # not using angle band vv", "'B5', 'B6', 'B7'], 'LANDSAT/LE07/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'],", "'cloud', 'shadow', 'cirrus']).Not()) def toIndex(image): bands = bandsByCollection[name] return image.expression(indexes[indexName],", "(nir + 6.0 * red - 7.5 * blue +", "img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start') visParams = {'bands': ['VV',", ".set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'c9c0bf,435ebf,eee8aa,006400' visParams", "[-0.00029], [-0.00015], [-0.00097]]) # Make an Array Image, with a", "getDegradationTileUrlByDate(geometry, date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") startDate = imDate", "import os import ee import math import sys import json", "geometry = ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) if indexName !=", ".filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds) le7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\", "'blue': image.select(bands[0]), 'green': image.select(bands[1]), 'red': image.select(bands[2]), 'nir': image.select(bands[3]), 'swir1': image.select(bands[4]),", "7.5 * blue + 1)', 'EVI2': '2.5 * (nir -", "40, True ) return imageToMapId(eeMosaicImage, visParams) def filteredSentinelComposite(visParams, startDate, endDate,", "= ee.Image(image) mapId = eeImage.getMapId(visParams) # TODO, just return URL", "* (1 + 0.5)' } def create(name): def maskClouds(image): def", ".filter(ee.Filter.eq('instrumentMode', 'IW')) sentinel1 = sentinel1.map(toNatural) sentinel1 = sentinel1.map(addRatioBands) median =", "return img.expression('2.5 * (i.nir - i.red) / (i.nir + 2.4", "return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1 = sentinel1.filterDate(startDate, endDate) \\", "getLandsat({ \"start\": start, \"end\": end, \"targetBands\": [band], \"region\": geometry, \"sensors\":", "'S2': [1, 2, 3, 7, 11, 10, 12]} bandNamesLandsatTOA =", "def getLandSatMergedCollection(): sensorBandDictLandsatTOA = {'L8': [1, 2, 3, 4, 5,", "indexCollection1 = clippedcollection.map(getIndex) indexCollection2 = indexCollection1.aggregate_array('indexValue') return indexCollection2.getInfo() def getTimeSeriesByIndex(indexName,", "for name in bandsByCollection: collection = collection.merge(create(name)) return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\", "elif (reducerName == 'last'): return ee.Reducer.last() elif (reducerName == 'sum'):", "== 'last'): return ee.Reducer.last() elif (reducerName == 'sum'): return ee.Reducer.sum()", "getLandsat, getS1 ########## Helper functions ########## def initialize(ee_account='', ee_key_path=''): try:", "ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8))) score = score.min(ndsi_rescale).multiply(100).byte() mask = score.lt(cloudThresh).rename(['cloudMask'])", "'ndmi'): return filteredImageNDMIToMapId(startDate, endDate) elif (lowerIndex == 'ndwi'): return filteredImageNDWIToMapId(startDate,", "['VV', 'VH', 'ratioVVVH'], 'min': [-15, -25, .40], 'max': [0, -10,", "lsd = landsatData.map(myImageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo()", "'LANDSAT/LE07/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LE07/C01/T2_TOA': ['B1', 'B2',", "score.min(visible_rescale) # Clouds are reasonably bright in all infrared bands.", "or isinstance(coords[0], tuple): geometry = ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords)", "'max'): return imageCollection.max() elif (reducerName == 'mean'): return imageCollection.mean() elif", "ee.Number(0.8).subtract(ee.Number(0.2))) score = score.min(visible_rescale) # Clouds are reasonably bright in", "img = img.updateMask(mask) return img.addBands(score) def s2MaskClouds(img): qa = img.select('QA60')", "\\ .aggregate_array('timeIndex') \\ .getInfo() ########## Degradation########## def getDegradationTileUrlByDateS1(geometry, date, visParams):", "ee.ImageCollection(assetId) if (startDate and endDate): eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection", "try: return json.loads(val.replace(\"'\", \"\\\"\")) except Exception as e: return {}", "= getLandsat({ \"start\": start, \"end\": end, \"targetBands\": [band], \"region\": geometry,", ".select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds) lc8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\", "endDate): def calcNDVI(img): return img.expression('(i.nir - i.red) / (i.nir +", "ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) eeFirstImage = ee.Image(eeCollection.mosaic()) try: if(skipCloudMask", "start, \"end\": end, \"targetBands\": [band], \"region\": geometry, \"sensors\": {\"l4\": True,", "Clouds are reasonably cool in temperature. temp_rescale = img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300)))", "geometry, 30) date = img.get('system:time_start') indexImage = ee.Image().set( 'indexValue', [ee.Number(date),", "def toNatural(img): return ee.Image(10).pow(img.divide(10)) def addRatioBands(img): # not using angle", "True) def reduceRegion(image): theReducer = getReducer(reducer) reduced = image.reduceRegion( theReducer,", "indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage lsd =", "0.5)) * (1 + 0.5)' } def create(name): def maskClouds(image):", "= ee.ImageCollection('COPERNICUS/S2') f2017s2 = sentinel2.filterDate(startDate, endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) m2017s2", "['blue', 'green', 'red', 'nir', 'swir1', 'temp', 'swir2'] metadataCloudCoverMax = 100", "'B5', 'B7'], 'LANDSAT/LT05/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T1_TOA':", "ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart, True) else: return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True) def reduceRegion(image): theReducer", "return filteredImageEVIToMapId(startDate, endDate) elif (lowerIndex == 'evi2'): return filteredImageEVI2ToMapId(startDate, endDate)", "False, \"l7\": False, \"l8\": True} }) selectedImage = landsatData.first() unmasked", "'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'],", "getFeatureCollectionTileUrl(featureCollection, field, matchID, visParams): fc = ee.FeatureCollection(featureCollection) single = fc.filter(ee.Filter.equals(field,", "bandNamesLandsatTOA).map(lsMaskClouds) lt5 = ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L5'],", "'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5',", "(reducerName == 'first'): return imageCollection.first() elif (reducerName == 'sum'): return", "\"start\": startDate.strftime('%Y-%m-%d'), \"end\": endDate.strftime('%Y-%m-%d'), \"targetBands\": ['RED', 'GREEN', 'BLUE', 'SWIR1', 'NIR'],", "0.6])) def cloudScoreS2(img): rescale = img.divide(10000) score = cloudScore(rescale).multiply(100).rename('cloudscore') return", "'last'): return ee.Reducer.last() elif (reducerName == 'sum'): return ee.Reducer.sum() else:", "band vv = img.select('VV') vh = img.select('VH') vv_vh = vv.divide(vh).rename('VV/VH')", "= score.min(visible_rescale) # Clouds are reasonably bright in all infrared", "except Exception as e: print(e) def getReducer(reducer): reducerName = reducer.lower()", "100 lt4 = ee.ImageCollection('LANDSAT/LT4_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L4'],", "return ee.Reducer.first() elif (reducerName == 'last'): return ee.Reducer.last() elif (reducerName", "\\ .map(reduceRegion) \\ .filterMetadata('index', 'not_equals', None) \\ .aggregate_array('timeIndex') \\ .getInfo()", "not using angle band vv = img.select('VV') vh = img.select('VH')", "return filteredImageNDWIToMapId(startDate, endDate) def filteredImageCompositeToMapId(assetId, visParams, startDate, endDate, metadataCloudCoverMax, simpleCompositeVariable):", "\\ .select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds) le7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax)", "red) / (nir + 2.4 * red + 1)', 'NDMI':", "in all visible bands. visible = img.select('red').add( img.select('green')).add(img.select('blue')) visible_rescale =", "3, 7, 11, 10, 12]} bandNamesLandsatTOA = ['blue', 'green', 'red',", "[1.001], [0.996]]) bias = ee.Array([[-0.00411], [-0.00093], [0.00094], [-0.00029], [-0.00015], [-0.00097]])", "= lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values def getDegradationTileUrlByDate(geometry, date,", "'B7'], 'LANDSAT/LT05/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T1_TOA': ['B1',", "geometry, scale).get(indexName) else: indexValue = image.reduceRegion(theReducer, geometry, scale) date =", "* red + 1)', 'NDMI': '(nir - swir1) / (nir", "m2017s3 = m2017s2.median() return imageToMapId(m2017s3, visParams) def filteredSentinelSARComposite(visParams, startDate, endDate):", "getClipped(image): return image.clip(geometry) clippedcollection = indexCollection.map(getClipped) indexCollection1 = clippedcollection.map(getIndex) indexCollection2", "extentGeom, 1000, maxPixels=500000000) minElev = minmaxElev.get('elevation_min').getInfo() maxElev = minmaxElev.get('elevation_max').getInfo() ciesinPopGrid", "datetime.datetime.strptime(date, \"%Y-%m-%d\") befDate = imDate - datetime.timedelta(days=1) aftDate = imDate", "\\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA) \\ .map(bandPassAdjustment) return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def filteredImageNDVIToMapId(startDate, endDate):", "'cirrus': 4096 } anySet = ee.Image(0) for Type in types:", "= ee.Image(0) for Type in types: anySet = anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0))", "(1 + 0.5)' } def create(name): def maskClouds(image): def isSet(types):", "\"end\": end, \"targetBands\": [band], \"region\": geometry, \"sensors\": {\"l4\": True, \"l5\":", "'region': geometry}) start = befDate.strftime('%Y-%m-%d') end = aftDate.strftime('%Y-%m-%d') selectedImage =", "3, 4, 5, 6], 'S2': [1, 2, 3, 7, 11,", "'indexValue', [ee.Number(date), indexValue] ) return indexImage lsd = landsatData.map(myImageMapper, True)", "visParams) def filteredSentinelComposite(visParams, startDate, endDate, metadataCloudCoverMax): def cloudScore(img): def rescale(img,", "clear = qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0)) return img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start')) def bandPassAdjustment(img): keep", "1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI).mean()) return imageToMapId(eviImage,", "val else: try: return json.loads(val) except Exception as e: try:", "i.red + 1)', {'i': img}).rename(['EVI2']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection =", "indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values def getDegradationTileUrlByDate(geometry,", "qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0)) return img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start')) def bandPassAdjustment(img): keep = img.select(['temp'])", "'swir1']) ndsi_rescale = ndsi.subtract(ee.Number(0.8)).divide( ee.Number(0.6).subtract(ee.Number(0.8))) score = score.min(ndsi_rescale).multiply(100).byte() mask =", "image.clip(geometry) clippedcollection = indexCollection.map(getClipped) indexCollection1 = clippedcollection.map(getIndex) indexCollection2 = indexCollection1.aggregate_array('indexValue')", "return img.expression(exp, {'img': img}).subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) score = ee.Image(1.0) score", "bright in all visible bands. visible = img.select('red').add( img.select('green')).add(img.select('blue')) visible_rescale", "if isinstance(val, dict): return val else: try: return json.loads(val) except", "1.6} indexImage = ee.Image().set( 'indexValue', [ee.Number(date), indexValue]) return indexImage lsd", "= unmasked.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPoint(geometry, start, end, band): if", "return ee.Reducer.mode() elif (reducerName == 'first'): return ee.Reducer.first() elif (reducerName", "def rescale(img, exp, thresholds): return img.expression(exp, {'img': img}).subtract(thresholds[0]).divide(thresholds[1] - thresholds[0])", "getLandSatMergedCollection(): sensorBandDictLandsatTOA = {'L8': [1, 2, 3, 4, 5, 9,", "['B2', 'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LE07/C01/T1_TOA': ['B1', 'B2', 'B3',", "if isinstance(coords[0], list) or isinstance(coords[0], tuple): geometry = ee.Geometry.Polygon(coords) else:", "def firstCloudFreeImageInMosaicToMapId(assetId, visParams, startDate, endDate): skipCloudMask = False eeCollection =", "skipCloudMask = False elif (\"lt5\" in lowerAsset): skipCloudMask = False", "unmasked = ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams = unmasked.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPoint(geometry,", "def filteredSentinelComposite(visParams, startDate, endDate, metadataCloudCoverMax): def cloudScore(img): def rescale(img, exp,", "landsatData = getLandsat({ \"start\": start, \"end\": end, \"targetBands\": [band], \"region\":", "cloudScore(img): def rescale(img, exp, thresholds): return img.expression(exp, {'img': img}).subtract(thresholds[0]).divide(thresholds[1] -", "return img.expression('(i.green - i.nir) / (i.green + i.nir)', {'i': img}).rename(['NDWI'])", "elif (\"le7\" in lowerAsset): sID = 'ETM' elif (\"lt5\" in", "'IW')) sentinel1 = sentinel1.map(toNatural) sentinel1 = sentinel1.map(addRatioBands) median = sentinel1.median()", "[0.3, 0.8])) ndsi = img.normalizedDifference(['B3', 'B11']) return score.min(rescale(ndsi, 'img', [0.8,", "\\ .select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds) lc8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax)", "not in visParams[\"bands\"].lower()): skipCloudMask = True elif (\"lc8\" in lowerAsset):", "* (nir - red) / (nir + 2.4 * red", "'max'): return ee.Reducer.max() elif (reducerName == 'mean'): return ee.Reducer.mean() elif", "os import ee import math import sys import json from", "return image.expression(indexes[indexName], { 'blue': image.select(bands[0]), 'green': image.select(bands[1]), 'red': image.select(bands[2]), 'nir':", "tuple): geometry = ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) collection =", "mask = scored.select(['cloud']).lte(20) masked = eeFirstImage.updateMask(mask) values = imageToMapId(masked, visParams)", "= None if isinstance(coords[0], list) or isinstance(coords[0], tuple): geometry =", "= ['blue', 'green', 'red', 'nir', 'swir1', 'swir2'] # linear regression", ") return imageToMapId(eeMosaicImage, visParams) def filteredSentinelComposite(visParams, startDate, endDate, metadataCloudCoverMax): def", "allow user to select first cloud free image again? def", "'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LE07/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5',", ".filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) sentinel1 =", "= '' if (\"lc8\" in lowerAsset): sID = 'OLI_TIRS' elif", "indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values ########## Stats", "########## def initialize(ee_account='', ee_key_path=''): try: if ee_account and ee_key_path and", "ee.Image(1.0) score = score.min(rescale(img, 'img.B2', [0.1, 0.3])) score = score.min(rescale(img,", "endDate: return ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart, True) else: return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True) def", "mask = score.lt(cloudThresh).rename(['cloudMask']) img = img.updateMask(mask) return img.addBands(score) def s2MaskClouds(img):", ".map(bandPassAdjustment) return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def filteredImageNDVIToMapId(startDate, endDate): def calcNDVI(img): return img.expression('(i.nir", "= ee.FeatureCollection(featureCollection) single = fc.filter(ee.Filter.equals(field, matchID)) mapId = ee.Image().paint(single, 0,", "sentinel1 = sentinel1.map(addRatioBands) median = sentinel1.median() return imageToMapId(median, visParams) ##########", "i.swir1)', {'i': img}).rename(['NDMI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate)", "return imageCollection.max() elif (reducerName == 'mean'): return imageCollection.mean() elif (reducerName", "else: geometry = ee.Geometry.Point(coords) collection = ee.ImageCollection([]) for name in", "'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDMI).mean()) return", "== 'mean'): return ee.Reducer.mean() elif (reducerName == 'mode'): return ee.Reducer.mode()", "Degradation########## def getDegradationTileUrlByDateS1(geometry, date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") befDate", "= qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0)) return img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start')) def bandPassAdjustment(img): keep =", "ciesinPopGrid.reduceRegion( ee.Reducer.sum(), extentGeom, maxPixels=500000000) pop = popDict.get('population-count').getInfo() pop = int(pop)", "['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LE07/C01/T2_TOA': ['B1', 'B2', 'B3',", "def getTimeSeriesByIndex(indexName, scale, coords, startDate, endDate, reducer): bandsByCollection = {", "select first cloud free image again? def firstCloudFreeImageInMosaicToMapId(assetId, visParams, startDate,", "lowerAsset): skipCloudMask = False else: skipCloudMask = True if (startDate", "maskClouds(image): def isSet(types): \"\"\" https://landsat.usgs.gov/collectionqualityband \"\"\" typeByValue = { 'badPixels':", "coords, startDate, endDate, reducer): bandsByCollection = { 'LANDSAT/LC08/C01/T1_TOA': ['B2', 'B3',", "indexName != None: indexCollection = ee.ImageCollection(assetId).filterDate( startDate, endDate).select(indexName) else: indexCollection", "filteredImageCompositeToMapId(assetId, visParams, startDate, endDate, metadataCloudCoverMax, simpleCompositeVariable): eeCollection = ee.ImageCollection(assetId) if", "'B6', 'B7'], 'LANDSAT/LC08/C01/T2_TOA': ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LE07/C01/T1_TOA':", "img.select(bands).toArray().toArray(1) # apply correction factors and reproject array to geographic", "= datetime.datetime.strptime(date, \"%Y-%m-%d\") befDate = imDate - datetime.timedelta(days=1) aftDate =", "i.nir)', {'i': img}).rename(['NDWI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate)", "(reducerName == 'max'): return imageCollection.max() elif (reducerName == 'mean'): return", "def getReducer(reducer): reducerName = reducer.lower() if(reducerName == 'min'): return ee.Reducer.min()", "eeCollection = ee.ImageCollection(assetId) if (startDate and endDate): eeCollection = eeCollection.filterDate(startDate,", "scale, coords, startDate, endDate, reducer): bandsByCollection = { 'LANDSAT/LC08/C01/T1_TOA': ['B2',", "image.reduceRegion( theReducer, geometry=geometry, scale=scale, maxPixels=1e6) return ee.Feature(None, { 'index': reduced.get('index'),", "return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True) def reduceRegion(image): theReducer = getReducer(reducer) reduced =", "bandNamesLandsatTOA).map(lsMaskClouds) le7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L7'],", "indexImage def getClipped(image): return image.clip(geometry) clippedcollection = indexCollection.map(getClipped) indexCollection1 =", "'sum'): return ee.Reducer.sum() else: return ee.Reducer.median() def reduceIC(imageCollection, reducer): reducerName", "(reducerName == 'mode'): return ee.Reducer.mode() elif (reducerName == 'first'): return", "= ee.Geometry.Point(coords) collection = ee.ImageCollection([]) for name in bandsByCollection: collection", "score.min( rescale(img, 'img.B8 + img.B11 + img.B12', [0.3, 0.8])) ndsi", "'CLOUD_COVER', 'less_than', metadataCloudCoverMax ) eeMosaicImage = ee.Algorithms.Landsat.simpleComposite( eeCollection, simpleCompositeVariable, 10,", "4096 } anySet = ee.Image(0) for Type in types: anySet", "image.select(bands[3]), 'swir1': image.select(bands[4]), 'swir2': image.select(bands[5]), }).clamp(-1, 1).rename(['index']) def toIndexWithTimeStart(image): time", "return ee.Reducer.max() elif (reducerName == 'mean'): return ee.Reducer.mean() elif (reducerName", "ee.Image(eeCollection.map(calcEVI2).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDMIToMapId(startDate, endDate): def calcNDMI(img): return", "0.8])) ndsi = img.normalizedDifference(['B3', 'B11']) return score.min(rescale(ndsi, 'img', [0.8, 0.6]))", "None: indexValue = image.reduceRegion( theReducer, geometry, scale).get(indexName) else: indexValue =", "indexCollection = ee.ImageCollection( assetId).filterDate(startDate, endDate) def getIndex(image): theReducer = getReducer(reducer)", "start, end, band): if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else:", "\"region\": geometry, \"sensors\": {\"l4\": True, \"l5\": True, \"l7\": True, \"l8\":", "+ datetime.timedelta(days=1) if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry", "values = imageToMapId(eeFirstImage, visParams) except EEException as ine: imageToMapId(eeFirstImage, visParams)", "'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LE07/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4',", "getLandsat({ \"start\": startDate.strftime('%Y-%m-%d'), \"end\": endDate.strftime('%Y-%m-%d'), \"targetBands\": ['RED', 'GREEN', 'BLUE', 'SWIR1',", "== 'sum'): return imageCollection.sum() else: return imageCollection.median() def safeParseJSON(val): if", "elif (\"le7\" in lowerAsset): skipCloudMask = False elif (\"lt5\" in", "= imDate + datetime.timedelta(days=1) if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry)", "return imageCollection.sum() else: return imageCollection.median() def safeParseJSON(val): if isinstance(val, dict):", "start = befDate.strftime('%Y-%m-%d') end = aftDate.strftime('%Y-%m-%d') selectedImage = sentinel1Data.filterDate(start, end).first()", "should we allow user to select first cloud free image", "return imageToMapId(eviImage, visParams) def filteredImageEVIToMapId(startDate, endDate): def calcEVI(img): return img.expression('2.5", "geometry}) start = befDate.strftime('%Y-%m-%d') end = aftDate.strftime('%Y-%m-%d') selectedImage = sentinel1Data.filterDate(start,", "\"region\": geometry, \"sensors\": {\"l4\": False, \"l5\": False, \"l7\": False, \"l8\":", "index): lowerIndex = index.lower() if (lowerIndex == 'ndvi'): return filteredImageNDVIToMapId(startDate,", "blue_rescale = img.select('blue').subtract(ee.Number(0.1)).divide( ee.Number(0.3).subtract(ee.Number(0.1))) score = score.min(blue_rescale) # Clouds are", ".map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA) \\ .map(bandPassAdjustment) return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def filteredImageNDVIToMapId(startDate, endDate): def", "landsatData.first() unmasked = ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams = unmasked.getMapId(visParams) return mapparams['tile_fetcher'].url_format def", "True) indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values ##########", "startDate.strftime('%Y-%m-%d'), \"end\": endDate.strftime('%Y-%m-%d'), \"targetBands\": ['RED', 'GREEN', 'BLUE', 'SWIR1', 'NIR'], \"region\":", "Clouds are reasonably bright in the blue band. blue_rescale =", "fc = ee.FeatureCollection(featureCollection) single = fc.filter(ee.Filter.equals(field, matchID)) mapId = ee.Image().paint(single,", "def filteredImageEVIToMapId(startDate, endDate): def calcEVI(img): return img.expression('2.5 * (i.nir -", "if ee_account and ee_key_path and os.path.exists(ee_key_path): credentials = ee.ServiceAccountCredentials(ee_account, ee_key_path)", "eeFirstImage.set('SENSOR_ID', sID)) mask = scored.select(['cloud']).lte(20) masked = eeFirstImage.updateMask(mask) values =", "= datetime.datetime.strptime(date, \"%Y-%m-%d\") startDate = imDate - datetime.timedelta(days=1) endDate =", "1, 'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDWI).mean())", "(nir + 2.4 * red + 1)', 'NDMI': '(nir -", "listAvailableBands(name, assetType): eeImage = None if assetType == \"imageCollection\": eeImage", "'indexValue', [ee.Number(date), indexValue]) return indexImage def getClipped(image): return image.clip(geometry) clippedcollection", "ee.Image().set( 'indexValue', [ee.Number(date), indexValue] ) return indexImage lsd = landsatData.map(myImageMapper,", "Type in types: anySet = anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return anySet return", "ee.ImageCollection(assetId) if (startDate and endDate): eeCollection = eeCollection.filterDate(startDate, endDate) eeCollection.filterMetadata(", "1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDVI).mean()) return imageToMapId(eviImage,", "correction factors and reproject array to geographic image componentsImage =", "= '505050,E8E8E8,00FF33,003300' visParams = {'opacity': 1, 'max': 1, 'min': -1,", "initialize(ee_account='', ee_key_path=''): try: if ee_account and ee_key_path and os.path.exists(ee_key_path): credentials", "datetime.timedelta(days=1) aftDate = imDate + datetime.timedelta(days=1) if isinstance(geometry[0], list): geometry", "score.min(temp_rescale) # However, clouds are not snow. ndsi = img.normalizedDifference(['green',", "{'opacity': 1, 'max': 1, 'min': -1, 'palette': colorPalette} eviImage =", "= ee.Image(reduceIC(eeCollection, reducer)) return imageToMapId(reducedImage, visParams) # TODO, should we", "except Exception as e: return {} ########## Helper routes ##########", "endDate) def getIndex(image): theReducer = getReducer(reducer) if indexName != None:", "URL so the routes are easier to deduce whats being", "- 7.5 * blue + 1)', 'EVI2': '2.5 * (nir", "'2.5 * (nir - red) / (nir + 6.0 *", "getS1 ########## Helper functions ########## def initialize(ee_account='', ee_key_path=''): try: if", "False, \"l5\": False, \"l7\": False, \"l8\": True} }) selectedImage =", "= ee.Array([[0.977], [1.005], [0.982], [1.001], [1.001], [0.996]]) bias = ee.Array([[-0.00411],", "sys import json from ee.ee_exception import EEException from gee.inputs import", "1, 'max': 1, 'min': -1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI).mean())", "'B7'], 'LANDSAT/LE07/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LE07/C01/T2_TOA': ['B1',", "def filteredImageCompositeToMapId(assetId, visParams, startDate, endDate, metadataCloudCoverMax, simpleCompositeVariable): eeCollection = ee.ImageCollection(assetId)", "\"%Y-%m-%d\") befDate = imDate - datetime.timedelta(days=1) aftDate = imDate +", "lowerIndex = index.lower() if (lowerIndex == 'ndvi'): return filteredImageNDVIToMapId(startDate, endDate)", "['VV', 'VH', 'VV/VH'], 'region': geometry}) start = befDate.strftime('%Y-%m-%d') end =", "landsatData.map(myImageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values = indexCollection2.getInfo() return values", "endDate, reducer): bandsByCollection = { 'LANDSAT/LC08/C01/T1_TOA': ['B2', 'B3', 'B4', 'B5',", "########## Helper functions ########## def initialize(ee_account='', ee_key_path=''): try: if ee_account", "except Exception as e: try: return json.loads(val.replace(\"'\", \"\\\"\")) except Exception", "img.B12', [0.3, 0.8])) ndsi = img.normalizedDifference(['B3', 'B11']) return score.min(rescale(ndsi, 'img',", "'LANDSAT/LT05/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T2_TOA': ['B1', 'B2',", "'B5', 'B6', 'B7'], 'LANDSAT/LC08/C01/T2_TOA': ['B2', 'B3', 'B4', 'B5', 'B6', 'B7'],", "None if isinstance(coords[0], list): geometry = ee.Geometry.Polygon(coords) else: geometry =", "= scored.select(['cloud']).lte(20) masked = eeFirstImage.updateMask(mask) values = imageToMapId(masked, visParams) else:", "['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T2_TOA': ['B1', 'B2', 'B3',", "filteredSentinelComposite(visParams, startDate, endDate, metadataCloudCoverMax): def cloudScore(img): def rescale(img, exp, thresholds):", "score.min(ndsi_rescale).multiply(100).byte() mask = score.lt(cloudThresh).rename(['cloudMask']) img = img.updateMask(mask) return img.addBands(score) def", "= { 'NDVI': '(nir - red) / (nir + red)',", "are reasonably bright in all visible bands. visible = img.select('red').add(", "!= None: indexValue = image.reduceRegion( theReducer, geometry, scale).get(indexName) else: indexValue", "return json.loads(val.replace(\"'\", \"\\\"\")) except Exception as e: return {} ##########", "'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LC08/C01/T2_TOA': ['B2', 'B3', 'B4', 'B5',", "'NDMI': '(nir - swir1) / (nir + swir1)', 'NDWI': '(green", "'c9c0bf,435ebf,eee8aa,006400' visParams = {'opacity': 1, 'max': 1, 'min': -1, 'palette':", "collection = ee.ImageCollection([]) for name in bandsByCollection: collection = collection.merge(create(name))", "ee.ImageCollection ########## # Index Image Collection def lsMaskClouds(img, cloudThresh=10): score", "reproject array to geographic image componentsImage = ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\ .arrayProject([0]).arrayFlatten([bands]).float()", "= ee.Algorithms.Landsat.simpleComposite( eeCollection, simpleCompositeVariable, 10, 40, True ) return imageToMapId(eeMosaicImage,", "['B1', 'B2', 'B3', 'B4', 'B5', 'B7'] } indexes = {", "ee.Image(eeCollection.map(calcNDMI).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDWIToMapId(startDate, endDate): def calcNDWI(img): return", "reasonably cool in temperature. temp_rescale = img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300))) score =", "def maskClouds(image): def isSet(types): \"\"\" https://landsat.usgs.gov/collectionqualityband \"\"\" typeByValue = {", "def lsMaskClouds(img, cloudThresh=10): score = ee.Image(1.0) # Clouds are reasonably", "########## def listAvailableBands(name, assetType): eeImage = None if assetType ==", "'(green - nir) / (green + nir)', 'NBR': '(nir -", "'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVIToMapId(startDate,", "selectedImage.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPointS1(geometry, start, end): if isinstance(geometry[0], list):", "if assetType == \"imageCollection\": eeImage = ee.ImageCollection(name).first() else: eeImage =", "visParams) # TODO, should we allow user to select first", "return imageToMapId(eviImage, visParams) def filteredImageByIndexToMapId(startDate, endDate, index): lowerIndex = index.lower()", "return indexCollection2.getInfo() def getTimeSeriesByIndex(indexName, scale, coords, startDate, endDate, reducer): bandsByCollection", "clear if both flags set to zero. clear = qa.bitwiseAnd(cloudBitMask).eq(0).And(", "\"targetBands\": ['RED', 'GREEN', 'BLUE', 'SWIR1', 'NIR'], \"region\": geometry, \"sensors\": {\"l4\":", "{'i': img}).rename(['NDVI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette", "-1, 'palette': colorPalette} eviImage = ee.Image(eeCollection.map(calcNDVI).mean()) return imageToMapId(eviImage, visParams) def", "geometry = ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": startDate.strftime('%Y-%m-%d'), \"end\": endDate.strftime('%Y-%m-%d'),", "{'L8': [1, 2, 3, 4, 5, 9, 6], 'L7': [0,", "'VV/VH'], 'region': geometry}) start = befDate.strftime('%Y-%m-%d') end = aftDate.strftime('%Y-%m-%d') selectedImage", "red + 0.5)) * (1 + 0.5)' } def create(name):", "geometry = ee.Geometry.Point(coords) if indexName != None: indexCollection = ee.ImageCollection(assetId).filterDate(", "if (lowerIndex == 'ndvi'): return filteredImageNDVIToMapId(startDate, endDate) elif (lowerIndex ==", "= False elif (\"le7\" in lowerAsset): skipCloudMask = False elif", "except EEException as ine: imageToMapId(eeFirstImage, visParams) return values ########## ee.FeatureCollection", "'max': [0, -10, 1], 'gamma': 1.6} indexImage = ee.Image().set( 'indexValue',", "indexCollection = None if isinstance(coords[0], list): geometry = ee.Geometry.Polygon(coords) else:", "lowerAsset): sID = 'OLI_TIRS' elif (\"le7\" in lowerAsset): sID =", "TODO, should we allow user to select first cloud free", "ee.FeatureCollection(featureCollection) single = fc.filter(ee.Filter.equals(field, matchID)) mapId = ee.Image().paint(single, 0, 2).getMapId(visParams)", "7], 'L5': [0, 1, 2, 3, 4, 5, 6], 'L4':", "\\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L7'], bandNamesLandsatTOA).map(lsMaskClouds) lc8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')", "imageCollection.max() elif (reducerName == 'mean'): return imageCollection.mean() elif (reducerName ==", "= ee.Image(eeCollection.map(calcEVI2).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDMIToMapId(startDate, endDate): def calcNDMI(img):", "2-D Array per pixel. arrayImage2D = img.select(bands).toArray().toArray(1) # apply correction", "minmaxElev.get('elevation_min').getInfo() maxElev = minmaxElev.get('elevation_max').getInfo() ciesinPopGrid = ee.Image('CIESIN/GPWv4/population-count/2020') popDict = ciesinPopGrid.reduceRegion(", "visible_rescale = visible.subtract(ee.Number(0.2)).divide( ee.Number(0.8).subtract(ee.Number(0.2))) score = score.min(visible_rescale) # Clouds are", "Helper functions ########## def initialize(ee_account='', ee_key_path=''): try: if ee_account and", "sentinel1.median() return imageToMapId(median, visParams) ########## Time Series ########## def getTimeSeriesByCollectionAndIndex(assetId,", "img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams =", "'img', [0.8, 0.6])) def cloudScoreS2(img): rescale = img.divide(10000) score =", "return ee.Reducer.min() elif (reducerName == 'max'): return ee.Reducer.max() elif (reducerName", "ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) reducedImage = ee.Image(reduceIC(eeCollection, reducer)) return", "= ciesinPopGrid.reduceRegion( ee.Reducer.sum(), extentGeom, maxPixels=500000000) pop = popDict.get('population-count').getInfo() pop =", "values ########## ee.FeatureCollection ########## def getFeatureCollectionTileUrl(featureCollection, field, matchID, visParams): fc", "sentinel1 = sentinel1.map(toNatural) sentinel1 = sentinel1.map(addRatioBands) median = sentinel1.median() return", "eeImage.getMapId(visParams) # TODO, just return URL so the routes are", "'505050,E8E8E8,00FF33,003300' visParams = {'opacity': 1, 'max': 1, 'min': -1, 'palette':", "= {'opacity': 1, 'max': 1, 'min': -1, 'palette': colorPalette} eviImage", "endDate) elif (lowerIndex == 'evi2'): return filteredImageEVI2ToMapId(startDate, endDate) elif (lowerIndex", "= cloudScore(rescale).multiply(100).rename('cloudscore') return img.addBands(score) sentinel2 = ee.ImageCollection('COPERNICUS/S2') f2017s2 = sentinel2.filterDate(startDate,", "/ (nir + swir2)', 'LSAVI': '((nir - red) / (nir", "ee.ImageCollection([]) for name in bandsByCollection: collection = collection.merge(create(name)) return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start'))", "i.red) / (i.nir + 2.4 * i.red + 1)', {'i':", "returned. return { 'url': mapId['tile_fetcher'].url_format } ########## ee.ImageCollection ########## def", "if(\"b2\" not in visParams[\"bands\"].lower()): skipCloudMask = True elif (\"lc8\" in", "'NDWI': '(green - nir) / (green + nir)', 'NBR': '(nir", "== 'first'): return imageCollection.first() elif (reducerName == 'sum'): return imageCollection.sum()", "== False): sID = '' if (\"lc8\" in lowerAsset): sID", "'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5',", "m2017s2 = f2017s2.map(cloudScoreS2) m2017s3 = m2017s2.median() return imageToMapId(m2017s3, visParams) def", "return imageCollection.mosaic() elif (reducerName == 'first'): return imageCollection.first() elif (reducerName", "'BLUE', 'SWIR1', 'NIR'], \"region\": geometry, \"sensors\": {\"l4\": False, \"l5\": False,", "/ (i.nir + i.swir1)', {'i': img}).rename(['NDMI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection", "= ee.Image('CIESIN/GPWv4/population-count/2020') popDict = ciesinPopGrid.reduceRegion( ee.Reducer.sum(), extentGeom, maxPixels=500000000) pop =", "lt5 = ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L5'], bandNamesLandsatTOA).map(lsMaskClouds)", "geometry = ee.Geometry.Point(geometry) sentinel1Data = getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'],", "# not using angle band vv = img.select('VV') vh =", "eeFirstImage = ee.Image(eeCollection.mosaic()) try: if(skipCloudMask == False): sID = ''", "'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5',", "2, 3, 4, 5, 7], 'L5': [0, 1, 2, 3,", "selectedImage = landsatData.first() unmasked = ee.Image(selectedImage).multiply(10000).toInt16().unmask() mapparams = unmasked.getMapId(visParams) return", "+ img.B3 + img.B2', [0.2, 0.8])) score = score.min( rescale(img,", "= elev.reduceRegion( ee.Reducer.minMax(), extentGeom, 1000, maxPixels=500000000) minElev = minmaxElev.get('elevation_min').getInfo() maxElev", "and ee_key_path and os.path.exists(ee_key_path): credentials = ee.ServiceAccountCredentials(ee_account, ee_key_path) ee.Initialize(credentials) else:", "= eeCollection.filterDate(startDate, endDate) eeCollection.filterMetadata( 'CLOUD_COVER', 'less_than', metadataCloudCoverMax ) eeMosaicImage =", "= score.min(rescale(img, 'img.B2', [0.1, 0.3])) score = score.min(rescale(img, 'img.B4 +", "= ee.Geometry.Polygon(coords) else: geometry = ee.Geometry.Point(coords) if indexName != None:", "[ee.Number(date), indexValue] ) return indexImage lsd = landsatData.map(myImageMapper, True) indexCollection2", "return indexImage def getClipped(image): return image.clip(geometry) clippedcollection = indexCollection.map(getClipped) indexCollection1", "- red) / (nir + red)', 'EVI': '2.5 * (nir", "metadataCloudCoverMax) \\ .map(s2MaskClouds).select(sensorBandDictLandsatTOA['S2'], bandNamesLandsatTOA) \\ .map(bandPassAdjustment) return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def filteredImageNDVIToMapId(startDate,", "assetId).filterDate(startDate, endDate) def getIndex(image): theReducer = getReducer(reducer) if indexName !=", "to select first cloud free image again? def firstCloudFreeImageInMosaicToMapId(assetId, visParams,", "ee.Reducer.sum(), extentGeom, maxPixels=500000000) pop = popDict.get('population-count').getInfo() pop = int(pop) return", "def calcEVI(img): return img.expression('2.5 * (i.nir - i.red) / (i.nir", "def filteredImageNDWIToMapId(startDate, endDate): def calcNDWI(img): return img.expression('(i.green - i.nir) /", "(\"le7\" in lowerAsset): sID = 'ETM' elif (\"lt5\" in lowerAsset):", "qa.bitwiseAnd(cirrusBitMask).eq(0)) return img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start')) def bandPassAdjustment(img): keep = img.select(['temp']) bands", "= score.min(rescale(img, 'img.B4 + img.B3 + img.B2', [0.2, 0.8])) score", "return ee.Reducer.mean() elif (reducerName == 'mode'): return ee.Reducer.mode() elif (reducerName", "getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry }).filterDate(start, end) def", "image.select(bands[1]), 'red': image.select(bands[2]), 'nir': image.select(bands[3]), 'swir1': image.select(bands[4]), 'swir2': image.select(bands[5]), }).clamp(-1,", "return imageCollection.first() elif (reducerName == 'sum'): return imageCollection.sum() else: return", "angle band vv = img.select('VV') vh = img.select('VH') vv_vh =", "= ee.ServiceAccountCredentials(ee_account, ee_key_path) ee.Initialize(credentials) else: ee.Initialize() except Exception as e:", "= image.get('system:time_start') image = maskClouds(image) return toIndex(image).set('system:time_start', time) # if", "unmasked.getMapId(visParams) return mapparams['tile_fetcher'].url_format def getDegradationPlotsByPoint(geometry, start, end, band): if isinstance(geometry[0],", "ee.Image(eeCollection.mosaic()) try: if(skipCloudMask == False): sID = '' if (\"lc8\"", "def bandPassAdjustment(img): keep = img.select(['temp']) bands = ['blue', 'green', 'red',", "metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds) s2 = ee.ImageCollection('COPERNICUS/S2') \\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than',", "red)', 'EVI': '2.5 * (nir - red) / (nir +", "sentinel1.filterDate(startDate, endDate) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \\ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \\ .filter(ee.Filter.eq('instrumentMode',", "endDate): eeCollection = ee.ImageCollection(assetId) if (startDate and endDate): eeFilterDate =", "= bandsByCollection[name] return image.expression(indexes[indexName], { 'blue': image.select(bands[0]), 'green': image.select(bands[1]), 'red':", "with a 2-D Array per pixel. arrayImage2D = img.select(bands).toArray().toArray(1) #", "visParams, reducer, startDate, endDate): eeCollection = ee.ImageCollection(assetId) if (startDate and", "def toIndex(image): bands = bandsByCollection[name] return image.expression(indexes[indexName], { 'blue': image.select(bands[0]),", "getDegradationPlotsByPoint(geometry, start, end, band): if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry)", "= 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams = {'opacity': 1, 'max': 1, 'min': -1,", "import ee import math import sys import json from ee.ee_exception", "index.lower() if (lowerIndex == 'ndvi'): return filteredImageNDVIToMapId(startDate, endDate) elif (lowerIndex", "maxPixels=500000000) minElev = minmaxElev.get('elevation_min').getInfo() maxElev = minmaxElev.get('elevation_max').getInfo() ciesinPopGrid = ee.Image('CIESIN/GPWv4/population-count/2020')", "def getDegradationTileUrlByDate(geometry, date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") startDate =", "ee.Image('USGS/GTOPO30') minmaxElev = elev.reduceRegion( ee.Reducer.minMax(), extentGeom, 1000, maxPixels=500000000) minElev =", "'less_than', metadataCloudCoverMax ) eeMosaicImage = ee.Algorithms.Landsat.simpleComposite( eeCollection, simpleCompositeVariable, 10, 40,", "########## def getFeatureCollectionTileUrl(featureCollection, field, matchID, visParams): fc = ee.FeatureCollection(featureCollection) single", "[0.1, 0.3])) score = score.min(rescale(img, 'img.B4 + img.B3 + img.B2',", "'snow': 1024, 'cirrus': 4096 } anySet = ee.Image(0) for Type", "\"sensors\": {\"l4\": True, \"l5\": True, \"l7\": True, \"l8\": True} })", "= int(math.pow(2, 11)) # clear if both flags set to", ") return indexImage lsd = landsatData.map(myImageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue')", "and endDate: return ee.ImageCollection(name).filterDate(startDate, endDate).filterBounds(geometry).map(toIndexWithTimeStart, True) else: return ee.ImageCollection(name).filterBounds(geometry).map(toIndexWithTimeStart, True)", "swir1)', 'NDWI': '(green - nir) / (green + nir)', 'NBR':", "endDate).filterMetadata( 'CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) m2017s2 = f2017s2.map(cloudScoreS2) m2017s3 = m2017s2.median()", "elif (lowerIndex == 'ndwi'): return filteredImageNDWIToMapId(startDate, endDate) def filteredImageCompositeToMapId(assetId, visParams,", "{ 'index': reduced.get('index'), 'timeIndex': [image.get('system:time_start'), reduced.get('index')] }) geometry = None", "[band], \"region\": geometry, \"sensors\": {\"l4\": True, \"l5\": True, \"l7\": True,", "'(nir - swir2) / (nir + swir2)', 'LSAVI': '((nir -", "geometry, \"sensors\": {\"l4\": True, \"l5\": True, \"l7\": True, \"l8\": True}", "\"l8\": True} }) def myImageMapper(img): theReducer = ee.Reducer.mean() indexValue =", "[ee.Number(date), indexValue]) return indexImage def getClipped(image): return image.clip(geometry) clippedcollection =", "to geographic image componentsImage = ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\ .arrayProject([0]).arrayFlatten([bands]).float() # .set('system:time_start',img.get('system:time_start'));", "filteredSentinelSARComposite(visParams, startDate, endDate): def toNatural(img): return ee.Image(10).pow(img.divide(10)) def addRatioBands(img): #", "startDate, endDate, metadataCloudCoverMax, simpleCompositeVariable): eeCollection = ee.ImageCollection(assetId) if (startDate and", "2.4 * red + 1)', 'NDMI': '(nir - swir1) /", "are reasonably bright in all infrared bands. infrared = img.select('nir').add(", "1, 2, 3, 4, 5, 6], 'L4': [0, 1, 2,", "vh_vv = vh.divide(vv).rename('VH/VV') return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') sentinel1 =", "startDate, endDate): eeCollection = ee.ImageCollection(assetId) if (startDate and endDate): eeFilterDate", "rescale(img, exp, thresholds): return img.expression(exp, {'img': img}).subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) score", "and 11 are clouds and cirrus, respectively. cloudBitMask = int(math.pow(2,", "eviImage = ee.Image(eeCollection.map(calcNDWI).mean()) return imageToMapId(eviImage, visParams) def filteredImageByIndexToMapId(startDate, endDate, index):", "ee.Geometry.Point(coords) collection = ee.ImageCollection([]) for name in bandsByCollection: collection =", "None: indexCollection = ee.ImageCollection(assetId).filterDate( startDate, endDate).select(indexName) else: indexCollection = ee.ImageCollection(", "getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '505050,E8E8E8,00FF33,003300' visParams = {'opacity': 1, 'max':", "'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds) s2 = ee.ImageCollection('COPERNICUS/S2') \\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE',", "/ (nir + red)', 'EVI': '2.5 * (nir - red)", "values ########## Stats ########## def getStatistics(extent): extentGeom = ee.Geometry.Polygon(extent) elev", "1)', 'NDMI': '(nir - swir1) / (nir + swir1)', 'NDWI':", "elif (reducerName == 'mosaic'): return imageCollection.mosaic() elif (reducerName == 'first'):", "endDate) colorPalette = 'c9c0bf,435ebf,eee8aa,006400' visParams = {'opacity': 1, 'max': 1,", "reducerName = reducer.lower() if(reducerName == 'min'): return imageCollection.min() elif (reducerName", "6], 'L4': [0, 1, 2, 3, 4, 5, 6], 'S2':", "elev = ee.Image('USGS/GTOPO30') minmaxElev = elev.reduceRegion( ee.Reducer.minMax(), extentGeom, 1000, maxPixels=500000000)", "= img.select('temp').subtract(ee.Number(300)).divide( ee.Number(290).subtract(ee.Number(300))) score = score.min(temp_rescale) # However, clouds are", "+ 2.4 * i.red + 1)', {'i': img}).rename(['EVI2']) \\ .set('system:time_start',", "0.8])) score = score.min( rescale(img, 'img.B8 + img.B11 + img.B12',", "img}).rename(['EVI2']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette =", "== 'first'): return ee.Reducer.first() elif (reducerName == 'last'): return ee.Reducer.last()", ".select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds) s2 = ee.ImageCollection('COPERNICUS/S2') \\ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', metadataCloudCoverMax) \\", ".aggregate_array('timeIndex') \\ .getInfo() ########## Degradation########## def getDegradationTileUrlByDateS1(geometry, date, visParams): imDate", "img.B2', [0.2, 0.8])) score = score.min( rescale(img, 'img.B8 + img.B11", "'nir': image.select(bands[3]), 'swir1': image.select(bands[4]), 'swir2': image.select(bands[5]), }).clamp(-1, 1).rename(['index']) def toIndexWithTimeStart(image):", "thresholds[0]) score = ee.Image(1.0) score = score.min(rescale(img, 'img.B2', [0.1, 0.3]))", "= img.normalizedDifference(['B3', 'B11']) return score.min(rescale(ndsi, 'img', [0.8, 0.6])) def cloudScoreS2(img):", "fc.filter(ee.Filter.equals(field, matchID)) mapId = ee.Image().paint(single, 0, 2).getMapId(visParams) return mapId['tile_fetcher'].url_format ##########", ".filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \\ .filter(ee.Filter.eq('instrumentMode', 'IW')) sentinel1 = sentinel1.map(toNatural) sentinel1 =", "= sentinel1.median() return imageToMapId(median, visParams) ########## Time Series ########## def", "{} ########## Helper routes ########## def listAvailableBands(name, assetType): eeImage =", "'region': geometry }).filterDate(start, end) def myimageMapper(img): theReducer = ee.Reducer.mean() indexValue", "ee.Reducer.min() elif (reducerName == 'max'): return ee.Reducer.max() elif (reducerName ==", "None if isinstance(coords[0], list) or isinstance(coords[0], tuple): geometry = ee.Geometry.Polygon(coords)", "ee.ImageCollection(assetId).filterDate( startDate, endDate).select(indexName) else: indexCollection = ee.ImageCollection( assetId).filterDate(startDate, endDate) def", "Make an Array Image, with a 2-D Array per pixel.", "import getLandsat, getS1 ########## Helper functions ########## def initialize(ee_account='', ee_key_path=''):", "= ee.Image(name) return { 'bands': eeImage.bandNames().getInfo(), 'imageName': name } ##########", "img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start') indexImage = ee.Image().set( 'indexValue',", "geometry = ee.Geometry.Point(coords) collection = ee.ImageCollection([]) for name in bandsByCollection:", "vv_vh = vv.divide(vh).rename('VV/VH') vh_vv = vh.divide(vv).rename('VH/VV') return vv.addBands(vh).addBands(vv_vh).addBands(vh_vv) sentinel1 =", "if (startDate and endDate): eeFilterDate = ee.Filter.date(startDate, endDate) eeCollection =", "ee.Algorithms.Landsat.simpleCloudScore( eeFirstImage.set('SENSOR_ID', sID)) mask = scored.select(['cloud']).lte(20) masked = eeFirstImage.updateMask(mask) values", "maxElev = minmaxElev.get('elevation_max').getInfo() ciesinPopGrid = ee.Image('CIESIN/GPWv4/population-count/2020') popDict = ciesinPopGrid.reduceRegion( ee.Reducer.sum(),", "reducer): geometry = None indexCollection = None if isinstance(coords[0], list):", "ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry, 30) date = img.get('system:time_start') indexImage", "7.5 * i.blue + 1)', {'i': img}).rename(['EVI']) \\ .set('system:time_start', img.get('system:time_start'))", "'shadow': 256, 'snow': 1024, 'cirrus': 4096 } anySet = ee.Image(0)", "/ (i.nir + 6.0 * i.red - 7.5 * i.blue", "\"%Y-%m-%d\") startDate = imDate - datetime.timedelta(days=1) endDate = imDate +", "(i.nir + i.swir1)', {'i': img}).rename(['NDMI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection =", "safeParseJSON(val): if isinstance(val, dict): return val else: try: return json.loads(val)", "= popDict.get('population-count').getInfo() pop = int(pop) return { 'minElev': minElev, 'maxElev':", "ee.Image ########## def imageToMapId(image, visParams): eeImage = ee.Image(image) mapId =", "\\ .select(sensorBandDictLandsatTOA['L4'], bandNamesLandsatTOA).map(lsMaskClouds) lt5 = ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax)", "infrared = img.select('nir').add( img.select('swir1')).add(img.select('swir2')) infrared_rescale = infrared.subtract(ee.Number(0.3)).divide( ee.Number(0.8).subtract(ee.Number(0.3))) score =", "\\ .map(bandPassAdjustment) return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def filteredImageNDVIToMapId(startDate, endDate): def calcNDVI(img): return", "'ndwi'): return filteredImageNDWIToMapId(startDate, endDate) def filteredImageCompositeToMapId(assetId, visParams, startDate, endDate, metadataCloudCoverMax,", "\"start\": start, \"end\": end, \"targetBands\": [band], \"region\": geometry, \"sensors\": {\"l4\":", "eeCollection = eeCollection.filter(eeFilterDate) reducedImage = ee.Image(reduceIC(eeCollection, reducer)) return imageToMapId(reducedImage, visParams)", "\\ .set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'c9c0bf,435ebf,eee8aa,006400'", "regression coefficients for adjustment gain = ee.Array([[0.977], [1.005], [0.982], [1.001],", "colorPalette = '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams = {'opacity': 1, 'max': 1, 'min':", "to zero. clear = qa.bitwiseAnd(cloudBitMask).eq(0).And( qa.bitwiseAnd(cirrusBitMask).eq(0)) return img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start')) def", "= getS1({ \"targetBands\": ['VV', 'VH', 'VV/VH'], 'region': geometry }).filterDate(start, end)", "assetType == \"imageCollection\": eeImage = ee.ImageCollection(name).first() else: eeImage = ee.Image(name)", "'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4',", "6], 'S2': [1, 2, 3, 7, 11, 10, 12]} bandNamesLandsatTOA", "= ee.Image(eeCollection.map(calcNDMI).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDWIToMapId(startDate, endDate): def calcNDWI(img):", "end, \"targetBands\": [band], \"region\": geometry, \"sensors\": {\"l4\": True, \"l5\": True,", "else: geometry = ee.Geometry.Point(coords) if indexName != None: indexCollection =", "'B3', 'B4', 'B5', 'B6', 'B7'], 'LANDSAT/LE07/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4',", "values def getDegradationTileUrlByDate(geometry, date, visParams): imDate = datetime.datetime.strptime(date, \"%Y-%m-%d\") startDate", "eeImage = ee.Image(name) return { 'bands': eeImage.bandNames().getInfo(), 'imageName': name }", "endDate, index): lowerIndex = index.lower() if (lowerIndex == 'ndvi'): return", "(\"le7\" in lowerAsset): skipCloudMask = False elif (\"lt5\" in lowerAsset):", "def getStatistics(extent): extentGeom = ee.Geometry.Polygon(extent) elev = ee.Image('USGS/GTOPO30') minmaxElev =", "red) / (nir + red)', 'EVI': '2.5 * (nir -", "img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = 'F5F5F5,E6D3C5,C48472,B9CF63,94BF3D,6BB037,42A333,00942C,008729,007824,004A16' visParams =", "\"l5\": False, \"l7\": False, \"l8\": True} }) selectedImage = landsatData.first()", "filteredImageEVIToMapId(startDate, endDate): def calcEVI(img): return img.expression('2.5 * (i.nir - i.red)", "bandPassAdjustment(img): keep = img.select(['temp']) bands = ['blue', 'green', 'red', 'nir',", "skipCloudMask = False else: skipCloudMask = True if (startDate and", "return ee.ImageCollection(ee.ImageCollection(collection).sort('system:time_start').distinct('system:time_start')) \\ .map(reduceRegion) \\ .filterMetadata('index', 'not_equals', None) \\ .aggregate_array('timeIndex')", "Time Series ########## def getTimeSeriesByCollectionAndIndex(assetId, indexName, scale, coords, startDate, endDate,", "simpleCompositeVariable): eeCollection = ee.ImageCollection(assetId) if (startDate and endDate): eeCollection =", "apply correction factors and reproject array to geographic image componentsImage", "0.3])) score = score.min(rescale(img, 'img.B4 + img.B3 + img.B2', [0.2,", "# .set('system:time_start',img.get('system:time_start')); return keep.addBands(componentsImage) def getLandSatMergedCollection(): sensorBandDictLandsatTOA = {'L8': [1,", "= True if (startDate and endDate): eeFilterDate = ee.Filter.date(startDate, endDate)", "geographic image componentsImage = ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\ .arrayProject([0]).arrayFlatten([bands]).float() # .set('system:time_start',img.get('system:time_start')); return", "reducer): bandsByCollection = { 'LANDSAT/LC08/C01/T1_TOA': ['B2', 'B3', 'B4', 'B5', 'B6',", "geometry = None if isinstance(coords[0], list) or isinstance(coords[0], tuple): geometry", "exp, thresholds): return img.expression(exp, {'img': img}).subtract(thresholds[0]).divide(thresholds[1] - thresholds[0]) score =", "elif (reducerName == 'mode'): return ee.Reducer.mode() elif (reducerName == 'first'):", "in types: anySet = anySet.Or(image.select( 'BQA').bitwiseAnd(typeByValue[Type]).neq(0)) return anySet return image.updateMask(isSet(['badPixels',", "= ee.Array([[-0.00411], [-0.00093], [0.00094], [-0.00029], [-0.00015], [-0.00097]]) # Make an", "score.min(rescale(ndsi, 'img', [0.8, 0.6])) def cloudScoreS2(img): rescale = img.divide(10000) score", "['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T1_TOA': ['B1', 'B2', 'B3',", "256, 'snow': 1024, 'cirrus': 4096 } anySet = ee.Image(0) for", "start, end): if isinstance(geometry[0], list): geometry = ee.Geometry.Polygon(geometry) else: geometry", "(\"lt5\" in lowerAsset): skipCloudMask = False else: skipCloudMask = True", "geometry = ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) sentinel1Data = getS1({", "clouds are not snow. ndsi = img.normalizedDifference(['green', 'swir1']) ndsi_rescale =", "'B11']) return score.min(rescale(ndsi, 'img', [0.8, 0.6])) def cloudScoreS2(img): rescale =", "4, 5, 6], 'S2': [1, 2, 3, 7, 11, 10,", "= indexCollection2.getInfo() return values ########## Stats ########## def getStatistics(extent): extentGeom", "+ 2.4 * red + 1)', 'NDMI': '(nir - swir1)", "ee.Reducer.minMax(), extentGeom, 1000, maxPixels=500000000) minElev = minmaxElev.get('elevation_min').getInfo() maxElev = minmaxElev.get('elevation_max').getInfo()", "= ['blue', 'green', 'red', 'nir', 'swir1', 'temp', 'swir2'] metadataCloudCoverMax =", "== 'sum'): return ee.Reducer.sum() else: return ee.Reducer.median() def reduceIC(imageCollection, reducer):", "colorPalette} eviImage = ee.Image(eeCollection.map(calcNDMI).mean()) return imageToMapId(eviImage, visParams) def filteredImageNDWIToMapId(startDate, endDate):", ".set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '0000FE,2E60FD,31B0FD,00FEFE,50FE00,DBFE66,FEFE00,FFBB00,FF6F00,FE0000' visParams", "1000, maxPixels=500000000) minElev = minmaxElev.get('elevation_min').getInfo() maxElev = minmaxElev.get('elevation_max').getInfo() ciesinPopGrid =", "return img.divide(10000).updateMask(clear).set('system:time_start', img.get('system:time_start')) def bandPassAdjustment(img): keep = img.select(['temp']) bands =", "= 'c9c0bf,435ebf,eee8aa,006400' visParams = {'opacity': 1, 'max': 1, 'min': -1,", "ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \\ .filterMetadata('CLOUD_COVER', 'less_than', metadataCloudCoverMax) \\ .select(sensorBandDictLandsatTOA['L8'], bandNamesLandsatTOA).map(lsMaskClouds) s2 =", "img.expression('(i.nir - i.red) / (i.nir + i.red)', {'i': img}).rename(['NDVI']) \\", "= minmaxElev.get('elevation_min').getInfo() maxElev = minmaxElev.get('elevation_max').getInfo() ciesinPopGrid = ee.Image('CIESIN/GPWv4/population-count/2020') popDict =", "else: geometry = ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": startDate.strftime('%Y-%m-%d'), \"end\":", "'B5', 'B7'], 'LANDSAT/LT05/C01/T1_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT05/C01/T2_TOA':", "aftDate = imDate + datetime.timedelta(days=1) if isinstance(geometry[0], list): geometry =", "red) / (nir + red + 0.5)) * (1 +", "bandNamesLandsatTOA) \\ .map(bandPassAdjustment) return ee.ImageCollection(lt4.merge(lt5).merge(le7).merge(lc8).merge(s2)) def filteredImageNDVIToMapId(startDate, endDate): def calcNDVI(img):", "elif (lowerIndex == 'evi2'): return filteredImageEVI2ToMapId(startDate, endDate) elif (lowerIndex ==", "ee.ServiceAccountCredentials(ee_account, ee_key_path) ee.Initialize(credentials) else: ee.Initialize() except Exception as e: print(e)", "lowerAsset): skipCloudMask = False elif (\"lt5\" in lowerAsset): skipCloudMask =", "'min'): return imageCollection.min() elif (reducerName == 'max'): return imageCollection.max() elif", "\"\\\"\")) except Exception as e: return {} ########## Helper routes", "return image.updateMask(isSet(['badPixels', 'cloud', 'shadow', 'cirrus']).Not()) def toIndex(image): bands = bandsByCollection[name]", "ee.Geometry.Polygon(geometry) else: geometry = ee.Geometry.Point(geometry) landsatData = getLandsat({ \"start\": startDate.strftime('%Y-%m-%d'),", "dict): return val else: try: return json.loads(val) except Exception as", "json.loads(val) except Exception as e: try: return json.loads(val.replace(\"'\", \"\\\"\")) except", "* i.red - 7.5 * i.blue + 1)', {'i': img}).rename(['EVI'])", "= sentinel1.map(toNatural) sentinel1 = sentinel1.map(addRatioBands) median = sentinel1.median() return imageToMapId(median,", "[1.005], [0.982], [1.001], [1.001], [0.996]]) bias = ee.Array([[-0.00411], [-0.00093], [0.00094],", "'ETM' elif (\"lt5\" in lowerAsset): sID = 'TM' scored =", "matchID)) mapId = ee.Image().paint(single, 0, 2).getMapId(visParams) return mapId['tile_fetcher'].url_format ########## Pre", "skipCloudMask = True elif (\"lc8\" in lowerAsset): skipCloudMask = False", "(reducerName == 'last'): return ee.Reducer.last() elif (reducerName == 'sum'): return", "== 'mode'): return imageCollection.mode() elif (reducerName == 'mosaic'): return imageCollection.mosaic()", "= getReducer(reducer) reduced = image.reduceRegion( theReducer, geometry=geometry, scale=scale, maxPixels=1e6) return", "colorPalette} eviImage = ee.Image(eeCollection.map(calcEVI).mean()) return imageToMapId(eviImage, visParams) def filteredImageEVI2ToMapId(startDate, endDate):", "indexImage lsd = sentinel1Data.map(myimageMapper, True) indexCollection2 = lsd.aggregate_array('indexValue') values =", "calcEVI(img): return img.expression('2.5 * (i.nir - i.red) / (i.nir +", "elif (\"lt5\" in lowerAsset): sID = 'TM' scored = ee.Algorithms.Landsat.simpleCloudScore(", "filteredImageNDWIToMapId(startDate, endDate) def filteredImageCompositeToMapId(assetId, visParams, startDate, endDate, metadataCloudCoverMax, simpleCompositeVariable): eeCollection", "'B2', 'B3', 'B4', 'B5', 'B7'] } indexes = { 'NDVI':", "'B2', 'B3', 'B4', 'B5', 'B7'], 'LANDSAT/LT04/C01/T2_TOA': ['B1', 'B2', 'B3', 'B4',", ".set('system:time_start', img.get('system:time_start')) eeCollection = getLandSatMergedCollection().filterDate(startDate, endDate) colorPalette = '505050,E8E8E8,00FF33,003300' visParams", "myimageMapper(img): theReducer = ee.Reducer.mean() indexValue = img.reduceRegion(theReducer, geometry, 30) date", "'NBR': '(nir - swir2) / (nir + swir2)', 'LSAVI': '((nir", "False eeCollection = ee.ImageCollection(assetId) lowerAsset = assetId.lower() if(\"b2\" not in", "/ (i.nir + 2.4 * i.red + 1)', {'i': img}).rename(['EVI2'])", "/ (i.green + i.nir)', {'i': img}).rename(['NDWI']) \\ .set('system:time_start', img.get('system:time_start')) eeCollection", "geometry = None indexCollection = None if isinstance(coords[0], list): geometry", "indexName != None: indexValue = image.reduceRegion( theReducer, geometry, scale).get(indexName) else:", "def toIndexWithTimeStart(image): time = image.get('system:time_start') image = maskClouds(image) return toIndex(image).set('system:time_start',", "else: return ee.Reducer.median() def reduceIC(imageCollection, reducer): reducerName = reducer.lower() if(reducerName", "= ee.Filter.date(startDate, endDate) eeCollection = eeCollection.filter(eeFilterDate) eeFirstImage = ee.Image(eeCollection.mosaic()) try:", "and reproject array to geographic image componentsImage = ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\", "return imageToMapId(eviImage, visParams) def filteredImageEVI2ToMapId(startDate, endDate): def calcEVI2(img): return img.expression('2.5", "array to geographic image componentsImage = ee.Image(gain).multiply(arrayImage2D).add(ee.Image(bias)) \\ .arrayProject([0]).arrayFlatten([bands]).float() #", "return { 'url': mapId['tile_fetcher'].url_format } ########## ee.ImageCollection ########## def imageCollectionToMapId(assetId,", "endDate) def filteredImageCompositeToMapId(assetId, visParams, startDate, endDate, metadataCloudCoverMax, simpleCompositeVariable): eeCollection =" ]
[ "import admin from django.urls import path,include from django.views.generic import TemplateView", "Index,UserDashboard,SignUp,AdminDashboard app_name='management' urlpatterns = [ # path('',homepage,name=\"index\"), path('',Index.as_view(), name='index'), path('signup',SignUp.as_view(),name=\"signup\"),", "app_name='management' urlpatterns = [ # path('',homepage,name=\"index\"), path('',Index.as_view(), name='index'), path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"),", "django.views.generic import TemplateView from .views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from .views", "# from .views import Index,UserDashboard,SignUp,AdminDashboard app_name='management' urlpatterns = [ #", "name='index'), path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>', activeUser, name='activeUser'), path('admindashboard/showuserdata/deactiveUser/<userId>',", "path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>', activeUser, name='activeUser'), path('admindashboard/showuserdata/deactiveUser/<userId>', deactiveUser, name='deactiveUser'), path('uploadimage/',uploadImage,name=\"uploadImage\"), path('editUserDetail/',UserDetailEdit.as_view(),name='userEditDetail'), path('logout',logout,name='logout')", ".views import Index,UserDashboard,SignUp,AdminDashboard app_name='management' urlpatterns = [ # path('',homepage,name=\"index\"), path('',Index.as_view(),", "Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from .views import Index,UserDashboard,SignUp,AdminDashboard app_name='management' urlpatterns = [", "path('admindashboard/showuserdata/activeUser/<userId>', activeUser, name='activeUser'), path('admindashboard/showuserdata/deactiveUser/<userId>', deactiveUser, name='deactiveUser'), path('uploadimage/',uploadImage,name=\"uploadImage\"), path('editUserDetail/',UserDetailEdit.as_view(),name='userEditDetail'), path('logout',logout,name='logout') ]", "import TemplateView from .views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from .views import", "from .views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from .views import Index,UserDashboard,SignUp,AdminDashboard app_name='management'", "import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from .views import Index,UserDashboard,SignUp,AdminDashboard app_name='management' urlpatterns =", "from django.urls import path,include from django.views.generic import TemplateView from .views", "path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>', activeUser, name='activeUser'), path('admindashboard/showuserdata/deactiveUser/<userId>', deactiveUser, name='deactiveUser'),", "path('',Index.as_view(), name='index'), path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>', activeUser, name='activeUser'),", "from .views import Index,UserDashboard,SignUp,AdminDashboard app_name='management' urlpatterns = [ # path('',homepage,name=\"index\"),", "urlpatterns = [ # path('',homepage,name=\"index\"), path('',Index.as_view(), name='index'), path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"),", "# path('',homepage,name=\"index\"), path('',Index.as_view(), name='index'), path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>',", "import Index,UserDashboard,SignUp,AdminDashboard app_name='management' urlpatterns = [ # path('',homepage,name=\"index\"), path('',Index.as_view(), name='index'),", "import path,include from django.views.generic import TemplateView from .views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage", "path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>', activeUser, name='activeUser'), path('admindashboard/showuserdata/deactiveUser/<userId>', deactiveUser, name='deactiveUser'), path('uploadimage/',uploadImage,name=\"uploadImage\"), path('editUserDetail/',UserDetailEdit.as_view(),name='userEditDetail'),", "from django.views.generic import TemplateView from .views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from", "django.urls import path,include from django.views.generic import TemplateView from .views import", "[ # path('',homepage,name=\"index\"), path('',Index.as_view(), name='index'), path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'),", "from django.contrib import admin from django.urls import path,include from django.views.generic", "path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>', activeUser, name='activeUser'), path('admindashboard/showuserdata/deactiveUser/<userId>', deactiveUser,", "path('',homepage,name=\"index\"), path('',Index.as_view(), name='index'), path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>', activeUser,", "path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'), path('admindashboard/showuserdata/deleteuser/<userId>',deleteuser,name='deleteuser'), path('admindashboard/showuserdata/activeUser/<userId>', activeUser, name='activeUser'), path('admindashboard/showuserdata/deactiveUser/<userId>', deactiveUser, name='deactiveUser'), path('uploadimage/',uploadImage,name=\"uploadImage\"),", ".views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from .views import Index,UserDashboard,SignUp,AdminDashboard app_name='management' urlpatterns", "path,include from django.views.generic import TemplateView from .views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage #", "= [ # path('',homepage,name=\"index\"), path('',Index.as_view(), name='index'), path('signup',SignUp.as_view(),name=\"signup\"), path('userdashboard',UserDashboard.as_view(),name=\"userDashboard\"), path('admindashboard',AdminDashboard.as_view(),name=\"adminDashboard\"), path('admindashboard/showuserdata/',showAdminData.as_view(),name='showAdminData'),", "TemplateView from .views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from .views import Index,UserDashboard,SignUp,AdminDashboard", "django.contrib import admin from django.urls import path,include from django.views.generic import", "admin from django.urls import path,include from django.views.generic import TemplateView from" ]
[ "formatSerialNumber(field): \"\"\" Format an disc serial number. Eg. 0x00085C48 =>", "\".wav\"), \"CDDA\": (ChunkCDDA, u\"audio/x-cda\", u\"Microsoft Windows audio CD file (cda)\",", "info[1] <= size: handler = info[0] for field in handler(self,", "video\") padding = self[\"size\"].value - 4 if 0 < padding:", "Authors: * <NAME> * <NAME> * <NAME> Changelog: * 2007-03-30:", "\"Audio format: Block align\") if size >= 16: yield UInt16(self,", "min(size, self.stream.size) def createFilenameSuffix(self): try: return self.VALID_TYPES[self[\"type\"].value][3] except KeyError: return", "Video for Windows Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt - What is an", "\"notused\", 1) def formatSerialNumber(field): \"\"\" Format an disc serial number.", "RawBytes(self, \"raw_format\", size) def parseVideoFormat(self, size): yield UInt32(self, \"video_size\", \"Video", "while not self.eof: yield AVIIndexEntry(self, \"index[]\") class Chunk(FieldSet): TAG_INFO =", "header[\"microsec_per_frame\"].value if microsec: desc += \", %.1f fps\" % (1000000.0", "the animation cycles\") yield UInt32(self, \"cx\") yield UInt32(self, \"cy\") yield", "offset = (minute*60 + second)*75 + frame + 150 (from", "parseAnimationHeader(self): yield UInt32(self, \"hdr_size\", \"Size of header (36 bytes)\") if", "yield UInt32(self, \"width\", \"Video format: Width\") yield UInt32(self, \"height\", \"Video", "per sample\") if size >= 18: yield UInt16(self, \"ext_size\", \"Audio", "8 < (self.size - self.current_size)/8: field = self.__class__(self, \"field[]\") yield", "video container * WAV audio container * CDA file Documents:", "def createDescription(self): tag = self[\"type\"].value if tag == \"AVI \":", "RawBytes(self, \"padding[]\", (self.size-self.current_size)/8) def createMimeType(self): try: return self.VALID_TYPES[self[\"type\"].value][1] except KeyError:", "if tag == \"AVI \": desc = u\"Microsoft AVI video\"", "\"codec\", \"Audio codec\"), audio_codec_name) yield UInt16(self, \"nb_channel\", \"Number of audio", "RB offset) HSG length = (minute*60 + second)*75 + frame", "\"padding[]\", padding) class AVIIndexEntry(FieldSet): size = 16*8 def createFields(self): yield", "* WAV audio container * CDA file Documents: - libavformat", "= float(field.value) / 60 return humanDuration(timedelta(seconds=sec)) def parseAnimationRate(self): while not", "(\"anim_seq\", parseAnimationSequence, \"Animation sequence\"), 'rate': (\"anim_rate\", parseAnimationRate, \"Animation sequence\"), 'icon':", "class RiffFile(Parser): PARSER_TAGS = { \"id\": \"riff\", \"category\": \"container\", \"file_ext\":", "None, \"Junk (padding)\"), # Metadata \"INAM\": (\"title\", parseText, \"Document title\"),", "self[\"size\"].value - 4 if 0 < padding: yield NullBytes(self, \"padding[]\",", "type depending on file type try: chunk_cls = self.VALID_TYPES[self[\"type\"].value][0] except", "and self[\"a_channel\"].value > 2 yield UInt16(self, \"reserved\", \"Audio format: \")", "= self.tag_info[0] self._description = self.tag_info[2] else: self.tag_info = (\"field[]\", None,", "RIFF content type\" return True def createFields(self): yield String(self, \"signature\",", "yield NullBytes(self, \"reserved\", 4) # Flags yield NullBits(self, \"reserved[]\", 4)", "\"clr_important\", \"Video format: ClrImportant\") def parseAudioFormat(self, size): yield Enum(UInt16(self, \"codec\",", "\"Number of audio channel\") yield UInt32(self, \"sample_per_sec\", \"Sample per second\")", "all chunks up to filesize while self.current_size < self[\"filesize\"].value*8+8: yield", "\"Number of samples\"), 'data': (\"audio_data\", None, \"Audio stream data\"), })", "second)*75 + frame (from RB length) \"\"\" yield UInt16(self, \"cda_version\",", "4, \"Stream four character code\", strip=\" \\0\", charset=\"ASCII\") if self[\"stream_type\"].value", "yield RedBook(self, \"rb_offset\", \"Track offset (Red-book format)\") yield RedBook(self, \"rb_length\",", "size = 16*8 def createFields(self): yield String(self, \"tag\", 4, \"Tag\",", "id\"), audio_codec_name) yield UInt16(self, \"channel\", \"Audio format: Channels\") yield UInt32(self,", "in CD audio (.cda) file \"\"\" def createFields(self): yield UInt8(self,", "yield UInt32(self, \"tag1\", \"Video format: Tag1\") yield UInt32(self, \"img_size\", \"Video", "2 != 0: yield UInt8(self, \"padding[]\", \"Padding\") else: handler =", "header size\") yield String(self, \"stream_type\", 4, \"Stream type four character", "\"left\", \"Destination rectangle (left)\") yield UInt16(self, \"top\", \"Destination rectangle (top)\")", "header[\"height\"].value) microsec = header[\"microsec_per_frame\"].value if microsec: desc += \", %.1f", "parse: * AVI video container * WAV audio container *", "\"odml\": (\"odml\", \"ODML\"), } def __init__(self, *args, **kw): FieldSet.__init__(self, *args,", "UInt16(self, \"cda_version\", \"CD file version (currently 1)\") yield UInt16(self, \"track_no\",", "\"ani\"), \"min_size\": 16*8, \"mime\": (u\"video/x-msvideo\", u\"audio/x-wav\", u\"audio/x-cda\"), # FIXME: Use", "container * WAV audio container * CDA file Documents: -", "yield UInt16(self, \"block_align\", \"Audio format: Block align\") if size >=", "sn = field.value return \"%04X-%04X\" % (sn >> 16, sn", "if handler: for field in handler(self): yield field else: yield", "return True def createFields(self): yield String(self, \"signature\", 4, \"AVI header", "for field in handler(self): yield field else: yield RawBytes(self, \"raw_content\",", "not self.eof: yield textHandler(UInt32(self, \"rate[]\"), formatJiffie) def parseIcon(self): yield SubFile(self,", "UInt16(self, \"channel\", \"Audio format: Channels\") yield UInt32(self, \"sample_rate\", \"Audio format:", "4) yield Bit(self, \"was_capture_file\") yield Bit(self, \"is_copyrighted\") yield NullBits(self, \"reserved[]\",", "\"Size of header (36 bytes)\") if self[\"hdr_size\"].value != 36: self.warning(\"Animation", "parseAVIStreamFormat(self): size = self[\"size\"].value strtype = self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER = {", "desc = u\"Microsoft AVI video\" if \"headers/avi_hdr\" in self: header", "if size >= 18: yield UInt16(self, \"ext_size\", \"Audio format: Size", "def formatJiffie(field): sec = float(field.value) / 60 return humanDuration(timedelta(seconds=sec)) def", "\"Bits per sample\") def parseWAVFact(self): yield UInt32(self, \"nb_sample\", \"Number of", "class AVIIndexEntry(FieldSet): size = 16*8 def createFields(self): yield String(self, \"tag\",", "\"Destination rectangle (bottom)\") class RedBook(FieldSet): \"\"\" RedBook offset parser, used", "\"Uncompressed video frame\", # \"dc\": \"Compressed video frame\", # \"wb\":", "(cda)\", \".cda\"), \"AVI \": (ChunkAVI, u\"video/x-msvideo\", u\"Microsoft AVI video\", \".avi\"),", "filesizeHandler(UInt32(self, \"filesize\", \"File size\")) yield String(self, \"type\", 4, \"Content type", "video_fourcc_name, lambda text: text.upper()) else: yield field yield UInt32(self, \"flags\",", "\"total_frame\", \"Real number of frame of OpenDML video\") padding =", "below # \"strn\": Stream description # TWOCC code, movie/field[]/tag.value[2:4]: #", "%.1f fps\" % (1000000.0 / microsec) if \"total_frame\" in header", "yield RedBook(self, \"rb_length\", \"Track length (Red-book format)\") def parseWAVFormat(self): size", "{ \"vids\": (parseVideoFormat, 40), \"auds\": (parseAudioFormat, 16) } handler =", "\"Stream language\", charset=\"ASCII\", strip=\"\\0\") yield UInt32(self, \"init_frames\", \"InitialFrames\") yield UInt32(self,", "second\") yield UInt16(self, \"block_align\", \"Block align\") yield UInt16(self, \"bit_per_sample\", \"Bits", "self: header = self[\"headers/avi_hdr\"] desc += \": %ux%u pixels\" %", "self._description = self.tag_info[2] else: self.tag_info = (\"field[]\", None, None) def", "yield NullBits(self, \"reserved[]\", 2) yield Bit(self, \"trust_cktype\") yield NullBits(self, \"reserved[]\",", "\"Sub-tag\", charset=\"ASCII\") handler = self.tag_info[1] while 8 < (self.size -", "UInt16(self, \"right\", \"Destination rectangle (right)\") yield UInt16(self, \"bottom\", \"Destination rectangle", "parseWAVFormat(self): size = self[\"size\"].value if size not in (16, 18):", "& 0xFFFF) def parseCDDA(self): \"\"\" HSG address format: number of", "%s bytes is not supported!\" % size) yield Enum(UInt16(self, \"codec\",", "\"top\", \"Destination rectangle (top)\") yield UInt16(self, \"right\", \"Destination rectangle (right)\")", "self[\"size\"].value, parser_class=IcoFile) class ChunkACON(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'anih': (\"anim_hdr\",", "UInt32, Enum, Bit, NullBits, NullBytes, RawBytes, String, PaddingBytes, SubFile) from", "header with unknown size (%s)\" % self[\"size\"].value) yield UInt32(self, \"nb_frame\",", "\"Suggested buffer size\") yield UInt32(self, \"quality\", \"Stream quality\") yield UInt32(self,", "size) def parseVideoFormat(self, size): yield UInt32(self, \"video_size\", \"Video format: Size\")", ">> 16, sn & 0xFFFF) def parseCDDA(self): \"\"\" HSG address", "1)\") yield UInt16(self, \"track_no\", \"Number of track\") yield textHandler(UInt32(self, \"disc_serial\",", "return desc else: try: return self.VALID_TYPES[tag][2] except KeyError: return u\"Microsoft", "\"Number of Blits before the animation cycles\") yield UInt32(self, \"cx\")", "to give frame rate\") yield UInt32(self, \"start\", \"Stream start time", "\"Junk (padding)\"), # Metadata \"INAM\": (\"title\", parseText, \"Document title\"), \"IART\":", "createMimeType(self): try: return self.VALID_TYPES[self[\"type\"].value][1] except KeyError: return None def createDescription(self):", "def createContentSize(self): size = (self[\"filesize\"].value + 8) * 8 return", "if (field.size/8) % 2 != 0: yield UInt8(self, \"padding[]\", \"Padding\")", "u\"Microsoft RIFF container\" def createContentSize(self): size = (self[\"filesize\"].value + 8)", "\"Audio format: \") yield UInt32(self, \"channel_mask\", \"Audio format: channels placement", "Enum(UInt16(self, \"codec\", \"Audio codec\"), audio_codec_name) yield UInt16(self, \"nb_channel\", \"Number of", "\".avi\"), \"ACON\": (ChunkACON, u\"image/x-ani\", u\"Microsoft Windows animated cursor\", \".ani\"), }", "14) yield UInt32(self, \"total_frame\", \"Total number of frames in the", "of samples\"), 'data': (\"audio_data\", None, \"Audio stream data\"), }) def", "placement bitmask\") yield UInt32(self, \"subformat\", \"Audio format: Subformat id\") def", "2, \"Stream language\", charset=\"ASCII\", strip=\"\\0\") yield UInt32(self, \"init_frames\", \"InitialFrames\") yield", "Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"format\", parseWAVFormat, \"Audio format\"), 'fact': (\"nb_sample\",", "- self.current_size)/8: field = self.__class__(self, \"field[]\") yield field if (field.size/8)", "(\"AVI LIST\", 8*8), (\"WAVEfmt \", 8*8), (\"CDDAfmt \", 8*8), (\"ACONanih\",", "(ChunkCDDA, u\"audio/x-cda\", u\"Microsoft Windows audio CD file (cda)\", \".cda\"), \"AVI", "<= size: handler = info[0] for field in handler(self, size):", "\"Block align\") yield UInt16(self, \"bit_per_sample\", \"Bits per sample\") def parseWAVFact(self):", "def validate(self): if self.stream.readBytes(0, 4) != \"RIFF\": return \"Wrong signature\"", "self.subtag_info: info = self.subtag_info[subtag] self.tag_info = (info[0], None, info[1]) self._name", "size\") yield UInt32(self, \"width\", \"Width in pixel\") yield UInt32(self, \"height\",", "title\"), \"IART\": (\"artist\", parseText, \"Artist\"), \"ICMT\": (\"comment\", parseText, \"Comment\"), \"ICOP\":", "humanDuration(timedelta(seconds=sec)) def parseAnimationRate(self): while not self.eof: yield textHandler(UInt32(self, \"rate[]\"), formatJiffie)", "\"Divide by scale to give frame rate\") yield UInt32(self, \"start\",", "info = TYPE_HANDLER[strtype] if info[1] <= size: handler = info[0]", "length = (minute*60 + second)*75 + frame (from RB length)", "\"Artist\"), \"ICMT\": (\"comment\", parseText, \"Comment\"), \"ICOP\": (\"copyright\", parseText, \"Copyright\"), \"IENG\":", "# Flags yield NullBits(self, \"reserved[]\", 4) yield Bit(self, \"has_index\") yield", "from lib.hachoir_core.endian import LITTLE_ENDIAN from lib.hachoir_core.text_handler import filesizeHandler, textHandler from", "\"bits_per_sample\", \"Audio format: Bits per sample\") if size >= 18:", "is not supported!\" % size) yield Enum(UInt16(self, \"codec\", \"Audio codec\"),", "\"Animation header\"), 'seq ': (\"anim_seq\", parseAnimationSequence, \"Animation sequence\"), 'rate': (\"anim_rate\",", "\"category\": \"container\", \"file_ext\": (\"avi\", \"cda\", \"wav\", \"ani\"), \"min_size\": 16*8, \"mime\":", "parseAudioFormat(self, size): yield Enum(UInt16(self, \"codec\", \"Audio format: Codec id\"), audio_codec_name)", "try: chunk_cls = self.VALID_TYPES[self[\"type\"].value][0] except KeyError: chunk_cls = Chunk #", "': (\"cdda\", parseCDDA, \"CD audio informations\"), }) class ChunkWAVE(Chunk): TAG_INFO", "rate/scale)\") yield UInt32(self, \"length\", \"Stream length (unit: rate/scale)\") yield UInt32(self,", "in the video\") yield UInt32(self, \"init_frame\", \"Initial frame (used in", "not self.eof: yield UInt32(self, \"icon[]\") def formatJiffie(field): sec = float(field.value)", "\"track_no\", \"Number of track\") yield textHandler(UInt32(self, \"disc_serial\", \"Disc serial number\"),", "\"Unknown RIFF content type\" return True def createFields(self): yield String(self,", "size >= 16: yield UInt16(self, \"bits_per_sample\", \"Audio format: Bits per", "byte per second\") yield UInt16(self, \"block_align\", \"Block align\") yield UInt16(self,", "UInt32(self, \"height\", \"Height in pixel\") yield UInt32(self, \"scale\") yield UInt32(self,", "(\"cdda\", parseCDDA, \"CD audio informations\"), }) class ChunkWAVE(Chunk): TAG_INFO =", "(self.size-self.current_size)/8) def createMimeType(self): try: return self.VALID_TYPES[self[\"type\"].value][1] except KeyError: return None", "\"Microsoft RIFF container\" } VALID_TYPES = { \"WAVE\": (ChunkWAVE, u\"audio/x-wav\",", "\"Padding\") else: handler = self.tag_info[1] if handler: for field in", "\"priority\", \"Stream priority\") yield String(self, \"language\", 2, \"Stream language\", charset=\"ASCII\",", "audio container * CDA file Documents: - libavformat source code", "\"Stream four character code\", strip=\" \\0\", charset=\"ASCII\") if self[\"stream_type\"].value ==", "change\" } subtag_info = { \"INFO\": (\"info\", \"File informations\"), \"hdrl\":", "Depth\") yield UInt32(self, \"tag1\", \"Video format: Tag1\") yield UInt32(self, \"img_size\",", "audio_codec_name) yield UInt16(self, \"nb_channel\", \"Number of audio channel\") yield UInt32(self,", "\".ani\"), } endian = LITTLE_ENDIAN def validate(self): if self.stream.readBytes(0, 4)", "(unit: rate/scale)\") yield UInt32(self, \"length\", \"Stream length (unit: rate/scale)\") yield", "def createFields(self): yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield UInt32(self,", "filesizeHandler(UInt32(self, \"size\", \"Size\")) if not self[\"size\"].value: return if self[\"tag\"].value ==", "(wojtekka AT logonet.com.pl) for its CDA file format information \"\"\"", "4, \"AVI header (RIFF)\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"filesize\", \"File size\"))", "Windows animated cursor\", \".ani\"), } endian = LITTLE_ENDIAN def validate(self):", "* microsec) desc += \", \" + humanDuration(delta) return desc", "def parseRawFormat(self, size): yield RawBytes(self, \"raw_format\", size) def parseVideoFormat(self, size):", "from lib.hachoir_core.text_handler import filesizeHandler, textHandler from lib.hachoir_parser.video.fourcc import audio_codec_name, video_fourcc_name", "in pixel\") yield UInt32(self, \"scale\") yield UInt32(self, \"rate\") yield UInt32(self,", "self.eof: yield UInt32(self, \"icon[]\") def formatJiffie(field): sec = float(field.value) /", "\"AVI \": (ChunkAVI, u\"video/x-msvideo\", u\"Microsoft AVI video\", \".avi\"), \"ACON\": (ChunkACON,", "if self[\"stream_type\"].value == \"vids\": yield Enum(field, video_fourcc_name, lambda text: text.upper())", "= self.tag_info[2] else: self.tag_info = (\"field[]\", None, None) def createFields(self):", "serial number\"), formatSerialNumber) yield UInt32(self, \"hsg_offset\", \"Track offset (HSG format)\")", "4) # Flags yield NullBits(self, \"reserved[]\", 4) yield Bit(self, \"has_index\")", "UInt32(self, \"nb_step\", \"Number of Blits before the animation cycles\") yield", "8*8), (\"WAVEfmt \", 8*8), (\"CDDAfmt \", 8*8), (\"ACONanih\", 8*8), ),", "\"WAVE\": (ChunkWAVE, u\"audio/x-wav\", u\"Microsoft WAVE audio\", \".wav\"), \"CDDA\": (ChunkCDDA, u\"audio/x-cda\",", "UInt32(self, \"length\") def parseODML(self): yield UInt32(self, \"total_frame\", \"Real number of", "return humanDuration(timedelta(seconds=sec)) def parseAnimationRate(self): while not self.eof: yield textHandler(UInt32(self, \"rate[]\"),", "UInt16(self, \"panes\", \"Video format: Panes\") yield UInt16(self, \"depth\", \"Video format:", "Format an disc serial number. Eg. 0x00085C48 => \"0008-5C48\" \"\"\"", "\"Number of samples in audio stream\") def parseAviHeader(self): yield UInt32(self,", "**kw) self._size = (8 + alignValue(self[\"size\"].value, 2)) * 8 tag", "parser * 2006-08-03: creation of CDA parser by <NAME> *", "} endian = LITTLE_ENDIAN def validate(self): if self.stream.readBytes(0, 4) !=", "self[\"size\"].value, strip=\" \\0\", truncate=\"\\0\", charset=\"ISO-8859-1\") def parseRawFormat(self, size): yield RawBytes(self,", "yield filesizeHandler(UInt32(self, \"filesize\", \"File size\")) yield String(self, \"type\", 4, \"Content", "\"ICRD\": (\"creation_date\", parseText, \"Creation date\"), \"ISFT\": (\"producer\", parseText, \"Producer\"), \"IDIT\":", "into RIFF parser * 2006-08-03: creation of CDA parser by", "an disc serial number. Eg. 0x00085C48 => \"0008-5C48\" \"\"\" sn", "not in self.VALID_TYPES: return \"Unknown RIFF content type\" return True", "handler = self.tag_info[1] if handler: for field in handler(self): yield", "parseAviHeader, \"AVI header\"), \"idx1\": (\"index\", parseIndex, \"Stream index\"), \"dmlh\": (\"odml_hdr\",", "yield String(self, \"signature\", 4, \"AVI header (RIFF)\", charset=\"ASCII\") yield filesizeHandler(UInt32(self,", "<NAME> Thanks to: * <NAME> (wojtekka AT logonet.com.pl) for its", "def createFields(self): yield String(self, \"signature\", 4, \"AVI header (RIFF)\", charset=\"ASCII\")", "frame\") yield UInt32(self, \"max_byte_per_sec\", \"Maximum byte per second\") yield NullBytes(self,", "(HSG format)\") yield UInt32(self, \"hsg_length\", \"Track length (HSG format)\") yield", "header\"), }) class ChunkCDDA(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ':", "= 16*8 def createFields(self): yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\")", "TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ \"strh\": (\"stream_hdr\", parseAVIStreamHeader, \"Stream header\"), \"strf\":", "Use regex \"RIFF.{4}(WAVE|CDDA|AVI )\" \"magic\": ( (\"AVI LIST\", 8*8), (\"WAVEfmt", "def parseWAVFact(self): yield UInt32(self, \"nb_sample\", \"Number of samples in audio", "creation of CDA parser by <NAME> * 2005-06-21: creation of", "(HSG format)\") yield RedBook(self, \"rb_offset\", \"Track offset (Red-book format)\") yield", "this cursor\") yield UInt32(self, \"nb_step\", \"Number of Blits before the", "of extra information\") if size >= 28: # and self[\"a_channel\"].value", "(padding)\"), # Metadata \"INAM\": (\"title\", parseText, \"Document title\"), \"IART\": (\"artist\",", "parseVideoFormat(self, size): yield UInt32(self, \"video_size\", \"Video format: Size\") yield UInt32(self,", "def parseWAVFormat(self): size = self[\"size\"].value if size not in (16,", "(Red-book format)\") def parseWAVFormat(self): size = self[\"size\"].value if size not", "field in handler(self): yield field else: yield RawBytes(self, \"raw_content\", self[\"size\"].value)", "\"padding[]\", (self.size-self.current_size)/8) def createMimeType(self): try: return self.VALID_TYPES[self[\"type\"].value][1] except KeyError: return", "\"\"\" from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, ParserError,", "+= \": %ux%u pixels\" % (header[\"width\"].value, header[\"height\"].value) microsec = header[\"microsec_per_frame\"].value", "stream\"), \"odml\": (\"odml\", \"ODML\"), } def __init__(self, *args, **kw): FieldSet.__init__(self,", "WAV parser by <NAME> * 2005-06-08: creation of AVI parser", "1) def formatSerialNumber(field): \"\"\" Format an disc serial number. Eg.", "charset=\"ASCII\") field = String(self, \"fourcc\", 4, \"Stream four character code\",", "parseWAVFormat, \"Audio format\"), 'fact': (\"nb_sample\", parseWAVFact, \"Number of samples\"), 'data':", "UInt32(self, \"total_frame\", \"Real number of frame of OpenDML video\") padding", "endian = LITTLE_ENDIAN def validate(self): if self.stream.readBytes(0, 4) != \"RIFF\":", "Width\") yield UInt32(self, \"height\", \"Video format: Height\") yield UInt16(self, \"panes\",", "+ humanDuration(delta) return desc else: try: return self.VALID_TYPES[tag][2] except KeyError:", "u\"audio/x-wav\", u\"audio/x-cda\"), # FIXME: Use regex \"RIFF.{4}(WAVE|CDDA|AVI )\" \"magic\": (", "= (minute*60 + second)*75 + frame + 150 (from RB", "= Chunk # Parse all chunks up to filesize while", "truncate=\"\\0\", charset=\"ISO-8859-1\") def parseRawFormat(self, size): yield RawBytes(self, \"raw_format\", size) def", "UInt32(self, \"subformat\", \"Audio format: Subformat id\") def parseAVIStreamFormat(self): size =", "String(self, \"signature\", 4, \"AVI header (RIFF)\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"filesize\",", "(\"movie\", \"Movie stream\"), \"odml\": (\"odml\", \"ODML\"), } def __init__(self, *args,", "\"Author\"), \"ICRD\": (\"creation_date\", parseText, \"Creation date\"), \"ISFT\": (\"producer\", parseText, \"Producer\"),", "yield UInt32(self, \"subformat\", \"Audio format: Subformat id\") def parseAVIStreamFormat(self): size", "UInt32(self, \"max_byte_per_sec\", \"Maximum byte per second\") yield NullBytes(self, \"reserved\", 4)", "data\", # \"pc\": \"Palette change\" } subtag_info = { \"INFO\":", "second\") yield NullBytes(self, \"reserved\", 4) # Flags yield NullBits(self, \"reserved[]\",", "\"Audio format: Bit rate\") yield UInt16(self, \"block_align\", \"Audio format: Block", "size not in (16, 18): self.warning(\"Format with size of %s", "size of %s bytes is not supported!\" % size) yield", "yield UInt32(self, \"bit_rate\", \"Audio format: Bit rate\") yield UInt16(self, \"block_align\",", "\"fourcc\", 4, \"Stream four character code\", strip=\" \\0\", charset=\"ASCII\") if", "* 2006-08-08: merge AVI, WAV and CDA parsers into RIFF", "merge AVI, WAV and CDA parsers into RIFF parser *", "Size\") yield UInt32(self, \"width\", \"Video format: Width\") yield UInt32(self, \"height\",", "list\"), \"movi\": (\"movie\", \"Movie stream\"), \"odml\": (\"odml\", \"ODML\"), } def", "information\") if size >= 28: # and self[\"a_channel\"].value > 2", "PARSER_TAGS = { \"id\": \"riff\", \"category\": \"container\", \"file_ext\": (\"avi\", \"cda\",", "\"Maximum byte per second\") yield NullBytes(self, \"reserved\", 4) # Flags", "= Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"cdda\", parseCDDA, \"CD audio informations\"),", "ClrImportant\") def parseAudioFormat(self, size): yield Enum(UInt16(self, \"codec\", \"Audio format: Codec", "self.warning(\"Animation header with unknown size (%s)\" % self[\"size\"].value) yield UInt32(self,", "\\0\", truncate=\"\\0\", charset=\"ISO-8859-1\") def parseRawFormat(self, size): yield RawBytes(self, \"raw_format\", size)", "padding: yield padding def createDescription(self): tag = self[\"tag\"].display return u\"Chunk", "\"Icon\"), }) class RiffFile(Parser): PARSER_TAGS = { \"id\": \"riff\", \"category\":", "PaddingBytes(self, \"notused\", 1) def formatSerialNumber(field): \"\"\" Format an disc serial", "desc += \", \" + humanDuration(delta) return desc else: try:", "per frame\") yield UInt32(self, \"max_byte_per_sec\", \"Maximum byte per second\") yield", "* 2005-06-21: creation of WAV parser by <NAME> * 2005-06-08:", "createFields(self): yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield UInt32(self, \"flags\")", "and <NAME> Thanks to: * <NAME> (wojtekka AT logonet.com.pl) for", "\"was_capture_file\") yield Bit(self, \"is_copyrighted\") yield NullBits(self, \"reserved[]\", 14) yield UInt32(self,", "while not self.eof: yield textHandler(UInt32(self, \"rate[]\"), formatJiffie) def parseIcon(self): yield", "yield UInt32(self, \"start\") yield UInt32(self, \"length\") def parseODML(self): yield UInt32(self,", "TAG_INFO.update({ 'anih': (\"anim_hdr\", parseAnimationHeader, \"Animation header\"), 'seq ': (\"anim_seq\", parseAnimationSequence,", "def formatSerialNumber(field): \"\"\" Format an disc serial number. Eg. 0x00085C48", "\"strh\": (\"stream_hdr\", parseAVIStreamHeader, \"Stream header\"), \"strf\": (\"stream_fmt\", parseAVIStreamFormat, \"Stream format\"),", "\"bottom\", \"Destination rectangle (bottom)\") class RedBook(FieldSet): \"\"\" RedBook offset parser,", "\"InitialFrames\") yield UInt32(self, \"scale\", \"Time scale\") yield UInt32(self, \"rate\", \"Divide", "0xFFFF) def parseCDDA(self): \"\"\" HSG address format: number of 1/75", "parseAnimationSequence, \"Animation sequence\"), 'rate': (\"anim_rate\", parseAnimationRate, \"Animation sequence\"), 'icon': (\"icon[]\",", "in self.VALID_TYPES: return \"Unknown RIFF content type\" return True def", "yield UInt32(self, \"rate\", \"Divide by scale to give frame rate\")", "= { \"id\": \"riff\", \"category\": \"container\", \"file_ext\": (\"avi\", \"cda\", \"wav\",", "parseIndex, \"Stream index\"), \"dmlh\": (\"odml_hdr\", parseODML, \"ODML header\"), }) class", "TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"cdda\", parseCDDA, \"CD audio", "\"clr_used\", \"Video format: ClrUsed\") yield UInt32(self, \"clr_important\", \"Video format: ClrImportant\")", "\"ODML header\"), }) class ChunkCDDA(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt", "length (HSG format)\") yield RedBook(self, \"rb_offset\", \"Track offset (Red-book format)\")", "of AVI parser by <NAME> and <NAME> Thanks to: *", "<NAME> and <NAME> Thanks to: * <NAME> (wojtekka AT logonet.com.pl)", "\"block_align\", \"Block align\") yield UInt16(self, \"bit_per_sample\", \"Bits per sample\") def", "if size >= 16: yield UInt16(self, \"bits_per_sample\", \"Audio format: Bits", "yield UInt32(self, \"total_frame\", \"Total number of frames in the video\")", "Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt - What is an animated cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm", "\"IART\": (\"artist\", parseText, \"Artist\"), \"ICMT\": (\"comment\", parseText, \"Comment\"), \"ICOP\": (\"copyright\",", "video)\") yield UInt32(self, \"nb_stream\", \"Number of streams\") yield UInt32(self, \"sug_buf_size\",", "# TWOCC code, movie/field[]/tag.value[2:4]: # \"db\": \"Uncompressed video frame\", #", "formatSerialNumber) yield UInt32(self, \"hsg_offset\", \"Track offset (HSG format)\") yield UInt32(self,", "if subtag in self.subtag_info: info = self.subtag_info[subtag] self.tag_info = (info[0],", "UInt16(self, \"left\", \"Destination rectangle (left)\") yield UInt16(self, \"top\", \"Destination rectangle", "'icon': (\"icon[]\", parseIcon, \"Icon\"), }) class RiffFile(Parser): PARSER_TAGS = {", "-*- \"\"\" RIFF parser, able to parse: * AVI video", "\"ICOP\": (\"copyright\", parseText, \"Copyright\"), \"IENG\": (\"author\", parseText, \"Author\"), \"ICRD\": (\"creation_date\",", "self[\"size\"].value if size not in (16, 18): self.warning(\"Format with size", "KeyError: return None def createDescription(self): tag = self[\"type\"].value if tag", "\"Width in pixel\") yield UInt32(self, \"height\", \"Height in pixel\") yield", "\"language\", 2, \"Stream language\", charset=\"ASCII\", strip=\"\\0\") yield UInt32(self, \"init_frames\", \"InitialFrames\")", "parser by <NAME> * 2005-06-08: creation of AVI parser by", "video frame\", # \"dc\": \"Compressed video frame\", # \"wb\": \"Audio", "in handler(self): yield field else: yield RawBytes(self, \"raw_content\", self[\"size\"].value) padding", "quality\") yield UInt32(self, \"sample_size\", \"Size of samples\") yield UInt16(self, \"left\",", "\"width\", \"Width in pixel\") yield UInt32(self, \"height\", \"Height in pixel\")", "\"reserved[]\", 14) yield UInt32(self, \"total_frame\", \"Total number of frames in", "def parseIcon(self): yield SubFile(self, \"icon_file\", self[\"size\"].value, parser_class=IcoFile) class ChunkACON(Chunk): TAG_INFO", "- Video for Windows Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt - What is", "start time (unit: rate/scale)\") yield UInt32(self, \"length\", \"Stream length (unit:", "from lib.hachoir_core.tools import alignValue, humanDuration from lib.hachoir_core.endian import LITTLE_ENDIAN from", "\"Wrong signature\" if self[\"type\"].value not in self.VALID_TYPES: return \"Unknown RIFF", "Windows audio CD file (cda)\", \".cda\"), \"AVI \": (ChunkAVI, u\"video/x-msvideo\",", "(.cda) file \"\"\" def createFields(self): yield UInt8(self, \"frame\") yield UInt8(self,", "parseWAVFact, \"Number of samples\"), 'data': (\"audio_data\", None, \"Audio stream data\"),", "u\"Microsoft Windows animated cursor\", \".ani\"), } endian = LITTLE_ENDIAN def", "if self[\"size\"].value != 56: raise ParserError(\"Invalid stream header size\") yield", "charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"filesize\", \"File size\")) yield String(self, \"type\", 4,", "self[\"tag\"].display return u\"Chunk (tag %s)\" % tag class ChunkAVI(Chunk): TAG_INFO", "if self[\"tag\"].value == \"LIST\": yield String(self, \"subtag\", 4, \"Sub-tag\", charset=\"ASCII\")", "yield String(self, \"subtag\", 4, \"Sub-tag\", charset=\"ASCII\") handler = self.tag_info[1] while", "textHandler(UInt32(self, \"rate[]\"), formatJiffie) def parseIcon(self): yield SubFile(self, \"icon_file\", self[\"size\"].value, parser_class=IcoFile)", "\"sug_buf_size\", \"Suggested buffer size\") yield UInt32(self, \"width\", \"Width in pixel\")", "* <NAME> Changelog: * 2007-03-30: support ACON (animated icons) *", "yield UInt32(self, \"byte_per_sec\", \"Average byte per second\") yield UInt16(self, \"block_align\",", "self[\"type\"].value if tag == \"AVI \": desc = u\"Microsoft AVI", "RedBook(FieldSet): \"\"\" RedBook offset parser, used in CD audio (.cda)", "\"wav\", \"ani\"), \"min_size\": 16*8, \"mime\": (u\"video/x-msvideo\", u\"audio/x-wav\", u\"audio/x-cda\"), # FIXME:", "frame\", # \"wb\": \"Audio data\", # \"pc\": \"Palette change\" }", "SubFile(self, \"icon_file\", self[\"size\"].value, parser_class=IcoFile) class ChunkACON(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({", "yield String(self, \"type\", 4, \"Content type (\\\"AVI \\\", \\\"WAVE\\\", ...)\",", "yield UInt32(self, \"icon[]\") def formatJiffie(field): sec = float(field.value) / 60", "(RIFF)\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"filesize\", \"File size\")) yield String(self, \"type\",", "per second\") yield UInt32(self, \"byte_per_sec\", \"Average byte per second\") yield", "\"start\", \"Stream start time (unit: rate/scale)\") yield UInt32(self, \"length\", \"Stream", "None, \"Sub-field list\"), \"JUNK\": (\"junk[]\", None, \"Junk (padding)\"), # Metadata", "per second\") yield NullBytes(self, \"reserved\", 4) # Flags yield NullBits(self,", "field if (field.size/8) % 2 != 0: yield UInt8(self, \"padding[]\",", "desc += \", %.1f fps\" % (1000000.0 / microsec) if", "chunk_cls = self.VALID_TYPES[self[\"type\"].value][0] except KeyError: chunk_cls = Chunk # Parse", "import Parser from lib.hachoir_core.field import (FieldSet, ParserError, UInt8, UInt16, UInt32,", "\"init_frames\", \"InitialFrames\") yield UInt32(self, \"scale\", \"Time scale\") yield UInt32(self, \"rate\",", "def parseODML(self): yield UInt32(self, \"total_frame\", \"Real number of frame of", "UInt32(self, \"start\", \"Stream start time (unit: rate/scale)\") yield UInt32(self, \"length\",", "NullBits(self, \"reserved[]\", 2) yield Bit(self, \"is_interleaved\") yield NullBits(self, \"reserved[]\", 2)", "animated cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm Authors: * <NAME> * <NAME> * <NAME>", "UInt32(self, \"planes\") yield UInt32(self, \"jiffie_rate\", \"Default Jiffies (1/60th of a", "'fact': (\"nb_sample\", parseWAVFact, \"Number of samples\"), 'data': (\"audio_data\", None, \"Audio", "} subtag_info = { \"INFO\": (\"info\", \"File informations\"), \"hdrl\": (\"headers\",", "video\") yield UInt32(self, \"init_frame\", \"Initial frame (used in interleaved video)\")", "\"Creation date\"), \"ISFT\": (\"producer\", parseText, \"Producer\"), \"IDIT\": (\"datetime\", parseText, \"Date", "Jiffies (1/60th of a second) if rate chunk not present\")", "self.stream.readBytes(0, 4) != \"RIFF\": return \"Wrong signature\" if self[\"type\"].value not", "AVIIndexEntry(self, \"index[]\") class Chunk(FieldSet): TAG_INFO = { # This dictionnary", "56: raise ParserError(\"Invalid stream header size\") yield String(self, \"stream_type\", 4,", "\"img_size\", \"Video format: Image size\") yield UInt32(self, \"xpels_meter\", \"Video format:", "field in handler(self, size): yield field def parseAVIStreamHeader(self): if self[\"size\"].value", "(right)\") yield UInt16(self, \"bottom\", \"Destination rectangle (bottom)\") class RedBook(FieldSet): \"\"\"", "\"raw_format\", size) def parseVideoFormat(self, size): yield UInt32(self, \"video_size\", \"Video format:", "of WAV parser by <NAME> * 2005-06-08: creation of AVI", "\"rb_offset\", \"Track offset (Red-book format)\") yield RedBook(self, \"rb_length\", \"Track length", "\"scale\") yield UInt32(self, \"rate\") yield UInt32(self, \"start\") yield UInt32(self, \"length\")", "delta = timedelta(seconds=float(header[\"total_frame\"].value) * microsec) desc += \", \" +", "yield AVIIndexEntry(self, \"index[]\") class Chunk(FieldSet): TAG_INFO = { # This", "bitmask\") yield UInt32(self, \"subformat\", \"Audio format: Subformat id\") def parseAVIStreamFormat(self):", "TYPE_HANDLER = { \"vids\": (parseVideoFormat, 40), \"auds\": (parseAudioFormat, 16) }", "\"File informations\"), \"hdrl\": (\"headers\", \"Headers\"), \"strl\": (\"stream[]\", \"Stream header list\"),", ">= 16: yield UInt16(self, \"bits_per_sample\", \"Audio format: Bits per sample\")", "\"min_size\": 16*8, \"mime\": (u\"video/x-msvideo\", u\"audio/x-wav\", u\"audio/x-cda\"), # FIXME: Use regex", "UInt16(self, \"nb_channel\", \"Number of audio channel\") yield UInt32(self, \"sample_per_sec\", \"Sample", "yield UInt32(self, \"sug_buf_size\", \"Suggested buffer size\") yield UInt32(self, \"width\", \"Width", "unknown size (%s)\" % self[\"size\"].value) yield UInt32(self, \"nb_frame\", \"Number of", "format: Image size\") yield UInt32(self, \"xpels_meter\", \"Video format: XPelsPerMeter\") yield", "Documents: - libavformat source code from ffmpeg library http://ffmpeg.mplayerhq.hu/ -", "': (\"anim_seq\", parseAnimationSequence, \"Animation sequence\"), 'rate': (\"anim_rate\", parseAnimationRate, \"Animation sequence\"),", "of unique Icons in this cursor\") yield UInt32(self, \"nb_step\", \"Number", "\"flags\") yield UInt32(self, \"start\", \"Offset from start of movie data\")", "format)\") def parseWAVFormat(self): size = self[\"size\"].value if size not in", "(\"nb_sample\", parseWAVFact, \"Number of samples\"), 'data': (\"audio_data\", None, \"Audio stream", "parseText, \"Creation date\"), \"ISFT\": (\"producer\", parseText, \"Producer\"), \"IDIT\": (\"datetime\", parseText,", "format: ClrUsed\") yield UInt32(self, \"clr_important\", \"Video format: ClrImportant\") def parseAudioFormat(self,", "not self.eof: yield RawBytes(self, \"padding[]\", (self.size-self.current_size)/8) def createMimeType(self): try: return", "\"Audio data\", # \"pc\": \"Palette change\" } subtag_info = {", "UInt32(self, \"clr_important\", \"Video format: ClrImportant\") def parseAudioFormat(self, size): yield Enum(UInt16(self,", "UInt8(self, \"minute\") yield PaddingBytes(self, \"notused\", 1) def formatSerialNumber(field): \"\"\" Format", "Todo: see below # \"strn\": Stream description # TWOCC code,", "self._name = self.tag_info[0] self._description = self.tag_info[2] else: self.tag_info = (\"field[]\",", "TAG_INFO.update({ \"strh\": (\"stream_hdr\", parseAVIStreamHeader, \"Stream header\"), \"strf\": (\"stream_fmt\", parseAVIStreamFormat, \"Stream", ")\" \"magic\": ( (\"AVI LIST\", 8*8), (\"WAVEfmt \", 8*8), (\"CDDAfmt", "Windows Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt - What is an animated cursor?", "\"subformat\", \"Audio format: Subformat id\") def parseAVIStreamFormat(self): size = self[\"size\"].value", "file version (currently 1)\") yield UInt16(self, \"track_no\", \"Number of track\")", "\"Video format: Depth\") yield UInt32(self, \"tag1\", \"Video format: Tag1\") yield", "\"buf_size\", \"Suggested buffer size\") yield UInt32(self, \"quality\", \"Stream quality\") yield", "{ \"INFO\": (\"info\", \"File informations\"), \"hdrl\": (\"headers\", \"Headers\"), \"strl\": (\"stream[]\",", "from lib.hachoir_core.field import (FieldSet, ParserError, UInt8, UInt16, UInt32, Enum, Bit,", "self[\"type\"].value not in self.VALID_TYPES: return \"Unknown RIFF content type\" return", "coding: UTF-8 -*- \"\"\" RIFF parser, able to parse: *", "(1/60th of a second) if rate chunk not present\") yield", "\"Video format: Height\") yield UInt16(self, \"panes\", \"Video format: Panes\") yield", "UInt32(self, \"sample_per_sec\", \"Sample per second\") yield UInt32(self, \"byte_per_sec\", \"Average byte", "FIXME: Use regex \"RIFF.{4}(WAVE|CDDA|AVI )\" \"magic\": ( (\"AVI LIST\", 8*8),", "Chunk # Parse all chunks up to filesize while self.current_size", "yield UInt16(self, \"depth\", \"Video format: Depth\") yield UInt32(self, \"tag1\", \"Video", "\"\"\" RIFF parser, able to parse: * AVI video container", "\"Video format: XPelsPerMeter\") yield UInt32(self, \"ypels_meter\", \"Video format: YPelsPerMeter\") yield", "(\"info\", \"File informations\"), \"hdrl\": (\"headers\", \"Headers\"), \"strl\": (\"stream[]\", \"Stream header", "* AVI video container * WAV audio container * CDA", "\": %ux%u pixels\" % (header[\"width\"].value, header[\"height\"].value) microsec = header[\"microsec_per_frame\"].value if", "tag = self[\"type\"].value if tag == \"AVI \": desc =", "(minute*60 + second)*75 + frame (from RB length) \"\"\" yield", "of frame of OpenDML video\") padding = self[\"size\"].value - 4", "dictionnary is edited by RiffFile.validate() \"LIST\": (\"list[]\", None, \"Sub-field list\"),", "# Parse all chunks up to filesize while self.current_size <", "type (\\\"AVI \\\", \\\"WAVE\\\", ...)\", charset=\"ASCII\") # Choose chunk type", "(\"copyright\", parseText, \"Copyright\"), \"IENG\": (\"author\", parseText, \"Author\"), \"ICRD\": (\"creation_date\", parseText,", "yield UInt32(self, \"bit_count\") yield UInt32(self, \"planes\") yield UInt32(self, \"jiffie_rate\", \"Default", "UInt32(self, \"quality\", \"Stream quality\") yield UInt32(self, \"sample_size\", \"Size of samples\")", "16*8, \"mime\": (u\"video/x-msvideo\", u\"audio/x-wav\", u\"audio/x-cda\"), # FIXME: Use regex \"RIFF.{4}(WAVE|CDDA|AVI", "UInt32(self, \"nb_frame\", \"Number of unique Icons in this cursor\") yield", "2007-03-30: support ACON (animated icons) * 2006-08-08: merge AVI, WAV", "\"Content type (\\\"AVI \\\", \\\"WAVE\\\", ...)\", charset=\"ASCII\") # Choose chunk", "\"db\": \"Uncompressed video frame\", # \"dc\": \"Compressed video frame\", #", "UInt32(self, \"rate\") yield UInt32(self, \"start\") yield UInt32(self, \"length\") def parseODML(self):", "parseIcon(self): yield SubFile(self, \"icon_file\", self[\"size\"].value, parser_class=IcoFile) class ChunkACON(Chunk): TAG_INFO =", "= self.seekBit(self._size) if padding: yield padding def createDescription(self): tag =", "parseRawFormat if strtype in TYPE_HANDLER: info = TYPE_HANDLER[strtype] if info[1]", "...)\", charset=\"ASCII\") # Choose chunk type depending on file type", "rate\") yield UInt16(self, \"block_align\", \"Audio format: Block align\") if size", "(\"CDDAfmt \", 8*8), (\"ACONanih\", 8*8), ), \"description\": \"Microsoft RIFF container\"", "0 < padding: yield NullBytes(self, \"padding[]\", padding) class AVIIndexEntry(FieldSet): size", "in pixel\") yield UInt32(self, \"height\", \"Height in pixel\") yield UInt32(self,", "(\"author\", parseText, \"Author\"), \"ICRD\": (\"creation_date\", parseText, \"Creation date\"), \"ISFT\": (\"producer\",", "UInt32(self, \"nb_stream\", \"Number of streams\") yield UInt32(self, \"sug_buf_size\", \"Suggested buffer", "(\"list[]\", None, \"Sub-field list\"), \"JUNK\": (\"junk[]\", None, \"Junk (padding)\"), #", "if rate chunk not present\") yield Bit(self, \"is_icon\") yield NullBits(self,", "% tag class ChunkAVI(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ \"strh\": (\"stream_hdr\",", "(self[\"filesize\"].value + 8) * 8 return min(size, self.stream.size) def createFilenameSuffix(self):", "id\") def parseAVIStreamFormat(self): size = self[\"size\"].value strtype = self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER", "(\"producer\", parseText, \"Producer\"), \"IDIT\": (\"datetime\", parseText, \"Date time\"), # TODO:", "4, \"Tag\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"size\", \"Size\")) if not self[\"size\"].value:", "(\"creation_date\", parseText, \"Creation date\"), \"ISFT\": (\"producer\", parseText, \"Producer\"), \"IDIT\": (\"datetime\",", "def parseAviHeader(self): yield UInt32(self, \"microsec_per_frame\", \"Microsecond per frame\") yield UInt32(self,", "not present\") yield Bit(self, \"is_icon\") yield NullBits(self, \"padding\", 31) def", "'rate': (\"anim_rate\", parseAnimationRate, \"Animation sequence\"), 'icon': (\"icon[]\", parseIcon, \"Icon\"), })", "from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, ParserError, UInt8,", "\"Number of track\") yield textHandler(UInt32(self, \"disc_serial\", \"Disc serial number\"), formatSerialNumber)", "def parseAnimationRate(self): while not self.eof: yield textHandler(UInt32(self, \"rate[]\"), formatJiffie) def", "\"is_interleaved\") yield NullBits(self, \"reserved[]\", 2) yield Bit(self, \"trust_cktype\") yield NullBits(self,", "\"rate\", \"Divide by scale to give frame rate\") yield UInt32(self,", "parseODML(self): yield UInt32(self, \"total_frame\", \"Real number of frame of OpenDML", "\"Date time\"), # TODO: Todo: see below # \"strn\": Stream", "Bit rate\") yield UInt16(self, \"block_align\", \"Audio format: Block align\") if", "ChunkACON(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'anih': (\"anim_hdr\", parseAnimationHeader, \"Animation header\"),", "\"Tag\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"size\", \"Size\")) if not self[\"size\"].value: return", "yield UInt16(self, \"reserved\", \"Audio format: \") yield UInt32(self, \"channel_mask\", \"Audio", "yield UInt16(self, \"channel\", \"Audio format: Channels\") yield UInt32(self, \"sample_rate\", \"Audio", "4, \"Tag\", charset=\"ASCII\") yield UInt32(self, \"flags\") yield UInt32(self, \"start\", \"Offset", "TWOCC code, movie/field[]/tag.value[2:4]: # \"db\": \"Uncompressed video frame\", # \"dc\":", "self.VALID_TYPES: return \"Unknown RIFF content type\" return True def createFields(self):", "disc serial number. Eg. 0x00085C48 => \"0008-5C48\" \"\"\" sn =", "filesize while self.current_size < self[\"filesize\"].value*8+8: yield chunk_cls(self, \"chunk[]\") if not", "(parseAudioFormat, 16) } handler = parseRawFormat if strtype in TYPE_HANDLER:", "TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'anih': (\"anim_hdr\", parseAnimationHeader, \"Animation header\"), 'seq", "yield UInt32(self, \"width\", \"Width in pixel\") yield UInt32(self, \"height\", \"Height", "icons) * 2006-08-08: merge AVI, WAV and CDA parsers into", "= (\"field[]\", None, None) def createFields(self): yield String(self, \"tag\", 4,", "\", \" + humanDuration(delta) return desc else: try: return self.VALID_TYPES[tag][2]", "information \"\"\" from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet,", "\"hsg_offset\", \"Track offset (HSG format)\") yield UInt32(self, \"hsg_length\", \"Track length", "pixel\") yield UInt32(self, \"scale\") yield UInt32(self, \"rate\") yield UInt32(self, \"start\")", "UInt16(self, \"bottom\", \"Destination rectangle (bottom)\") class RedBook(FieldSet): \"\"\" RedBook offset", "self.tag_info = (\"field[]\", None, None) def createFields(self): yield String(self, \"tag\",", "u\"audio/x-cda\", u\"Microsoft Windows audio CD file (cda)\", \".cda\"), \"AVI \":", "AT logonet.com.pl) for its CDA file format information \"\"\" from", "\"icon_file\", self[\"size\"].value, parser_class=IcoFile) class ChunkACON(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'anih':", "self.TAG_INFO: self.tag_info = self.TAG_INFO[tag] if tag == \"LIST\": subtag =", "in interleaved video)\") yield UInt32(self, \"nb_stream\", \"Number of streams\") yield", "parseAVIStreamFormat, \"Stream format\"), \"avih\": (\"avi_hdr\", parseAviHeader, \"AVI header\"), \"idx1\": (\"index\",", "yield UInt32(self, \"sample_size\", \"Size of samples\") yield UInt16(self, \"left\", \"Destination", "\"Audio format: Subformat id\") def parseAVIStreamFormat(self): size = self[\"size\"].value strtype", "yield UInt32(self, \"channel_mask\", \"Audio format: channels placement bitmask\") yield UInt32(self,", "used in CD audio (.cda) file \"\"\" def createFields(self): yield", "def createDescription(self): tag = self[\"tag\"].display return u\"Chunk (tag %s)\" %", "\"IDIT\": (\"datetime\", parseText, \"Date time\"), # TODO: Todo: see below", "yield Enum(field, video_fourcc_name, lambda text: text.upper()) else: yield field yield", "'anih': (\"anim_hdr\", parseAnimationHeader, \"Animation header\"), 'seq ': (\"anim_seq\", parseAnimationSequence, \"Animation", "\"codec\", \"Audio format: Codec id\"), audio_codec_name) yield UInt16(self, \"channel\", \"Audio", "%s)\" % tag class ChunkAVI(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ \"strh\":", "while 8 < (self.size - self.current_size)/8: field = self.__class__(self, \"field[]\")", "yield Enum(UInt16(self, \"codec\", \"Audio format: Codec id\"), audio_codec_name) yield UInt16(self,", "\"AVI header\"), \"idx1\": (\"index\", parseIndex, \"Stream index\"), \"dmlh\": (\"odml_hdr\", parseODML,", "if \"total_frame\" in header and header[\"total_frame\"].value: delta = timedelta(seconds=float(header[\"total_frame\"].value) *", "\"height\", \"Height in pixel\") yield UInt32(self, \"scale\") yield UInt32(self, \"rate\")", "createFields(self): yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"size\",", "size): yield Enum(UInt16(self, \"codec\", \"Audio format: Codec id\"), audio_codec_name) yield", "= self[\"tag\"].display return u\"Chunk (tag %s)\" % tag class ChunkAVI(Chunk):", "frame\", # \"dc\": \"Compressed video frame\", # \"wb\": \"Audio data\",", "size = self[\"size\"].value strtype = self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER = { \"vids\":", "Choose chunk type depending on file type try: chunk_cls =", "yield UInt16(self, \"panes\", \"Video format: Panes\") yield UInt16(self, \"depth\", \"Video", "40), \"auds\": (parseAudioFormat, 16) } handler = parseRawFormat if strtype", "def createFields(self): yield UInt8(self, \"frame\") yield UInt8(self, \"second\") yield UInt8(self,", "size\") yield UInt32(self, \"xpels_meter\", \"Video format: XPelsPerMeter\") yield UInt32(self, \"ypels_meter\",", "chunk_cls(self, \"chunk[]\") if not self.eof: yield RawBytes(self, \"padding[]\", (self.size-self.current_size)/8) def", "tag in self.TAG_INFO: self.tag_info = self.TAG_INFO[tag] if tag == \"LIST\":", "parseAVIStreamHeader(self): if self[\"size\"].value != 56: raise ParserError(\"Invalid stream header size\")", "if 0 < padding: yield NullBytes(self, \"padding[]\", padding) class AVIIndexEntry(FieldSet):", "RawBytes(self, \"raw_content\", self[\"size\"].value) padding = self.seekBit(self._size) if padding: yield padding", "\"\"\" yield UInt16(self, \"cda_version\", \"CD file version (currently 1)\") yield", "self.tag_info = self.TAG_INFO[tag] if tag == \"LIST\": subtag = self[\"subtag\"].value", "RedBook(self, \"rb_offset\", \"Track offset (Red-book format)\") yield RedBook(self, \"rb_length\", \"Track", "is edited by RiffFile.validate() \"LIST\": (\"list[]\", None, \"Sub-field list\"), \"JUNK\":", "UInt32(self, \"length\", \"Stream length (unit: rate/scale)\") yield UInt32(self, \"buf_size\", \"Suggested", "not in (16, 18): self.warning(\"Format with size of %s bytes", "UInt16(self, \"bit_per_sample\", \"Bits per sample\") def parseWAVFact(self): yield UInt32(self, \"nb_sample\",", "== \"vids\": yield Enum(field, video_fourcc_name, lambda text: text.upper()) else: yield", "while not self.eof: yield UInt32(self, \"icon[]\") def formatJiffie(field): sec =", "movie data\") yield UInt32(self, \"length\") def parseIndex(self): while not self.eof:", "'fmt ': (\"cdda\", parseCDDA, \"CD audio informations\"), }) class ChunkWAVE(Chunk):", "\"flags\", \"Stream flags\") yield UInt16(self, \"priority\", \"Stream priority\") yield String(self,", "scale\") yield UInt32(self, \"rate\", \"Divide by scale to give frame", "\\\"WAVE\\\", ...)\", charset=\"ASCII\") # Choose chunk type depending on file", "150 (from RB offset) HSG length = (minute*60 + second)*75", "yield UInt32(self, \"flags\", \"Stream flags\") yield UInt16(self, \"priority\", \"Stream priority\")", "size >= 28: # and self[\"a_channel\"].value > 2 yield UInt16(self,", "self._size = (8 + alignValue(self[\"size\"].value, 2)) * 8 tag =", "rectangle (right)\") yield UInt16(self, \"bottom\", \"Destination rectangle (bottom)\") class RedBook(FieldSet):", "\"Audio format: Bits per sample\") if size >= 18: yield", "2 yield UInt16(self, \"reserved\", \"Audio format: \") yield UInt32(self, \"channel_mask\",", "yield Enum(UInt16(self, \"codec\", \"Audio codec\"), audio_codec_name) yield UInt16(self, \"nb_channel\", \"Number", "TAG_INFO = { # This dictionnary is edited by RiffFile.validate()", "UInt32(self, \"nb_sample\", \"Number of samples in audio stream\") def parseAviHeader(self):", "padding) class AVIIndexEntry(FieldSet): size = 16*8 def createFields(self): yield String(self,", "\"\"\" HSG address format: number of 1/75 second HSG offset", "(\"headers\", \"Headers\"), \"strl\": (\"stream[]\", \"Stream header list\"), \"movi\": (\"movie\", \"Movie", "parseAVIStreamHeader, \"Stream header\"), \"strf\": (\"stream_fmt\", parseAVIStreamFormat, \"Stream format\"), \"avih\": (\"avi_hdr\",", "creation of WAV parser by <NAME> * 2005-06-08: creation of", "AVI, WAV and CDA parsers into RIFF parser * 2006-08-03:", "Channels\") yield UInt32(self, \"sample_rate\", \"Audio format: Sample rate\") yield UInt32(self,", "yield UInt16(self, \"ext_size\", \"Audio format: Size of extra information\") if", "\"padding[]\", \"Padding\") else: handler = self.tag_info[1] if handler: for field", "info[1]) self._name = self.tag_info[0] self._description = self.tag_info[2] else: self.tag_info =", "\") yield UInt32(self, \"channel_mask\", \"Audio format: channels placement bitmask\") yield", "second\") yield UInt32(self, \"byte_per_sec\", \"Average byte per second\") yield UInt16(self,", "UInt8(self, \"frame\") yield UInt8(self, \"second\") yield UInt8(self, \"minute\") yield PaddingBytes(self,", "(8 + alignValue(self[\"size\"].value, 2)) * 8 tag = self[\"tag\"].value if", "yield UInt32(self, \"flags\") yield UInt32(self, \"start\", \"Offset from start of", "\"start\") yield UInt32(self, \"length\") def parseODML(self): yield UInt32(self, \"total_frame\", \"Real", "if tag in self.TAG_INFO: self.tag_info = self.TAG_INFO[tag] if tag ==", "yield UInt32(self, \"init_frames\", \"InitialFrames\") yield UInt32(self, \"scale\", \"Time scale\") yield", "# TODO: Todo: see below # \"strn\": Stream description #", "give frame rate\") yield UInt32(self, \"start\", \"Stream start time (unit:", "yield UInt32(self, \"height\", \"Height in pixel\") yield UInt32(self, \"scale\") yield", "UInt16(self, \"ext_size\", \"Audio format: Size of extra information\") if size", "yield UInt32(self, \"cx\") yield UInt32(self, \"cy\") yield UInt32(self, \"bit_count\") yield", "yield String(self, \"language\", 2, \"Stream language\", charset=\"ASCII\", strip=\"\\0\") yield UInt32(self,", "class ChunkACON(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'anih': (\"anim_hdr\", parseAnimationHeader, \"Animation", "\"Audio stream data\"), }) def parseAnimationHeader(self): yield UInt32(self, \"hdr_size\", \"Size", "yield UInt32(self, \"height\", \"Video format: Height\") yield UInt16(self, \"panes\", \"Video", "\"init_frame\", \"Initial frame (used in interleaved video)\") yield UInt32(self, \"nb_stream\",", "# and self[\"a_channel\"].value > 2 yield UInt16(self, \"reserved\", \"Audio format:", "charset=\"ASCII\") # Choose chunk type depending on file type try:", "audio channel\") yield UInt32(self, \"sample_per_sec\", \"Sample per second\") yield UInt32(self,", "{ \"WAVE\": (ChunkWAVE, u\"audio/x-wav\", u\"Microsoft WAVE audio\", \".wav\"), \"CDDA\": (ChunkCDDA,", "\"Suggested buffer size\") yield UInt32(self, \"width\", \"Width in pixel\") yield", "Image size\") yield UInt32(self, \"xpels_meter\", \"Video format: XPelsPerMeter\") yield UInt32(self,", "parseIndex(self): while not self.eof: yield AVIIndexEntry(self, \"index[]\") class Chunk(FieldSet): TAG_INFO", "\"second\") yield UInt8(self, \"minute\") yield PaddingBytes(self, \"notused\", 1) def formatSerialNumber(field):", "parseAnimationHeader, \"Animation header\"), 'seq ': (\"anim_seq\", parseAnimationSequence, \"Animation sequence\"), 'rate':", "serial number. Eg. 0x00085C48 => \"0008-5C48\" \"\"\" sn = field.value", "= (self[\"filesize\"].value + 8) * 8 return min(size, self.stream.size) def", "<NAME> Changelog: * 2007-03-30: support ACON (animated icons) * 2006-08-08:", "subtag in self.subtag_info: info = self.subtag_info[subtag] self.tag_info = (info[0], None,", "\"INFO\": (\"info\", \"File informations\"), \"hdrl\": (\"headers\", \"Headers\"), \"strl\": (\"stream[]\", \"Stream", "HSG offset = (minute*60 + second)*75 + frame + 150", "\", 8*8), (\"CDDAfmt \", 8*8), (\"ACONanih\", 8*8), ), \"description\": \"Microsoft", "\"IENG\": (\"author\", parseText, \"Author\"), \"ICRD\": (\"creation_date\", parseText, \"Creation date\"), \"ISFT\":", "} def __init__(self, *args, **kw): FieldSet.__init__(self, *args, **kw) self._size =", "'data': (\"audio_data\", None, \"Audio stream data\"), }) def parseAnimationHeader(self): yield", "\"CDDA\": (ChunkCDDA, u\"audio/x-cda\", u\"Microsoft Windows audio CD file (cda)\", \".cda\"),", "regex \"RIFF.{4}(WAVE|CDDA|AVI )\" \"magic\": ( (\"AVI LIST\", 8*8), (\"WAVEfmt \",", "yield NullBits(self, \"reserved[]\", 2) yield Bit(self, \"is_interleaved\") yield NullBits(self, \"reserved[]\",", "self[\"filesize\"].value*8+8: yield chunk_cls(self, \"chunk[]\") if not self.eof: yield RawBytes(self, \"padding[]\",", "lib.hachoir_core.text_handler import filesizeHandler, textHandler from lib.hachoir_parser.video.fourcc import audio_codec_name, video_fourcc_name from", "Codec id\"), audio_codec_name) yield UInt16(self, \"channel\", \"Audio format: Channels\") yield", "\"Audio format: Size of extra information\") if size >= 28:", "def parseIndex(self): while not self.eof: yield AVIIndexEntry(self, \"index[]\") class Chunk(FieldSet):", "depending on file type try: chunk_cls = self.VALID_TYPES[self[\"type\"].value][0] except KeyError:", "index\"), \"dmlh\": (\"odml_hdr\", parseODML, \"ODML header\"), }) class ChunkCDDA(Chunk): TAG_INFO", "class RedBook(FieldSet): \"\"\" RedBook offset parser, used in CD audio", "Enum(UInt16(self, \"codec\", \"Audio format: Codec id\"), audio_codec_name) yield UInt16(self, \"channel\",", "self.stream.size) def createFilenameSuffix(self): try: return self.VALID_TYPES[self[\"type\"].value][3] except KeyError: return \".riff\"", "HSG length = (minute*60 + second)*75 + frame (from RB", "float(field.value) / 60 return humanDuration(timedelta(seconds=sec)) def parseAnimationRate(self): while not self.eof:", "yield NullBits(self, \"reserved[]\", 14) yield UInt32(self, \"total_frame\", \"Total number of", "yield padding def createDescription(self): tag = self[\"tag\"].display return u\"Chunk (tag", "(\"field[]\", None, None) def createFields(self): yield String(self, \"tag\", 4, \"Tag\",", "except KeyError: return None def createDescription(self): tag = self[\"type\"].value if", "CD audio (.cda) file \"\"\" def createFields(self): yield UInt8(self, \"frame\")", "\"bit_rate\", \"Audio format: Bit rate\") yield UInt16(self, \"block_align\", \"Audio format:", "\"wb\": \"Audio data\", # \"pc\": \"Palette change\" } subtag_info =", "parser, able to parse: * AVI video container * WAV", "(parseVideoFormat, 40), \"auds\": (parseAudioFormat, 16) } handler = parseRawFormat if", "\"Stream start time (unit: rate/scale)\") yield UInt32(self, \"length\", \"Stream length", "return \"Unknown RIFF content type\" return True def createFields(self): yield", "by <NAME> * 2005-06-08: creation of AVI parser by <NAME>", "sequence\"), 'icon': (\"icon[]\", parseIcon, \"Icon\"), }) class RiffFile(Parser): PARSER_TAGS =", "character code\", charset=\"ASCII\") field = String(self, \"fourcc\", 4, \"Stream four", "frame (used in interleaved video)\") yield UInt32(self, \"nb_stream\", \"Number of", "fps\" % (1000000.0 / microsec) if \"total_frame\" in header and", "yield NullBytes(self, \"padding[]\", padding) class AVIIndexEntry(FieldSet): size = 16*8 def", "self.TAG_INFO[tag] if tag == \"LIST\": subtag = self[\"subtag\"].value if subtag", "u\"image/x-ani\", u\"Microsoft Windows animated cursor\", \".ani\"), } endian = LITTLE_ENDIAN", "yield chunk_cls(self, \"chunk[]\") if not self.eof: yield RawBytes(self, \"padding[]\", (self.size-self.current_size)/8)", "\"nb_frame\", \"Number of unique Icons in this cursor\") yield UInt32(self,", "strip=\" \\0\", truncate=\"\\0\", charset=\"ISO-8859-1\") def parseRawFormat(self, size): yield RawBytes(self, \"raw_format\",", "\" + humanDuration(delta) return desc else: try: return self.VALID_TYPES[tag][2] except", "None def createDescription(self): tag = self[\"type\"].value if tag == \"AVI", "yield UInt32(self, \"xpels_meter\", \"Video format: XPelsPerMeter\") yield UInt32(self, \"ypels_meter\", \"Video", "padding def createDescription(self): tag = self[\"tag\"].display return u\"Chunk (tag %s)\"", "of streams\") yield UInt32(self, \"sug_buf_size\", \"Suggested buffer size\") yield UInt32(self,", "header and header[\"total_frame\"].value: delta = timedelta(seconds=float(header[\"total_frame\"].value) * microsec) desc +=", "format: Height\") yield UInt16(self, \"panes\", \"Video format: Panes\") yield UInt16(self,", "yield UInt16(self, \"bit_per_sample\", \"Bits per sample\") def parseWAVFact(self): yield UInt32(self,", "animated cursor\", \".ani\"), } endian = LITTLE_ENDIAN def validate(self): if", "def parseAVIStreamFormat(self): size = self[\"size\"].value strtype = self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER =", "u\"Microsoft WAVE audio\", \".wav\"), \"CDDA\": (ChunkCDDA, u\"audio/x-cda\", u\"Microsoft Windows audio", "Bit(self, \"was_capture_file\") yield Bit(self, \"is_copyrighted\") yield NullBits(self, \"reserved[]\", 14) yield", "\"description\": \"Microsoft RIFF container\" } VALID_TYPES = { \"WAVE\": (ChunkWAVE,", "(\"stream[]\", \"Stream header list\"), \"movi\": (\"movie\", \"Movie stream\"), \"odml\": (\"odml\",", "code from ffmpeg library http://ffmpeg.mplayerhq.hu/ - Video for Windows Programmer's", "self.tag_info[1] while 8 < (self.size - self.current_size)/8: field = self.__class__(self,", "in handler(self, size): yield field def parseAVIStreamHeader(self): if self[\"size\"].value !=", "UInt32(self, \"buf_size\", \"Suggested buffer size\") yield UInt32(self, \"quality\", \"Stream quality\")", "= self.TAG_INFO[tag] if tag == \"LIST\": subtag = self[\"subtag\"].value if", "return None def createDescription(self): tag = self[\"type\"].value if tag ==", "': (\"format\", parseWAVFormat, \"Audio format\"), 'fact': (\"nb_sample\", parseWAVFact, \"Number of", "frame + 150 (from RB offset) HSG length = (minute*60", "\"channel\", \"Audio format: Channels\") yield UInt32(self, \"sample_rate\", \"Audio format: Sample", "yield UInt32(self, \"clr_important\", \"Video format: ClrImportant\") def parseAudioFormat(self, size): yield", "yield UInt32(self, \"cy\") yield UInt32(self, \"bit_count\") yield UInt32(self, \"planes\") yield", "ParserError, UInt8, UInt16, UInt32, Enum, Bit, NullBits, NullBytes, RawBytes, String,", "\"field[]\") yield field if (field.size/8) % 2 != 0: yield", "(field.size/8) % 2 != 0: yield UInt8(self, \"padding[]\", \"Padding\") else:", "in header and header[\"total_frame\"].value: delta = timedelta(seconds=float(header[\"total_frame\"].value) * microsec) desc", "libavformat source code from ffmpeg library http://ffmpeg.mplayerhq.hu/ - Video for", "(top)\") yield UInt16(self, \"right\", \"Destination rectangle (right)\") yield UInt16(self, \"bottom\",", "\"pc\": \"Palette change\" } subtag_info = { \"INFO\": (\"info\", \"File", "\"signature\", 4, \"AVI header (RIFF)\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"filesize\", \"File", "18: yield UInt16(self, \"ext_size\", \"Audio format: Size of extra information\")", "cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm Authors: * <NAME> * <NAME> * <NAME> Changelog:", "import timedelta def parseText(self): yield String(self, \"text\", self[\"size\"].value, strip=\" \\0\",", "(\\\"AVI \\\", \\\"WAVE\\\", ...)\", charset=\"ASCII\") # Choose chunk type depending", "else: yield RawBytes(self, \"raw_content\", self[\"size\"].value) padding = self.seekBit(self._size) if padding:", "String(self, \"fourcc\", 4, \"Stream four character code\", strip=\" \\0\", charset=\"ASCII\")", "class Chunk(FieldSet): TAG_INFO = { # This dictionnary is edited", "lib.hachoir_parser.video.fourcc import audio_codec_name, video_fourcc_name from lib.hachoir_parser.image.ico import IcoFile from datetime", "UInt16(self, \"depth\", \"Video format: Depth\") yield UInt32(self, \"tag1\", \"Video format:", "4, \"Stream type four character code\", charset=\"ASCII\") field = String(self,", "offset parser, used in CD audio (.cda) file \"\"\" def", "UInt32(self, \"jiffie_rate\", \"Default Jiffies (1/60th of a second) if rate", "u\"Microsoft Windows audio CD file (cda)\", \".cda\"), \"AVI \": (ChunkAVI,", "Parse all chunks up to filesize while self.current_size < self[\"filesize\"].value*8+8:", "\"Video format: Width\") yield UInt32(self, \"height\", \"Video format: Height\") yield", "frame (from RB length) \"\"\" yield UInt16(self, \"cda_version\", \"CD file", "< (self.size - self.current_size)/8: field = self.__class__(self, \"field[]\") yield field", "\"LIST\": (\"list[]\", None, \"Sub-field list\"), \"JUNK\": (\"junk[]\", None, \"Junk (padding)\"),", "None, info[1]) self._name = self.tag_info[0] self._description = self.tag_info[2] else: self.tag_info", "by <NAME> and <NAME> Thanks to: * <NAME> (wojtekka AT", "\"0008-5C48\" \"\"\" sn = field.value return \"%04X-%04X\" % (sn >>", "4 if 0 < padding: yield NullBytes(self, \"padding[]\", padding) class", "size): yield UInt32(self, \"video_size\", \"Video format: Size\") yield UInt32(self, \"width\",", "RiffFile(Parser): PARSER_TAGS = { \"id\": \"riff\", \"category\": \"container\", \"file_ext\": (\"avi\",", "NullBits(self, \"reserved[]\", 4) yield Bit(self, \"has_index\") yield Bit(self, \"must_use_index\") yield", "yield UInt32(self, \"img_size\", \"Video format: Image size\") yield UInt32(self, \"xpels_meter\",", "frames in the video\") yield UInt32(self, \"init_frame\", \"Initial frame (used", "\\0\", charset=\"ASCII\") if self[\"stream_type\"].value == \"vids\": yield Enum(field, video_fourcc_name, lambda", "offset) HSG length = (minute*60 + second)*75 + frame (from", "UInt8(self, \"second\") yield UInt8(self, \"minute\") yield PaddingBytes(self, \"notused\", 1) def", "\"length\") def parseIndex(self): while not self.eof: yield AVIIndexEntry(self, \"index[]\") class", "tag = self[\"tag\"].display return u\"Chunk (tag %s)\" % tag class", "yield UInt32(self, \"nb_frame\", \"Number of unique Icons in this cursor\")", "if size >= 28: # and self[\"a_channel\"].value > 2 yield", "in self: header = self[\"headers/avi_hdr\"] desc += \": %ux%u pixels\"", "\"id\": \"riff\", \"category\": \"container\", \"file_ext\": (\"avi\", \"cda\", \"wav\", \"ani\"), \"min_size\":", "= header[\"microsec_per_frame\"].value if microsec: desc += \", %.1f fps\" %", "audio CD file (cda)\", \".cda\"), \"AVI \": (ChunkAVI, u\"video/x-msvideo\", u\"Microsoft", "\"Comment\"), \"ICOP\": (\"copyright\", parseText, \"Copyright\"), \"IENG\": (\"author\", parseText, \"Author\"), \"ICRD\":", "(\"stream_fmt\", parseAVIStreamFormat, \"Stream format\"), \"avih\": (\"avi_hdr\", parseAviHeader, \"AVI header\"), \"idx1\":", "field yield UInt32(self, \"flags\", \"Stream flags\") yield UInt16(self, \"priority\", \"Stream", "(from RB offset) HSG length = (minute*60 + second)*75 +", "\".cda\"), \"AVI \": (ChunkAVI, u\"video/x-msvideo\", u\"Microsoft AVI video\", \".avi\"), \"ACON\":", "number of 1/75 second HSG offset = (minute*60 + second)*75", "self.warning(\"Format with size of %s bytes is not supported!\" %", "== \"LIST\": yield String(self, \"subtag\", 4, \"Sub-tag\", charset=\"ASCII\") handler =", "\", %.1f fps\" % (1000000.0 / microsec) if \"total_frame\" in", "CDA file Documents: - libavformat source code from ffmpeg library", "UInt32(self, \"height\", \"Video format: Height\") yield UInt16(self, \"panes\", \"Video format:", "import audio_codec_name, video_fourcc_name from lib.hachoir_parser.image.ico import IcoFile from datetime import", "import (FieldSet, ParserError, UInt8, UInt16, UInt32, Enum, Bit, NullBits, NullBytes,", "of OpenDML video\") padding = self[\"size\"].value - 4 if 0", "\"nb_stream\", \"Number of streams\") yield UInt32(self, \"sug_buf_size\", \"Suggested buffer size\")", "} handler = parseRawFormat if strtype in TYPE_HANDLER: info =", "Bit(self, \"is_copyrighted\") yield NullBits(self, \"reserved[]\", 14) yield UInt32(self, \"total_frame\", \"Total", "True def createFields(self): yield String(self, \"signature\", 4, \"AVI header (RIFF)\",", "<reponame>Branlala/docker-sickbeardfr # -*- coding: UTF-8 -*- \"\"\" RIFF parser, able", "= self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER = { \"vids\": (parseVideoFormat, 40), \"auds\": (parseAudioFormat,", "\"RIFF.{4}(WAVE|CDDA|AVI )\" \"magic\": ( (\"AVI LIST\", 8*8), (\"WAVEfmt \", 8*8),", "ClrUsed\") yield UInt32(self, \"clr_important\", \"Video format: ClrImportant\") def parseAudioFormat(self, size):", "UInt32(self, \"hdr_size\", \"Size of header (36 bytes)\") if self[\"hdr_size\"].value !=", "\"nb_channel\", \"Number of audio channel\") yield UInt32(self, \"sample_per_sec\", \"Sample per", "AVI video\", \".avi\"), \"ACON\": (ChunkACON, u\"image/x-ani\", u\"Microsoft Windows animated cursor\",", "priority\") yield String(self, \"language\", 2, \"Stream language\", charset=\"ASCII\", strip=\"\\0\") yield", "parseCDDA(self): \"\"\" HSG address format: number of 1/75 second HSG", "humanDuration from lib.hachoir_core.endian import LITTLE_ENDIAN from lib.hachoir_core.text_handler import filesizeHandler, textHandler", "\"JUNK\": (\"junk[]\", None, \"Junk (padding)\"), # Metadata \"INAM\": (\"title\", parseText,", "by scale to give frame rate\") yield UInt32(self, \"start\", \"Stream", "AVI parser by <NAME> and <NAME> Thanks to: * <NAME>", "String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"size\", \"Size\")) if", "interleaved video)\") yield UInt32(self, \"nb_stream\", \"Number of streams\") yield UInt32(self,", "String(self, \"subtag\", 4, \"Sub-tag\", charset=\"ASCII\") handler = self.tag_info[1] while 8", "self[\"size\"].value: return if self[\"tag\"].value == \"LIST\": yield String(self, \"subtag\", 4,", "padding = self.seekBit(self._size) if padding: yield padding def createDescription(self): tag", "= Chunk.TAG_INFO.copy() TAG_INFO.update({ 'anih': (\"anim_hdr\", parseAnimationHeader, \"Animation header\"), 'seq ':", "2005-06-08: creation of AVI parser by <NAME> and <NAME> Thanks", "lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, ParserError, UInt8, UInt16,", "frame of OpenDML video\") padding = self[\"size\"].value - 4 if", "(Red-book format)\") yield RedBook(self, \"rb_length\", \"Track length (Red-book format)\") def", "*args, **kw) self._size = (8 + alignValue(self[\"size\"].value, 2)) * 8", "\"reserved[]\", 2) yield Bit(self, \"trust_cktype\") yield NullBits(self, \"reserved[]\", 4) yield", "\"Video format: ClrImportant\") def parseAudioFormat(self, size): yield Enum(UInt16(self, \"codec\", \"Audio", "1/75 second HSG offset = (minute*60 + second)*75 + frame", "align\") yield UInt16(self, \"bit_per_sample\", \"Bits per sample\") def parseWAVFact(self): yield", "= info[0] for field in handler(self, size): yield field def", "self.current_size)/8: field = self.__class__(self, \"field[]\") yield field if (field.size/8) %", "in this cursor\") yield UInt32(self, \"nb_step\", \"Number of Blits before", "* 2006-08-03: creation of CDA parser by <NAME> * 2005-06-21:", "UInt32(self, \"flags\") yield UInt32(self, \"start\", \"Offset from start of movie", "description # TWOCC code, movie/field[]/tag.value[2:4]: # \"db\": \"Uncompressed video frame\",", "yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield UInt32(self, \"flags\") yield", "self[\"a_channel\"].value > 2 yield UInt16(self, \"reserved\", \"Audio format: \") yield", "self.eof: yield textHandler(UInt32(self, \"rate[]\"), formatJiffie) def parseIcon(self): yield SubFile(self, \"icon_file\",", "\"Destination rectangle (right)\") yield UInt16(self, \"bottom\", \"Destination rectangle (bottom)\") class", "Stream description # TWOCC code, movie/field[]/tag.value[2:4]: # \"db\": \"Uncompressed video", "* CDA file Documents: - libavformat source code from ffmpeg", "parseIcon, \"Icon\"), }) class RiffFile(Parser): PARSER_TAGS = { \"id\": \"riff\",", "ChunkAVI(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ \"strh\": (\"stream_hdr\", parseAVIStreamHeader, \"Stream header\"),", "\"Producer\"), \"IDIT\": (\"datetime\", parseText, \"Date time\"), # TODO: Todo: see", "UInt32(self, \"rate\", \"Divide by scale to give frame rate\") yield", "except KeyError: chunk_cls = Chunk # Parse all chunks up", "= self[\"size\"].value strtype = self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER = { \"vids\": (parseVideoFormat,", "AVI video\" if \"headers/avi_hdr\" in self: header = self[\"headers/avi_hdr\"] desc", "\"LIST\": yield String(self, \"subtag\", 4, \"Sub-tag\", charset=\"ASCII\") handler = self.tag_info[1]", "length) \"\"\" yield UInt16(self, \"cda_version\", \"CD file version (currently 1)\")", "size\")) yield String(self, \"type\", 4, \"Content type (\\\"AVI \\\", \\\"WAVE\\\",", "format: Block align\") if size >= 16: yield UInt16(self, \"bits_per_sample\",", "in TYPE_HANDLER: info = TYPE_HANDLER[strtype] if info[1] <= size: handler", "list\"), \"JUNK\": (\"junk[]\", None, \"Junk (padding)\"), # Metadata \"INAM\": (\"title\",", "if strtype in TYPE_HANDLER: info = TYPE_HANDLER[strtype] if info[1] <=", "NullBits, NullBytes, RawBytes, String, PaddingBytes, SubFile) from lib.hachoir_core.tools import alignValue,", "yield UInt32(self, \"start\", \"Stream start time (unit: rate/scale)\") yield UInt32(self,", "of frames in the video\") yield UInt32(self, \"init_frame\", \"Initial frame", "16) } handler = parseRawFormat if strtype in TYPE_HANDLER: info", "TYPE_HANDLER: info = TYPE_HANDLER[strtype] if info[1] <= size: handler =", "yield Bit(self, \"is_copyrighted\") yield NullBits(self, \"reserved[]\", 14) yield UInt32(self, \"total_frame\",", "four character code\", charset=\"ASCII\") field = String(self, \"fourcc\", 4, \"Stream", "def parseAudioFormat(self, size): yield Enum(UInt16(self, \"codec\", \"Audio format: Codec id\"),", "NullBits(self, \"reserved[]\", 14) yield UInt32(self, \"total_frame\", \"Total number of frames", "align\") if size >= 16: yield UInt16(self, \"bits_per_sample\", \"Audio format:", "from lib.hachoir_parser.video.fourcc import audio_codec_name, video_fourcc_name from lib.hachoir_parser.image.ico import IcoFile from", "self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER = { \"vids\": (parseVideoFormat, 40), \"auds\": (parseAudioFormat, 16)", "\"Video format: Panes\") yield UInt16(self, \"depth\", \"Video format: Depth\") yield", "RIFF container\" def createContentSize(self): size = (self[\"filesize\"].value + 8) *", "in (16, 18): self.warning(\"Format with size of %s bytes is", "\"hsg_length\", \"Track length (HSG format)\") yield RedBook(self, \"rb_offset\", \"Track offset", "} VALID_TYPES = { \"WAVE\": (ChunkWAVE, u\"audio/x-wav\", u\"Microsoft WAVE audio\",", "\"Average byte per second\") yield UInt16(self, \"block_align\", \"Block align\") yield", "\"nb_sample\", \"Number of samples in audio stream\") def parseAviHeader(self): yield", "UInt16(self, \"block_align\", \"Audio format: Block align\") if size >= 16:", "start of movie data\") yield UInt32(self, \"length\") def parseIndex(self): while", "address format: number of 1/75 second HSG offset = (minute*60", "None, \"Audio stream data\"), }) def parseAnimationHeader(self): yield UInt32(self, \"hdr_size\",", "logonet.com.pl) for its CDA file format information \"\"\" from lib.hachoir_parser", "format: Bit rate\") yield UInt16(self, \"block_align\", \"Audio format: Block align\")", "self[\"size\"].value) padding = self.seekBit(self._size) if padding: yield padding def createDescription(self):", "animation cycles\") yield UInt32(self, \"cx\") yield UInt32(self, \"cy\") yield UInt32(self,", "yield UInt32(self, \"buf_size\", \"Suggested buffer size\") yield UInt32(self, \"quality\", \"Stream", "container\" def createContentSize(self): size = (self[\"filesize\"].value + 8) * 8", "yield UInt16(self, \"bits_per_sample\", \"Audio format: Bits per sample\") if size", "LIST\", 8*8), (\"WAVEfmt \", 8*8), (\"CDDAfmt \", 8*8), (\"ACONanih\", 8*8),", "date\"), \"ISFT\": (\"producer\", parseText, \"Producer\"), \"IDIT\": (\"datetime\", parseText, \"Date time\"),", "\"Movie stream\"), \"odml\": (\"odml\", \"ODML\"), } def __init__(self, *args, **kw):", "\"subtag\", 4, \"Sub-tag\", charset=\"ASCII\") handler = self.tag_info[1] while 8 <", "size): yield RawBytes(self, \"raw_format\", size) def parseVideoFormat(self, size): yield UInt32(self,", "if size not in (16, 18): self.warning(\"Format with size of", "on file type try: chunk_cls = self.VALID_TYPES[self[\"type\"].value][0] except KeyError: chunk_cls", "\"Audio format: Codec id\"), audio_codec_name) yield UInt16(self, \"channel\", \"Audio format:", "* <NAME> * <NAME> Changelog: * 2007-03-30: support ACON (animated", "(left)\") yield UInt16(self, \"top\", \"Destination rectangle (top)\") yield UInt16(self, \"right\",", "UInt32(self, \"icon[]\") def formatJiffie(field): sec = float(field.value) / 60 return", "filesizeHandler, textHandler from lib.hachoir_parser.video.fourcc import audio_codec_name, video_fourcc_name from lib.hachoir_parser.image.ico import", "\"Video format: Tag1\") yield UInt32(self, \"img_size\", \"Video format: Image size\")", "= parseRawFormat if strtype in TYPE_HANDLER: info = TYPE_HANDLER[strtype] if", "UInt32(self, \"init_frames\", \"InitialFrames\") yield UInt32(self, \"scale\", \"Time scale\") yield UInt32(self,", "parseText, \"Producer\"), \"IDIT\": (\"datetime\", parseText, \"Date time\"), # TODO: Todo:", "(ChunkWAVE, u\"audio/x-wav\", u\"Microsoft WAVE audio\", \".wav\"), \"CDDA\": (ChunkCDDA, u\"audio/x-cda\", u\"Microsoft", "import LITTLE_ENDIAN from lib.hachoir_core.text_handler import filesizeHandler, textHandler from lib.hachoir_parser.video.fourcc import", "parseWAVFact(self): yield UInt32(self, \"nb_sample\", \"Number of samples in audio stream\")", "(ChunkAVI, u\"video/x-msvideo\", u\"Microsoft AVI video\", \".avi\"), \"ACON\": (ChunkACON, u\"image/x-ani\", u\"Microsoft", "UInt32(self, \"length\") def parseIndex(self): while not self.eof: yield AVIIndexEntry(self, \"index[]\")", "the video\") yield UInt32(self, \"init_frame\", \"Initial frame (used in interleaved", "desc else: try: return self.VALID_TYPES[tag][2] except KeyError: return u\"Microsoft RIFF", "subtag_info = { \"INFO\": (\"info\", \"File informations\"), \"hdrl\": (\"headers\", \"Headers\"),", "2006-08-03: creation of CDA parser by <NAME> * 2005-06-21: creation", "\"Audio format: Channels\") yield UInt32(self, \"sample_rate\", \"Audio format: Sample rate\")", "sn & 0xFFFF) def parseCDDA(self): \"\"\" HSG address format: number", "\"ISFT\": (\"producer\", parseText, \"Producer\"), \"IDIT\": (\"datetime\", parseText, \"Date time\"), #", "flags\") yield UInt16(self, \"priority\", \"Stream priority\") yield String(self, \"language\", 2,", "yield UInt32(self, \"total_frame\", \"Real number of frame of OpenDML video\")", "# \"db\": \"Uncompressed video frame\", # \"dc\": \"Compressed video frame\",", "return self.VALID_TYPES[self[\"type\"].value][1] except KeyError: return None def createDescription(self): tag =", "\"size\", \"Size\")) if not self[\"size\"].value: return if self[\"tag\"].value == \"LIST\":", "\"tag\", 4, \"Tag\", charset=\"ASCII\") yield UInt32(self, \"flags\") yield UInt32(self, \"start\",", "informations\"), }) class ChunkWAVE(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ':", "Bits per sample\") if size >= 18: yield UInt16(self, \"ext_size\",", "\"Stream flags\") yield UInt16(self, \"priority\", \"Stream priority\") yield String(self, \"language\",", "yield Bit(self, \"must_use_index\") yield NullBits(self, \"reserved[]\", 2) yield Bit(self, \"is_interleaved\")", "= (8 + alignValue(self[\"size\"].value, 2)) * 8 tag = self[\"tag\"].value", "* 8 return min(size, self.stream.size) def createFilenameSuffix(self): try: return self.VALID_TYPES[self[\"type\"].value][3]", "yield field if (field.size/8) % 2 != 0: yield UInt8(self,", "parseText, \"Artist\"), \"ICMT\": (\"comment\", parseText, \"Comment\"), \"ICOP\": (\"copyright\", parseText, \"Copyright\"),", "XPelsPerMeter\") yield UInt32(self, \"ypels_meter\", \"Video format: YPelsPerMeter\") yield UInt32(self, \"clr_used\",", "Panes\") yield UInt16(self, \"depth\", \"Video format: Depth\") yield UInt32(self, \"tag1\",", "\"block_align\", \"Audio format: Block align\") if size >= 16: yield", "(unit: rate/scale)\") yield UInt32(self, \"buf_size\", \"Suggested buffer size\") yield UInt32(self,", "\"frame\") yield UInt8(self, \"second\") yield UInt8(self, \"minute\") yield PaddingBytes(self, \"notused\",", "= field.value return \"%04X-%04X\" % (sn >> 16, sn &", "desc += \": %ux%u pixels\" % (header[\"width\"].value, header[\"height\"].value) microsec =", "(header[\"width\"].value, header[\"height\"].value) microsec = header[\"microsec_per_frame\"].value if microsec: desc += \",", "if \"headers/avi_hdr\" in self: header = self[\"headers/avi_hdr\"] desc += \":", "Metadata \"INAM\": (\"title\", parseText, \"Document title\"), \"IART\": (\"artist\", parseText, \"Artist\"),", "UInt16(self, \"priority\", \"Stream priority\") yield String(self, \"language\", 2, \"Stream language\",", "signature\" if self[\"type\"].value not in self.VALID_TYPES: return \"Unknown RIFF content", "yield UInt32(self, \"start\", \"Offset from start of movie data\") yield", "of header (36 bytes)\") if self[\"hdr_size\"].value != 36: self.warning(\"Animation header", "\"cda\", \"wav\", \"ani\"), \"min_size\": 16*8, \"mime\": (u\"video/x-msvideo\", u\"audio/x-wav\", u\"audio/x-cda\"), #", "(\"artist\", parseText, \"Artist\"), \"ICMT\": (\"comment\", parseText, \"Comment\"), \"ICOP\": (\"copyright\", parseText,", "ParserError(\"Invalid stream header size\") yield String(self, \"stream_type\", 4, \"Stream type", "\"cy\") yield UInt32(self, \"bit_count\") yield UInt32(self, \"planes\") yield UInt32(self, \"jiffie_rate\",", "self[\"size\"].value strtype = self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER = { \"vids\": (parseVideoFormat, 40),", "\"Stream header list\"), \"movi\": (\"movie\", \"Movie stream\"), \"odml\": (\"odml\", \"ODML\"),", "content type\" return True def createFields(self): yield String(self, \"signature\", 4,", "yield UInt32(self, \"nb_sample\", \"Number of samples in audio stream\") def", "\"container\", \"file_ext\": (\"avi\", \"cda\", \"wav\", \"ani\"), \"min_size\": 16*8, \"mime\": (u\"video/x-msvideo\",", "What is an animated cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm Authors: * <NAME> *", "character code\", strip=\" \\0\", charset=\"ASCII\") if self[\"stream_type\"].value == \"vids\": yield", "\\\", \\\"WAVE\\\", ...)\", charset=\"ASCII\") # Choose chunk type depending on", "\"total_frame\", \"Total number of frames in the video\") yield UInt32(self,", "self.VALID_TYPES[tag][2] except KeyError: return u\"Microsoft RIFF container\" def createContentSize(self): size", "humanDuration(delta) return desc else: try: return self.VALID_TYPES[tag][2] except KeyError: return", "microsec: desc += \", %.1f fps\" % (1000000.0 / microsec)", "yield UInt16(self, \"block_align\", \"Block align\") yield UInt16(self, \"bit_per_sample\", \"Bits per", "(1000000.0 / microsec) if \"total_frame\" in header and header[\"total_frame\"].value: delta", "import filesizeHandler, textHandler from lib.hachoir_parser.video.fourcc import audio_codec_name, video_fourcc_name from lib.hachoir_parser.image.ico", "and header[\"total_frame\"].value: delta = timedelta(seconds=float(header[\"total_frame\"].value) * microsec) desc += \",", "(\"stream_hdr\", parseAVIStreamHeader, \"Stream header\"), \"strf\": (\"stream_fmt\", parseAVIStreamFormat, \"Stream format\"), \"avih\":", "< padding: yield NullBytes(self, \"padding[]\", padding) class AVIIndexEntry(FieldSet): size =", "\"Tag\", charset=\"ASCII\") yield UInt32(self, \"flags\") yield UInt32(self, \"start\", \"Offset from", "for its CDA file format information \"\"\" from lib.hachoir_parser import", "chunks up to filesize while self.current_size < self[\"filesize\"].value*8+8: yield chunk_cls(self,", "\"Track length (Red-book format)\") def parseWAVFormat(self): size = self[\"size\"].value if", "= self.subtag_info[subtag] self.tag_info = (info[0], None, info[1]) self._name = self.tag_info[0]", "UInt32(self, \"video_size\", \"Video format: Size\") yield UInt32(self, \"width\", \"Video format:", "31) def parseAnimationSequence(self): while not self.eof: yield UInt32(self, \"icon[]\") def", "chunk not present\") yield Bit(self, \"is_icon\") yield NullBits(self, \"padding\", 31)", "handler(self, size): yield field def parseAVIStreamHeader(self): if self[\"size\"].value != 56:", "format: Tag1\") yield UInt32(self, \"img_size\", \"Video format: Image size\") yield", "2)) * 8 tag = self[\"tag\"].value if tag in self.TAG_INFO:", "(%s)\" % self[\"size\"].value) yield UInt32(self, \"nb_frame\", \"Number of unique Icons", "\"dmlh\": (\"odml_hdr\", parseODML, \"ODML header\"), }) class ChunkCDDA(Chunk): TAG_INFO =", "\"must_use_index\") yield NullBits(self, \"reserved[]\", 2) yield Bit(self, \"is_interleaved\") yield NullBits(self,", "+ frame (from RB length) \"\"\" yield UInt16(self, \"cda_version\", \"CD", "yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"size\", \"Size\"))", "format: Subformat id\") def parseAVIStreamFormat(self): size = self[\"size\"].value strtype =", "0: yield UInt8(self, \"padding[]\", \"Padding\") else: handler = self.tag_info[1] if", "if self.stream.readBytes(0, 4) != \"RIFF\": return \"Wrong signature\" if self[\"type\"].value", "strtype in TYPE_HANDLER: info = TYPE_HANDLER[strtype] if info[1] <= size:", "\"chunk[]\") if not self.eof: yield RawBytes(self, \"padding[]\", (self.size-self.current_size)/8) def createMimeType(self):", "yield UInt16(self, \"bottom\", \"Destination rectangle (bottom)\") class RedBook(FieldSet): \"\"\" RedBook", "raise ParserError(\"Invalid stream header size\") yield String(self, \"stream_type\", 4, \"Stream", "of 1/75 second HSG offset = (minute*60 + second)*75 +", "sample\") if size >= 18: yield UInt16(self, \"ext_size\", \"Audio format:", "with unknown size (%s)\" % self[\"size\"].value) yield UInt32(self, \"nb_frame\", \"Number", "parseText, \"Document title\"), \"IART\": (\"artist\", parseText, \"Artist\"), \"ICMT\": (\"comment\", parseText,", "data\") yield UInt32(self, \"length\") def parseIndex(self): while not self.eof: yield", "sequence\"), 'rate': (\"anim_rate\", parseAnimationRate, \"Animation sequence\"), 'icon': (\"icon[]\", parseIcon, \"Icon\"),", "+ second)*75 + frame (from RB length) \"\"\" yield UInt16(self,", "\"raw_content\", self[\"size\"].value) padding = self.seekBit(self._size) if padding: yield padding def", "parser, used in CD audio (.cda) file \"\"\" def createFields(self):", "\"Track offset (HSG format)\") yield UInt32(self, \"hsg_length\", \"Track length (HSG", "UInt8, UInt16, UInt32, Enum, Bit, NullBits, NullBytes, RawBytes, String, PaddingBytes,", "\"Stream quality\") yield UInt32(self, \"sample_size\", \"Size of samples\") yield UInt16(self,", "return min(size, self.stream.size) def createFilenameSuffix(self): try: return self.VALID_TYPES[self[\"type\"].value][3] except KeyError:", ">= 28: # and self[\"a_channel\"].value > 2 yield UInt16(self, \"reserved\",", "handler: for field in handler(self): yield field else: yield RawBytes(self,", "+ 150 (from RB offset) HSG length = (minute*60 +", "\"Video format: Size\") yield UInt32(self, \"width\", \"Video format: Width\") yield", "able to parse: * AVI video container * WAV audio", "\"Animation sequence\"), 'icon': (\"icon[]\", parseIcon, \"Icon\"), }) class RiffFile(Parser): PARSER_TAGS", "video\", \".avi\"), \"ACON\": (ChunkACON, u\"image/x-ani\", u\"Microsoft Windows animated cursor\", \".ani\"),", "in self.TAG_INFO: self.tag_info = self.TAG_INFO[tag] if tag == \"LIST\": subtag", "u\"audio/x-wav\", u\"Microsoft WAVE audio\", \".wav\"), \"CDDA\": (ChunkCDDA, u\"audio/x-cda\", u\"Microsoft Windows", "byte per second\") yield NullBytes(self, \"reserved\", 4) # Flags yield", "(\"format\", parseWAVFormat, \"Audio format\"), 'fact': (\"nb_sample\", parseWAVFact, \"Number of samples\"),", "\"Stream type four character code\", charset=\"ASCII\") field = String(self, \"fourcc\",", "format: Bits per sample\") if size >= 18: yield UInt16(self,", "not supported!\" % size) yield Enum(UInt16(self, \"codec\", \"Audio codec\"), audio_codec_name)", "Enum, Bit, NullBits, NullBytes, RawBytes, String, PaddingBytes, SubFile) from lib.hachoir_core.tools", "\"File size\")) yield String(self, \"type\", 4, \"Content type (\\\"AVI \\\",", "> 2 yield UInt16(self, \"reserved\", \"Audio format: \") yield UInt32(self,", "}) def parseAnimationHeader(self): yield UInt32(self, \"hdr_size\", \"Size of header (36", "UInt32(self, \"tag1\", \"Video format: Tag1\") yield UInt32(self, \"img_size\", \"Video format:", "RedBook offset parser, used in CD audio (.cda) file \"\"\"", "if not self[\"size\"].value: return if self[\"tag\"].value == \"LIST\": yield String(self,", "/ 60 return humanDuration(timedelta(seconds=sec)) def parseAnimationRate(self): while not self.eof: yield", "support ACON (animated icons) * 2006-08-08: merge AVI, WAV and", "present\") yield Bit(self, \"is_icon\") yield NullBits(self, \"padding\", 31) def parseAnimationSequence(self):", "yield SubFile(self, \"icon_file\", self[\"size\"].value, parser_class=IcoFile) class ChunkACON(Chunk): TAG_INFO = Chunk.TAG_INFO.copy()", "if padding: yield padding def createDescription(self): tag = self[\"tag\"].display return", "header (36 bytes)\") if self[\"hdr_size\"].value != 36: self.warning(\"Animation header with", "yield field def parseAVIStreamHeader(self): if self[\"size\"].value != 56: raise ParserError(\"Invalid", "(minute*60 + second)*75 + frame + 150 (from RB offset)", "return \"Wrong signature\" if self[\"type\"].value not in self.VALID_TYPES: return \"Unknown", "LITTLE_ENDIAN def validate(self): if self.stream.readBytes(0, 4) != \"RIFF\": return \"Wrong", "self[\"stream_type\"].value == \"vids\": yield Enum(field, video_fourcc_name, lambda text: text.upper()) else:", "\"\"\" def createFields(self): yield UInt8(self, \"frame\") yield UInt8(self, \"second\") yield", "\"height\", \"Video format: Height\") yield UInt16(self, \"panes\", \"Video format: Panes\")", "parseCDDA, \"CD audio informations\"), }) class ChunkWAVE(Chunk): TAG_INFO = Chunk.TAG_INFO.copy()", "(bottom)\") class RedBook(FieldSet): \"\"\" RedBook offset parser, used in CD", "\"Destination rectangle (left)\") yield UInt16(self, \"top\", \"Destination rectangle (top)\") yield", "\"avih\": (\"avi_hdr\", parseAviHeader, \"AVI header\"), \"idx1\": (\"index\", parseIndex, \"Stream index\"),", "\"Audio format: Sample rate\") yield UInt32(self, \"bit_rate\", \"Audio format: Bit", "type try: chunk_cls = self.VALID_TYPES[self[\"type\"].value][0] except KeyError: chunk_cls = Chunk", "rectangle (left)\") yield UInt16(self, \"top\", \"Destination rectangle (top)\") yield UInt16(self,", "parseText, \"Date time\"), # TODO: Todo: see below # \"strn\":", "= { \"vids\": (parseVideoFormat, 40), \"auds\": (parseAudioFormat, 16) } handler", "class ChunkAVI(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ \"strh\": (\"stream_hdr\", parseAVIStreamHeader, \"Stream", "Chunk.TAG_INFO.copy() TAG_INFO.update({ \"strh\": (\"stream_hdr\", parseAVIStreamHeader, \"Stream header\"), \"strf\": (\"stream_fmt\", parseAVIStreamFormat,", "video\" if \"headers/avi_hdr\" in self: header = self[\"headers/avi_hdr\"] desc +=", "= self.VALID_TYPES[self[\"type\"].value][0] except KeyError: chunk_cls = Chunk # Parse all", "AVIIndexEntry(FieldSet): size = 16*8 def createFields(self): yield String(self, \"tag\", 4,", "(\"junk[]\", None, \"Junk (padding)\"), # Metadata \"INAM\": (\"title\", parseText, \"Document", "self.tag_info = (info[0], None, info[1]) self._name = self.tag_info[0] self._description =", "format: Channels\") yield UInt32(self, \"sample_rate\", \"Audio format: Sample rate\") yield", "# \"pc\": \"Palette change\" } subtag_info = { \"INFO\": (\"info\",", "yield UInt16(self, \"left\", \"Destination rectangle (left)\") yield UInt16(self, \"top\", \"Destination", "yield String(self, \"stream_type\", 4, \"Stream type four character code\", charset=\"ASCII\")", "= LITTLE_ENDIAN def validate(self): if self.stream.readBytes(0, 4) != \"RIFF\": return", "code\", charset=\"ASCII\") field = String(self, \"fourcc\", 4, \"Stream four character", "validate(self): if self.stream.readBytes(0, 4) != \"RIFF\": return \"Wrong signature\" if", "formatJiffie(field): sec = float(field.value) / 60 return humanDuration(timedelta(seconds=sec)) def parseAnimationRate(self):", "video frame\", # \"wb\": \"Audio data\", # \"pc\": \"Palette change\"", "format)\") yield RedBook(self, \"rb_length\", \"Track length (Red-book format)\") def parseWAVFormat(self):", "not self[\"size\"].value: return if self[\"tag\"].value == \"LIST\": yield String(self, \"subtag\",", "yield UInt32(self, \"ypels_meter\", \"Video format: YPelsPerMeter\") yield UInt32(self, \"clr_used\", \"Video", "of movie data\") yield UInt32(self, \"length\") def parseIndex(self): while not", "yield Bit(self, \"trust_cktype\") yield NullBits(self, \"reserved[]\", 4) yield Bit(self, \"was_capture_file\")", "yield UInt32(self, \"length\", \"Stream length (unit: rate/scale)\") yield UInt32(self, \"buf_size\",", "\", 8*8), (\"ACONanih\", 8*8), ), \"description\": \"Microsoft RIFF container\" }", "createFields(self): yield String(self, \"signature\", 4, \"AVI header (RIFF)\", charset=\"ASCII\") yield", "Tag1\") yield UInt32(self, \"img_size\", \"Video format: Image size\") yield UInt32(self,", "sec = float(field.value) / 60 return humanDuration(timedelta(seconds=sec)) def parseAnimationRate(self): while", "if not self.eof: yield RawBytes(self, \"padding[]\", (self.size-self.current_size)/8) def createMimeType(self): try:", "in self.subtag_info: info = self.subtag_info[subtag] self.tag_info = (info[0], None, info[1])", "supported!\" % size) yield Enum(UInt16(self, \"codec\", \"Audio codec\"), audio_codec_name) yield", "RIFF parser * 2006-08-03: creation of CDA parser by <NAME>", "== \"AVI \": desc = u\"Microsoft AVI video\" if \"headers/avi_hdr\"", "RawBytes, String, PaddingBytes, SubFile) from lib.hachoir_core.tools import alignValue, humanDuration from", "self[\"size\"].value != 56: raise ParserError(\"Invalid stream header size\") yield String(self,", "UInt32(self, \"ypels_meter\", \"Video format: YPelsPerMeter\") yield UInt32(self, \"clr_used\", \"Video format:", "yield UInt32(self, \"nb_step\", \"Number of Blits before the animation cycles\")", "\"stream_type\", 4, \"Stream type four character code\", charset=\"ASCII\") field =", "samples in audio stream\") def parseAviHeader(self): yield UInt32(self, \"microsec_per_frame\", \"Microsecond", "FieldSet.__init__(self, *args, **kw) self._size = (8 + alignValue(self[\"size\"].value, 2)) *", "UInt32(self, \"bit_rate\", \"Audio format: Bit rate\") yield UInt16(self, \"block_align\", \"Audio", "String(self, \"stream_type\", 4, \"Stream type four character code\", charset=\"ASCII\") field", "return self.VALID_TYPES[tag][2] except KeyError: return u\"Microsoft RIFF container\" def createContentSize(self):", "parseAnimationRate, \"Animation sequence\"), 'icon': (\"icon[]\", parseIcon, \"Icon\"), }) class RiffFile(Parser):", "8*8), (\"CDDAfmt \", 8*8), (\"ACONanih\", 8*8), ), \"description\": \"Microsoft RIFF", "\"trust_cktype\") yield NullBits(self, \"reserved[]\", 4) yield Bit(self, \"was_capture_file\") yield Bit(self,", "language\", charset=\"ASCII\", strip=\"\\0\") yield UInt32(self, \"init_frames\", \"InitialFrames\") yield UInt32(self, \"scale\",", "samples\") yield UInt16(self, \"left\", \"Destination rectangle (left)\") yield UInt16(self, \"top\",", "data\"), }) def parseAnimationHeader(self): yield UInt32(self, \"hdr_size\", \"Size of header", "chunk_cls = Chunk # Parse all chunks up to filesize", "audio_codec_name) yield UInt16(self, \"channel\", \"Audio format: Channels\") yield UInt32(self, \"sample_rate\",", "file type try: chunk_cls = self.VALID_TYPES[self[\"type\"].value][0] except KeyError: chunk_cls =", "= self.tag_info[1] if handler: for field in handler(self): yield field", "# This dictionnary is edited by RiffFile.validate() \"LIST\": (\"list[]\", None,", "parseText, \"Author\"), \"ICRD\": (\"creation_date\", parseText, \"Creation date\"), \"ISFT\": (\"producer\", parseText,", "import alignValue, humanDuration from lib.hachoir_core.endian import LITTLE_ENDIAN from lib.hachoir_core.text_handler import", "\"sample_per_sec\", \"Sample per second\") yield UInt32(self, \"byte_per_sec\", \"Average byte per", "= timedelta(seconds=float(header[\"total_frame\"].value) * microsec) desc += \", \" + humanDuration(delta)", "IcoFile from datetime import timedelta def parseText(self): yield String(self, \"text\",", "UInt32(self, \"hsg_offset\", \"Track offset (HSG format)\") yield UInt32(self, \"hsg_length\", \"Track", "\"Real number of frame of OpenDML video\") padding = self[\"size\"].value", "16: yield UInt16(self, \"bits_per_sample\", \"Audio format: Bits per sample\") if", "\"Initial frame (used in interleaved video)\") yield UInt32(self, \"nb_stream\", \"Number", "def parseVideoFormat(self, size): yield UInt32(self, \"video_size\", \"Video format: Size\") yield", "yield UInt8(self, \"padding[]\", \"Padding\") else: handler = self.tag_info[1] if handler:", "UInt8(self, \"padding[]\", \"Padding\") else: handler = self.tag_info[1] if handler: for", "of audio channel\") yield UInt32(self, \"sample_per_sec\", \"Sample per second\") yield", "\"planes\") yield UInt32(self, \"jiffie_rate\", \"Default Jiffies (1/60th of a second)", "container * CDA file Documents: - libavformat source code from", "* 2005-06-08: creation of AVI parser by <NAME> and <NAME>", "% size) yield Enum(UInt16(self, \"codec\", \"Audio codec\"), audio_codec_name) yield UInt16(self,", "HSG address format: number of 1/75 second HSG offset =", "charset=\"ASCII\") if self[\"stream_type\"].value == \"vids\": yield Enum(field, video_fourcc_name, lambda text:", "u\"Microsoft AVI video\", \".avi\"), \"ACON\": (ChunkACON, u\"image/x-ani\", u\"Microsoft Windows animated", "Bit(self, \"must_use_index\") yield NullBits(self, \"reserved[]\", 2) yield Bit(self, \"is_interleaved\") yield", "parseText, \"Copyright\"), \"IENG\": (\"author\", parseText, \"Author\"), \"ICRD\": (\"creation_date\", parseText, \"Creation", "yield Bit(self, \"is_interleaved\") yield NullBits(self, \"reserved[]\", 2) yield Bit(self, \"trust_cktype\")", "!= \"RIFF\": return \"Wrong signature\" if self[\"type\"].value not in self.VALID_TYPES:", "ChunkCDDA(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"cdda\", parseCDDA, \"CD", "= self[\"size\"].value - 4 if 0 < padding: yield NullBytes(self,", "yield UInt8(self, \"frame\") yield UInt8(self, \"second\") yield UInt8(self, \"minute\") yield", "Bit, NullBits, NullBytes, RawBytes, String, PaddingBytes, SubFile) from lib.hachoir_core.tools import", "rate\") yield UInt32(self, \"bit_rate\", \"Audio format: Bit rate\") yield UInt16(self,", "Size of extra information\") if size >= 28: # and", "ACON (animated icons) * 2006-08-08: merge AVI, WAV and CDA", "yield UInt32(self, \"nb_stream\", \"Number of streams\") yield UInt32(self, \"sug_buf_size\", \"Suggested", "def parseAVIStreamHeader(self): if self[\"size\"].value != 56: raise ParserError(\"Invalid stream header", "not self.eof: yield AVIIndexEntry(self, \"index[]\") class Chunk(FieldSet): TAG_INFO = {", "audio\", \".wav\"), \"CDDA\": (ChunkCDDA, u\"audio/x-cda\", u\"Microsoft Windows audio CD file", "\"channel_mask\", \"Audio format: channels placement bitmask\") yield UInt32(self, \"subformat\", \"Audio", "\"Stream format\"), \"avih\": (\"avi_hdr\", parseAviHeader, \"AVI header\"), \"idx1\": (\"index\", parseIndex,", "format: \") yield UInt32(self, \"channel_mask\", \"Audio format: channels placement bitmask\")", "file format information \"\"\" from lib.hachoir_parser import Parser from lib.hachoir_core.field", "+ second)*75 + frame + 150 (from RB offset) HSG", "per second\") yield UInt16(self, \"block_align\", \"Block align\") yield UInt16(self, \"bit_per_sample\",", "header\"), \"idx1\": (\"index\", parseIndex, \"Stream index\"), \"dmlh\": (\"odml_hdr\", parseODML, \"ODML", "for Windows Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt - What is an animated", "header\"), 'seq ': (\"anim_seq\", parseAnimationSequence, \"Animation sequence\"), 'rate': (\"anim_rate\", parseAnimationRate,", "*args, **kw): FieldSet.__init__(self, *args, **kw) self._size = (8 + alignValue(self[\"size\"].value,", "of %s bytes is not supported!\" % size) yield Enum(UInt16(self,", "class ChunkWAVE(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"format\", parseWAVFormat,", "% (header[\"width\"].value, header[\"height\"].value) microsec = header[\"microsec_per_frame\"].value if microsec: desc +=", "(self.size - self.current_size)/8: field = self.__class__(self, \"field[]\") yield field if", "yield UInt32(self, \"hsg_offset\", \"Track offset (HSG format)\") yield UInt32(self, \"hsg_length\",", "by RiffFile.validate() \"LIST\": (\"list[]\", None, \"Sub-field list\"), \"JUNK\": (\"junk[]\", None,", "format)\") yield UInt32(self, \"hsg_length\", \"Track length (HSG format)\") yield RedBook(self,", "parseRawFormat(self, size): yield RawBytes(self, \"raw_format\", size) def parseVideoFormat(self, size): yield", "createDescription(self): tag = self[\"type\"].value if tag == \"AVI \": desc", "Height\") yield UInt16(self, \"panes\", \"Video format: Panes\") yield UInt16(self, \"depth\",", "UTF-8 -*- \"\"\" RIFF parser, able to parse: * AVI", "format: Sample rate\") yield UInt32(self, \"bit_rate\", \"Audio format: Bit rate\")", "UInt32(self, \"sug_buf_size\", \"Suggested buffer size\") yield UInt32(self, \"width\", \"Width in", "\"cda_version\", \"CD file version (currently 1)\") yield UInt16(self, \"track_no\", \"Number", "yield UInt32(self, \"jiffie_rate\", \"Default Jiffies (1/60th of a second) if", "yield UInt32(self, \"length\") def parseIndex(self): while not self.eof: yield AVIIndexEntry(self,", "UInt32(self, \"total_frame\", \"Total number of frames in the video\") yield", "2) yield Bit(self, \"trust_cktype\") yield NullBits(self, \"reserved[]\", 4) yield Bit(self,", "\"Headers\"), \"strl\": (\"stream[]\", \"Stream header list\"), \"movi\": (\"movie\", \"Movie stream\"),", "8*8), ), \"description\": \"Microsoft RIFF container\" } VALID_TYPES = {", "self[\"tag\"].value == \"LIST\": yield String(self, \"subtag\", 4, \"Sub-tag\", charset=\"ASCII\") handler", "from lib.hachoir_parser.image.ico import IcoFile from datetime import timedelta def parseText(self):", "info[0] for field in handler(self, size): yield field def parseAVIStreamHeader(self):", "by <NAME> * 2005-06-21: creation of WAV parser by <NAME>", "yield UInt32(self, \"scale\") yield UInt32(self, \"rate\") yield UInt32(self, \"start\") yield", "audio (.cda) file \"\"\" def createFields(self): yield UInt8(self, \"frame\") yield", "CDA parser by <NAME> * 2005-06-21: creation of WAV parser", "of a second) if rate chunk not present\") yield Bit(self,", "\"Microsecond per frame\") yield UInt32(self, \"max_byte_per_sec\", \"Maximum byte per second\")", "\"rate\") yield UInt32(self, \"start\") yield UInt32(self, \"length\") def parseODML(self): yield", "self.current_size < self[\"filesize\"].value*8+8: yield chunk_cls(self, \"chunk[]\") if not self.eof: yield", "yield Bit(self, \"is_icon\") yield NullBits(self, \"padding\", 31) def parseAnimationSequence(self): while", "info = self.subtag_info[subtag] self.tag_info = (info[0], None, info[1]) self._name =", "UInt16(self, \"reserved\", \"Audio format: \") yield UInt32(self, \"channel_mask\", \"Audio format:", "unique Icons in this cursor\") yield UInt32(self, \"nb_step\", \"Number of", "\"RIFF\": return \"Wrong signature\" if self[\"type\"].value not in self.VALID_TYPES: return", "4, \"Content type (\\\"AVI \\\", \\\"WAVE\\\", ...)\", charset=\"ASCII\") # Choose", "self.tag_info[0] self._description = self.tag_info[2] else: self.tag_info = (\"field[]\", None, None)", "}) class ChunkCDDA(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"cdda\",", "of samples in audio stream\") def parseAviHeader(self): yield UInt32(self, \"microsec_per_frame\",", "0x00085C48 => \"0008-5C48\" \"\"\" sn = field.value return \"%04X-%04X\" %", "\"Video format: YPelsPerMeter\") yield UInt32(self, \"clr_used\", \"Video format: ClrUsed\") yield", "NullBytes, RawBytes, String, PaddingBytes, SubFile) from lib.hachoir_core.tools import alignValue, humanDuration", "size = self[\"size\"].value if size not in (16, 18): self.warning(\"Format", "yield UInt16(self, \"cda_version\", \"CD file version (currently 1)\") yield UInt16(self,", "= self[\"subtag\"].value if subtag in self.subtag_info: info = self.subtag_info[subtag] self.tag_info", "\"reserved[]\", 2) yield Bit(self, \"is_interleaved\") yield NullBits(self, \"reserved[]\", 2) yield", "rectangle (top)\") yield UInt16(self, \"right\", \"Destination rectangle (right)\") yield UInt16(self,", "else: self.tag_info = (\"field[]\", None, None) def createFields(self): yield String(self,", "AVI video container * WAV audio container * CDA file", "format\"), 'fact': (\"nb_sample\", parseWAVFact, \"Number of samples\"), 'data': (\"audio_data\", None,", "yield UInt16(self, \"nb_channel\", \"Number of audio channel\") yield UInt32(self, \"sample_per_sec\",", "else: handler = self.tag_info[1] if handler: for field in handler(self):", "This dictionnary is edited by RiffFile.validate() \"LIST\": (\"list[]\", None, \"Sub-field", "yield NullBits(self, \"reserved[]\", 4) yield Bit(self, \"has_index\") yield Bit(self, \"must_use_index\")", "+= \", \" + humanDuration(delta) return desc else: try: return", "\"Video format: ClrUsed\") yield UInt32(self, \"clr_important\", \"Video format: ClrImportant\") def", "four character code\", strip=\" \\0\", charset=\"ASCII\") if self[\"stream_type\"].value == \"vids\":", "(\"datetime\", parseText, \"Date time\"), # TODO: Todo: see below #", "(u\"video/x-msvideo\", u\"audio/x-wav\", u\"audio/x-cda\"), # FIXME: Use regex \"RIFF.{4}(WAVE|CDDA|AVI )\" \"magic\":", "\"CD audio informations\"), }) class ChunkWAVE(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({", "__init__(self, *args, **kw): FieldSet.__init__(self, *args, **kw) self._size = (8 +", "UInt32(self, \"sample_size\", \"Size of samples\") yield UInt16(self, \"left\", \"Destination rectangle", "tag class ChunkAVI(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ \"strh\": (\"stream_hdr\", parseAVIStreamHeader,", "UInt32(self, \"hsg_length\", \"Track length (HSG format)\") yield RedBook(self, \"rb_offset\", \"Track", "yield UInt32(self, \"length\") def parseODML(self): yield UInt32(self, \"total_frame\", \"Real number", "Thanks to: * <NAME> (wojtekka AT logonet.com.pl) for its CDA", "UInt32(self, \"start\", \"Offset from start of movie data\") yield UInt32(self,", "\"AVI \": desc = u\"Microsoft AVI video\" if \"headers/avi_hdr\" in", "% 2 != 0: yield UInt8(self, \"padding[]\", \"Padding\") else: handler", "\"tag1\", \"Video format: Tag1\") yield UInt32(self, \"img_size\", \"Video format: Image", "\"CD file version (currently 1)\") yield UInt16(self, \"track_no\", \"Number of", "lambda text: text.upper()) else: yield field yield UInt32(self, \"flags\", \"Stream", "\"hdr_size\", \"Size of header (36 bytes)\") if self[\"hdr_size\"].value != 36:", "\"magic\": ( (\"AVI LIST\", 8*8), (\"WAVEfmt \", 8*8), (\"CDDAfmt \",", "'seq ': (\"anim_seq\", parseAnimationSequence, \"Animation sequence\"), 'rate': (\"anim_rate\", parseAnimationRate, \"Animation", "Enum(field, video_fourcc_name, lambda text: text.upper()) else: yield field yield UInt32(self,", "\"icon[]\") def formatJiffie(field): sec = float(field.value) / 60 return humanDuration(timedelta(seconds=sec))", "* <NAME> * <NAME> * <NAME> Changelog: * 2007-03-30: support", "\"Default Jiffies (1/60th of a second) if rate chunk not", "channel\") yield UInt32(self, \"sample_per_sec\", \"Sample per second\") yield UInt32(self, \"byte_per_sec\",", "frame rate\") yield UInt32(self, \"start\", \"Stream start time (unit: rate/scale)\")", "UInt32(self, \"width\", \"Width in pixel\") yield UInt32(self, \"height\", \"Height in", "\"Destination rectangle (top)\") yield UInt16(self, \"right\", \"Destination rectangle (right)\") yield", "!= 0: yield UInt8(self, \"padding[]\", \"Padding\") else: handler = self.tag_info[1]", "\"Number of unique Icons in this cursor\") yield UInt32(self, \"nb_step\",", "(\"anim_rate\", parseAnimationRate, \"Animation sequence\"), 'icon': (\"icon[]\", parseIcon, \"Icon\"), }) class", "cycles\") yield UInt32(self, \"cx\") yield UInt32(self, \"cy\") yield UInt32(self, \"bit_count\")", "18): self.warning(\"Format with size of %s bytes is not supported!\"", "\"Document title\"), \"IART\": (\"artist\", parseText, \"Artist\"), \"ICMT\": (\"comment\", parseText, \"Comment\"),", "= TYPE_HANDLER[strtype] if info[1] <= size: handler = info[0] for", "\"total_frame\" in header and header[\"total_frame\"].value: delta = timedelta(seconds=float(header[\"total_frame\"].value) * microsec)", "RB length) \"\"\" yield UInt16(self, \"cda_version\", \"CD file version (currently", "format: Panes\") yield UInt16(self, \"depth\", \"Video format: Depth\") yield UInt32(self,", "an animated cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm Authors: * <NAME> * <NAME> *", "yield UInt32(self, \"hsg_length\", \"Track length (HSG format)\") yield RedBook(self, \"rb_offset\",", "- libavformat source code from ffmpeg library http://ffmpeg.mplayerhq.hu/ - Video", "before the animation cycles\") yield UInt32(self, \"cx\") yield UInt32(self, \"cy\")", "\"Size of samples\") yield UInt16(self, \"left\", \"Destination rectangle (left)\") yield", "format: YPelsPerMeter\") yield UInt32(self, \"clr_used\", \"Video format: ClrUsed\") yield UInt32(self,", "video_fourcc_name from lib.hachoir_parser.image.ico import IcoFile from datetime import timedelta def", "(\"audio_data\", None, \"Audio stream data\"), }) def parseAnimationHeader(self): yield UInt32(self,", "RIFF container\" } VALID_TYPES = { \"WAVE\": (ChunkWAVE, u\"audio/x-wav\", u\"Microsoft", "\"ext_size\", \"Audio format: Size of extra information\") if size >=", "\"auds\": (parseAudioFormat, 16) } handler = parseRawFormat if strtype in", "http://ffmpeg.mplayerhq.hu/ - Video for Windows Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt - What", "UInt32(self, \"img_size\", \"Video format: Image size\") yield UInt32(self, \"xpels_meter\", \"Video", "stream data\"), }) def parseAnimationHeader(self): yield UInt32(self, \"hdr_size\", \"Size of", "\"riff\", \"category\": \"container\", \"file_ext\": (\"avi\", \"cda\", \"wav\", \"ani\"), \"min_size\": 16*8,", "yield UInt32(self, \"rate\") yield UInt32(self, \"start\") yield UInt32(self, \"length\") def", "UInt32(self, \"channel_mask\", \"Audio format: channels placement bitmask\") yield UInt32(self, \"subformat\",", "for field in handler(self, size): yield field def parseAVIStreamHeader(self): if", "<NAME> (wojtekka AT logonet.com.pl) for its CDA file format information", "\"reserved[]\", 4) yield Bit(self, \"was_capture_file\") yield Bit(self, \"is_copyrighted\") yield NullBits(self,", "# \"wb\": \"Audio data\", # \"pc\": \"Palette change\" } subtag_info", "lib.hachoir_core.endian import LITTLE_ENDIAN from lib.hachoir_core.text_handler import filesizeHandler, textHandler from lib.hachoir_parser.video.fourcc", "NullBytes(self, \"padding[]\", padding) class AVIIndexEntry(FieldSet): size = 16*8 def createFields(self):", "cursor\", \".ani\"), } endian = LITTLE_ENDIAN def validate(self): if self.stream.readBytes(0,", "return u\"Microsoft RIFF container\" def createContentSize(self): size = (self[\"filesize\"].value +", "u\"Chunk (tag %s)\" % tag class ChunkAVI(Chunk): TAG_INFO = Chunk.TAG_INFO.copy()", "RedBook(self, \"rb_length\", \"Track length (Red-book format)\") def parseWAVFormat(self): size =", "= (minute*60 + second)*75 + frame (from RB length) \"\"\"", "yield UInt32(self, \"quality\", \"Stream quality\") yield UInt32(self, \"sample_size\", \"Size of", "return u\"Chunk (tag %s)\" % tag class ChunkAVI(Chunk): TAG_INFO =", "type four character code\", charset=\"ASCII\") field = String(self, \"fourcc\", 4,", "\"jiffie_rate\", \"Default Jiffies (1/60th of a second) if rate chunk", ">= 18: yield UInt16(self, \"ext_size\", \"Audio format: Size of extra", "String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield UInt32(self, \"flags\") yield UInt32(self,", "datetime import timedelta def parseText(self): yield String(self, \"text\", self[\"size\"].value, strip=\"", "), \"description\": \"Microsoft RIFF container\" } VALID_TYPES = { \"WAVE\":", "header = self[\"headers/avi_hdr\"] desc += \": %ux%u pixels\" % (header[\"width\"].value,", "UInt32(self, \"sample_rate\", \"Audio format: Sample rate\") yield UInt32(self, \"bit_rate\", \"Audio", "and CDA parsers into RIFF parser * 2006-08-03: creation of", "second)*75 + frame + 150 (from RB offset) HSG length", "\"Track offset (Red-book format)\") yield RedBook(self, \"rb_length\", \"Track length (Red-book", "header\"), \"strf\": (\"stream_fmt\", parseAVIStreamFormat, \"Stream format\"), \"avih\": (\"avi_hdr\", parseAviHeader, \"AVI", "\"depth\", \"Video format: Depth\") yield UInt32(self, \"tag1\", \"Video format: Tag1\")", "handler(self): yield field else: yield RawBytes(self, \"raw_content\", self[\"size\"].value) padding =", "source code from ffmpeg library http://ffmpeg.mplayerhq.hu/ - Video for Windows", "from start of movie data\") yield UInt32(self, \"length\") def parseIndex(self):", "%ux%u pixels\" % (header[\"width\"].value, header[\"height\"].value) microsec = header[\"microsec_per_frame\"].value if microsec:", "handler = parseRawFormat if strtype in TYPE_HANDLER: info = TYPE_HANDLER[strtype]", "version (currently 1)\") yield UInt16(self, \"track_no\", \"Number of track\") yield", "\"right\", \"Destination rectangle (right)\") yield UInt16(self, \"bottom\", \"Destination rectangle (bottom)\")", "to: * <NAME> (wojtekka AT logonet.com.pl) for its CDA file", "(used in interleaved video)\") yield UInt32(self, \"nb_stream\", \"Number of streams\")", "if self[\"type\"].value not in self.VALID_TYPES: return \"Unknown RIFF content type\"", "\"type\", 4, \"Content type (\\\"AVI \\\", \\\"WAVE\\\", ...)\", charset=\"ASCII\") #", "self.subtag_info[subtag] self.tag_info = (info[0], None, info[1]) self._name = self.tag_info[0] self._description", "UInt16(self, \"track_no\", \"Number of track\") yield textHandler(UInt32(self, \"disc_serial\", \"Disc serial", "rate/scale)\") yield UInt32(self, \"buf_size\", \"Suggested buffer size\") yield UInt32(self, \"quality\",", "Guide http://www.opennet.ru/docs/formats/avi.txt - What is an animated cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm Authors:", "UInt32(self, \"flags\", \"Stream flags\") yield UInt16(self, \"priority\", \"Stream priority\") yield", "UInt32(self, \"clr_used\", \"Video format: ClrUsed\") yield UInt32(self, \"clr_important\", \"Video format:", "# \"strn\": Stream description # TWOCC code, movie/field[]/tag.value[2:4]: # \"db\":", "rate\") yield UInt32(self, \"start\", \"Stream start time (unit: rate/scale)\") yield", "self.__class__(self, \"field[]\") yield field if (field.size/8) % 2 != 0:", "\"padding\", 31) def parseAnimationSequence(self): while not self.eof: yield UInt32(self, \"icon[]\")", "size\") yield UInt32(self, \"quality\", \"Stream quality\") yield UInt32(self, \"sample_size\", \"Size", "def parseCDDA(self): \"\"\" HSG address format: number of 1/75 second", "yield filesizeHandler(UInt32(self, \"size\", \"Size\")) if not self[\"size\"].value: return if self[\"tag\"].value", "\"ICMT\": (\"comment\", parseText, \"Comment\"), \"ICOP\": (\"copyright\", parseText, \"Copyright\"), \"IENG\": (\"author\",", "TAG_INFO.update({ 'fmt ': (\"format\", parseWAVFormat, \"Audio format\"), 'fact': (\"nb_sample\", parseWAVFact,", "Icons in this cursor\") yield UInt32(self, \"nb_step\", \"Number of Blits", "UInt32(self, \"start\") yield UInt32(self, \"length\") def parseODML(self): yield UInt32(self, \"total_frame\",", "Bit(self, \"is_icon\") yield NullBits(self, \"padding\", 31) def parseAnimationSequence(self): while not", "see below # \"strn\": Stream description # TWOCC code, movie/field[]/tag.value[2:4]:", "(\"index\", parseIndex, \"Stream index\"), \"dmlh\": (\"odml_hdr\", parseODML, \"ODML header\"), })", "Chunk.TAG_INFO.copy() TAG_INFO.update({ 'anih': (\"anim_hdr\", parseAnimationHeader, \"Animation header\"), 'seq ': (\"anim_seq\",", "of samples\") yield UInt16(self, \"left\", \"Destination rectangle (left)\") yield UInt16(self,", "\"reserved[]\", 4) yield Bit(self, \"has_index\") yield Bit(self, \"must_use_index\") yield NullBits(self,", "text.upper()) else: yield field yield UInt32(self, \"flags\", \"Stream flags\") yield", "\"Stream priority\") yield String(self, \"language\", 2, \"Stream language\", charset=\"ASCII\", strip=\"\\0\")", "yield UInt16(self, \"right\", \"Destination rectangle (right)\") yield UInt16(self, \"bottom\", \"Destination", "scale to give frame rate\") yield UInt32(self, \"start\", \"Stream start", "\"Offset from start of movie data\") yield UInt32(self, \"length\") def", "UInt32(self, \"microsec_per_frame\", \"Microsecond per frame\") yield UInt32(self, \"max_byte_per_sec\", \"Maximum byte", "\"scale\", \"Time scale\") yield UInt32(self, \"rate\", \"Divide by scale to", "= Chunk.TAG_INFO.copy() TAG_INFO.update({ \"strh\": (\"stream_hdr\", parseAVIStreamHeader, \"Stream header\"), \"strf\": (\"stream_fmt\",", "\"bit_count\") yield UInt32(self, \"planes\") yield UInt32(self, \"jiffie_rate\", \"Default Jiffies (1/60th", "return if self[\"tag\"].value == \"LIST\": yield String(self, \"subtag\", 4, \"Sub-tag\",", "\"panes\", \"Video format: Panes\") yield UInt16(self, \"depth\", \"Video format: Depth\")", "\"\"\" Format an disc serial number. Eg. 0x00085C48 => \"0008-5C48\"", "yield String(self, \"text\", self[\"size\"].value, strip=\" \\0\", truncate=\"\\0\", charset=\"ISO-8859-1\") def parseRawFormat(self,", "\"mime\": (u\"video/x-msvideo\", u\"audio/x-wav\", u\"audio/x-cda\"), # FIXME: Use regex \"RIFF.{4}(WAVE|CDDA|AVI )\"", "TODO: Todo: see below # \"strn\": Stream description # TWOCC", "yield UInt16(self, \"priority\", \"Stream priority\") yield String(self, \"language\", 2, \"Stream", "= self[\"headers/avi_hdr\"] desc += \": %ux%u pixels\" % (header[\"width\"].value, header[\"height\"].value)", "yield UInt32(self, \"clr_used\", \"Video format: ClrUsed\") yield UInt32(self, \"clr_important\", \"Video", "if tag == \"LIST\": subtag = self[\"subtag\"].value if subtag in", "file (cda)\", \".cda\"), \"AVI \": (ChunkAVI, u\"video/x-msvideo\", u\"Microsoft AVI video\",", "8) * 8 return min(size, self.stream.size) def createFilenameSuffix(self): try: return", "+ alignValue(self[\"size\"].value, 2)) * 8 tag = self[\"tag\"].value if tag", "\"has_index\") yield Bit(self, \"must_use_index\") yield NullBits(self, \"reserved[]\", 2) yield Bit(self,", "NullBits(self, \"padding\", 31) def parseAnimationSequence(self): while not self.eof: yield UInt32(self,", "\"nb_step\", \"Number of Blits before the animation cycles\") yield UInt32(self,", "yield UInt16(self, \"track_no\", \"Number of track\") yield textHandler(UInt32(self, \"disc_serial\", \"Disc", "yield textHandler(UInt32(self, \"disc_serial\", \"Disc serial number\"), formatSerialNumber) yield UInt32(self, \"hsg_offset\",", "\"byte_per_sec\", \"Average byte per second\") yield UInt16(self, \"block_align\", \"Block align\")", "format information \"\"\" from lib.hachoir_parser import Parser from lib.hachoir_core.field import", "timedelta def parseText(self): yield String(self, \"text\", self[\"size\"].value, strip=\" \\0\", truncate=\"\\0\",", "\"Audio format: channels placement bitmask\") yield UInt32(self, \"subformat\", \"Audio format:", "\"quality\", \"Stream quality\") yield UInt32(self, \"sample_size\", \"Size of samples\") yield", "= (info[0], None, info[1]) self._name = self.tag_info[0] self._description = self.tag_info[2]", "library http://ffmpeg.mplayerhq.hu/ - Video for Windows Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt -", "yield textHandler(UInt32(self, \"rate[]\"), formatJiffie) def parseIcon(self): yield SubFile(self, \"icon_file\", self[\"size\"].value,", "{ \"id\": \"riff\", \"category\": \"container\", \"file_ext\": (\"avi\", \"cda\", \"wav\", \"ani\"),", "formatJiffie) def parseIcon(self): yield SubFile(self, \"icon_file\", self[\"size\"].value, parser_class=IcoFile) class ChunkACON(Chunk):", "<NAME> * 2005-06-08: creation of AVI parser by <NAME> and", "VALID_TYPES = { \"WAVE\": (ChunkWAVE, u\"audio/x-wav\", u\"Microsoft WAVE audio\", \".wav\"),", "yield UInt32(self, \"scale\", \"Time scale\") yield UInt32(self, \"rate\", \"Divide by", "\"Copyright\"), \"IENG\": (\"author\", parseText, \"Author\"), \"ICRD\": (\"creation_date\", parseText, \"Creation date\"),", "format: ClrImportant\") def parseAudioFormat(self, size): yield Enum(UInt16(self, \"codec\", \"Audio format:", "yield UInt32(self, \"max_byte_per_sec\", \"Maximum byte per second\") yield NullBytes(self, \"reserved\",", "* <NAME> (wojtekka AT logonet.com.pl) for its CDA file format", "<NAME> * <NAME> * <NAME> Changelog: * 2007-03-30: support ACON", "samples\"), 'data': (\"audio_data\", None, \"Audio stream data\"), }) def parseAnimationHeader(self):", "YPelsPerMeter\") yield UInt32(self, \"clr_used\", \"Video format: ClrUsed\") yield UInt32(self, \"clr_important\",", "PaddingBytes, SubFile) from lib.hachoir_core.tools import alignValue, humanDuration from lib.hachoir_core.endian import", "Blits before the animation cycles\") yield UInt32(self, \"cx\") yield UInt32(self,", "its CDA file format information \"\"\" from lib.hachoir_parser import Parser", "self.seekBit(self._size) if padding: yield padding def createDescription(self): tag = self[\"tag\"].display", "( (\"AVI LIST\", 8*8), (\"WAVEfmt \", 8*8), (\"CDDAfmt \", 8*8),", "\"rb_length\", \"Track length (Red-book format)\") def parseWAVFormat(self): size = self[\"size\"].value", "\"Time scale\") yield UInt32(self, \"rate\", \"Divide by scale to give", "(\"odml\", \"ODML\"), } def __init__(self, *args, **kw): FieldSet.__init__(self, *args, **kw)", "-*- coding: UTF-8 -*- \"\"\" RIFF parser, able to parse:", "stream header size\") yield String(self, \"stream_type\", 4, \"Stream type four", "createFields(self): yield UInt8(self, \"frame\") yield UInt8(self, \"second\") yield UInt8(self, \"minute\")", "16*8 def createFields(self): yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield", "= self.tag_info[1] while 8 < (self.size - self.current_size)/8: field =", "\": desc = u\"Microsoft AVI video\" if \"headers/avi_hdr\" in self:", "\"disc_serial\", \"Disc serial number\"), formatSerialNumber) yield UInt32(self, \"hsg_offset\", \"Track offset", "format\"), \"avih\": (\"avi_hdr\", parseAviHeader, \"AVI header\"), \"idx1\": (\"index\", parseIndex, \"Stream", "\"vids\": yield Enum(field, video_fourcc_name, lambda text: text.upper()) else: yield field", "\"Palette change\" } subtag_info = { \"INFO\": (\"info\", \"File informations\"),", "u\"Microsoft AVI video\" if \"headers/avi_hdr\" in self: header = self[\"headers/avi_hdr\"]", "\"AVI header (RIFF)\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"filesize\", \"File size\")) yield", "!= 36: self.warning(\"Animation header with unknown size (%s)\" % self[\"size\"].value)", "time (unit: rate/scale)\") yield UInt32(self, \"length\", \"Stream length (unit: rate/scale)\")", "< self[\"filesize\"].value*8+8: yield chunk_cls(self, \"chunk[]\") if not self.eof: yield RawBytes(self,", "yield UInt32(self, \"sample_rate\", \"Audio format: Sample rate\") yield UInt32(self, \"bit_rate\",", "UInt32(self, \"init_frame\", \"Initial frame (used in interleaved video)\") yield UInt32(self,", "parseText, \"Comment\"), \"ICOP\": (\"copyright\", parseText, \"Copyright\"), \"IENG\": (\"author\", parseText, \"Author\"),", "file \"\"\" def createFields(self): yield UInt8(self, \"frame\") yield UInt8(self, \"second\")", "\"length\", \"Stream length (unit: rate/scale)\") yield UInt32(self, \"buf_size\", \"Suggested buffer", "self.tag_info[1] if handler: for field in handler(self): yield field else:", "second HSG offset = (minute*60 + second)*75 + frame +", "rate chunk not present\") yield Bit(self, \"is_icon\") yield NullBits(self, \"padding\",", "\"INAM\": (\"title\", parseText, \"Document title\"), \"IART\": (\"artist\", parseText, \"Artist\"), \"ICMT\":", "from datetime import timedelta def parseText(self): yield String(self, \"text\", self[\"size\"].value,", "}) class RiffFile(Parser): PARSER_TAGS = { \"id\": \"riff\", \"category\": \"container\",", "\"width\", \"Video format: Width\") yield UInt32(self, \"height\", \"Video format: Height\")", "def parseAnimationHeader(self): yield UInt32(self, \"hdr_size\", \"Size of header (36 bytes)\")", "else: yield field yield UInt32(self, \"flags\", \"Stream flags\") yield UInt16(self,", "field = String(self, \"fourcc\", 4, \"Stream four character code\", strip=\"", "size = (self[\"filesize\"].value + 8) * 8 return min(size, self.stream.size)", "import IcoFile from datetime import timedelta def parseText(self): yield String(self,", "format: Codec id\"), audio_codec_name) yield UInt16(self, \"channel\", \"Audio format: Channels\")", "yield UInt16(self, \"top\", \"Destination rectangle (top)\") yield UInt16(self, \"right\", \"Destination", "microsec = header[\"microsec_per_frame\"].value if microsec: desc += \", %.1f fps\"", "if self[\"hdr_size\"].value != 36: self.warning(\"Animation header with unknown size (%s)\"", "in audio stream\") def parseAviHeader(self): yield UInt32(self, \"microsec_per_frame\", \"Microsecond per", "UInt16(self, \"bits_per_sample\", \"Audio format: Bits per sample\") if size >=", "parser by <NAME> and <NAME> Thanks to: * <NAME> (wojtekka", "yield field else: yield RawBytes(self, \"raw_content\", self[\"size\"].value) padding = self.seekBit(self._size)", "lib.hachoir_core.field import (FieldSet, ParserError, UInt8, UInt16, UInt32, Enum, Bit, NullBits,", "with size of %s bytes is not supported!\" % size)", "\"Track length (HSG format)\") yield RedBook(self, \"rb_offset\", \"Track offset (Red-book", "length (Red-book format)\") def parseWAVFormat(self): size = self[\"size\"].value if size", "\"filesize\", \"File size\")) yield String(self, \"type\", 4, \"Content type (\\\"AVI", "<NAME> * <NAME> Changelog: * 2007-03-30: support ACON (animated icons)", "% (sn >> 16, sn & 0xFFFF) def parseCDDA(self): \"\"\"", "= self[\"size\"].value if size not in (16, 18): self.warning(\"Format with", "\"is_icon\") yield NullBits(self, \"padding\", 31) def parseAnimationSequence(self): while not self.eof:", "UInt16(self, \"top\", \"Destination rectangle (top)\") yield UInt16(self, \"right\", \"Destination rectangle", "size): yield field def parseAVIStreamHeader(self): if self[\"size\"].value != 56: raise", "RiffFile.validate() \"LIST\": (\"list[]\", None, \"Sub-field list\"), \"JUNK\": (\"junk[]\", None, \"Junk", "= self[\"tag\"].value if tag in self.TAG_INFO: self.tag_info = self.TAG_INFO[tag] if", "UInt16(self, \"block_align\", \"Block align\") yield UInt16(self, \"bit_per_sample\", \"Bits per sample\")", "CDA file format information \"\"\" from lib.hachoir_parser import Parser from", "def createMimeType(self): try: return self.VALID_TYPES[self[\"type\"].value][1] except KeyError: return None def", "\"\"\" RedBook offset parser, used in CD audio (.cda) file", "self[\"headers/avi_hdr\"] desc += \": %ux%u pixels\" % (header[\"width\"].value, header[\"height\"].value) microsec", "\"microsec_per_frame\", \"Microsecond per frame\") yield UInt32(self, \"max_byte_per_sec\", \"Maximum byte per", "# Metadata \"INAM\": (\"title\", parseText, \"Document title\"), \"IART\": (\"artist\", parseText,", "\"movi\": (\"movie\", \"Movie stream\"), \"odml\": (\"odml\", \"ODML\"), } def __init__(self,", "4) != \"RIFF\": return \"Wrong signature\" if self[\"type\"].value not in", "from ffmpeg library http://ffmpeg.mplayerhq.hu/ - Video for Windows Programmer's Guide", "= String(self, \"fourcc\", 4, \"Stream four character code\", strip=\" \\0\",", "UInt32(self, \"scale\", \"Time scale\") yield UInt32(self, \"rate\", \"Divide by scale", "padding: yield NullBytes(self, \"padding[]\", padding) class AVIIndexEntry(FieldSet): size = 16*8", "else: try: return self.VALID_TYPES[tag][2] except KeyError: return u\"Microsoft RIFF container\"", "def parseAnimationSequence(self): while not self.eof: yield UInt32(self, \"icon[]\") def formatJiffie(field):", "Flags yield NullBits(self, \"reserved[]\", 4) yield Bit(self, \"has_index\") yield Bit(self,", "header (RIFF)\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"filesize\", \"File size\")) yield String(self,", "None, None) def createFields(self): yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\")", "handler = self.tag_info[1] while 8 < (self.size - self.current_size)/8: field", "size\") yield String(self, \"stream_type\", 4, \"Stream type four character code\",", "= Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"format\", parseWAVFormat, \"Audio format\"), 'fact':", "size >= 18: yield UInt16(self, \"ext_size\", \"Audio format: Size of", "tag == \"AVI \": desc = u\"Microsoft AVI video\" if", "bytes)\") if self[\"hdr_size\"].value != 36: self.warning(\"Animation header with unknown size", "\"video_size\", \"Video format: Size\") yield UInt32(self, \"width\", \"Video format: Width\")", "KeyError: return u\"Microsoft RIFF container\" def createContentSize(self): size = (self[\"filesize\"].value", "\"idx1\": (\"index\", parseIndex, \"Stream index\"), \"dmlh\": (\"odml_hdr\", parseODML, \"ODML header\"),", "field else: yield RawBytes(self, \"raw_content\", self[\"size\"].value) padding = self.seekBit(self._size) if", "bytes is not supported!\" % size) yield Enum(UInt16(self, \"codec\", \"Audio", "TYPE_HANDLER[strtype] if info[1] <= size: handler = info[0] for field", "padding = self[\"size\"].value - 4 if 0 < padding: yield", "self[\"subtag\"].value if subtag in self.subtag_info: info = self.subtag_info[subtag] self.tag_info =", "{ # This dictionnary is edited by RiffFile.validate() \"LIST\": (\"list[]\",", "KeyError: chunk_cls = Chunk # Parse all chunks up to", "\"Audio codec\"), audio_codec_name) yield UInt16(self, \"nb_channel\", \"Number of audio channel\")", "UInt32(self, \"byte_per_sec\", \"Average byte per second\") yield UInt16(self, \"block_align\", \"Block", "\"LIST\": subtag = self[\"subtag\"].value if subtag in self.subtag_info: info =", "2006-08-08: merge AVI, WAV and CDA parsers into RIFF parser", "charset=\"ASCII\") handler = self.tag_info[1] while 8 < (self.size - self.current_size)/8:", "format: Depth\") yield UInt32(self, \"tag1\", \"Video format: Tag1\") yield UInt32(self,", "(\"odml_hdr\", parseODML, \"ODML header\"), }) class ChunkCDDA(Chunk): TAG_INFO = Chunk.TAG_INFO.copy()", "OpenDML video\") padding = self[\"size\"].value - 4 if 0 <", "\": (ChunkAVI, u\"video/x-msvideo\", u\"Microsoft AVI video\", \".avi\"), \"ACON\": (ChunkACON, u\"image/x-ani\",", "audio_codec_name, video_fourcc_name from lib.hachoir_parser.image.ico import IcoFile from datetime import timedelta", "to parse: * AVI video container * WAV audio container", "to filesize while self.current_size < self[\"filesize\"].value*8+8: yield chunk_cls(self, \"chunk[]\") if", "+ 8) * 8 return min(size, self.stream.size) def createFilenameSuffix(self): try:", "\"Stream index\"), \"dmlh\": (\"odml_hdr\", parseODML, \"ODML header\"), }) class ChunkCDDA(Chunk):", "field.value return \"%04X-%04X\" % (sn >> 16, sn & 0xFFFF)", "'fmt ': (\"format\", parseWAVFormat, \"Audio format\"), 'fact': (\"nb_sample\", parseWAVFact, \"Number", "yield NullBits(self, \"padding\", 31) def parseAnimationSequence(self): while not self.eof: yield", "**kw): FieldSet.__init__(self, *args, **kw) self._size = (8 + alignValue(self[\"size\"].value, 2))", "header[\"total_frame\"].value: delta = timedelta(seconds=float(header[\"total_frame\"].value) * microsec) desc += \", \"", "parser by <NAME> * 2005-06-21: creation of WAV parser by", "try: return self.VALID_TYPES[tag][2] except KeyError: return u\"Microsoft RIFF container\" def", "def __init__(self, *args, **kw): FieldSet.__init__(self, *args, **kw) self._size = (8", "(\"anim_hdr\", parseAnimationHeader, \"Animation header\"), 'seq ': (\"anim_seq\", parseAnimationSequence, \"Animation sequence\"),", "buffer size\") yield UInt32(self, \"width\", \"Width in pixel\") yield UInt32(self,", "parsers into RIFF parser * 2006-08-03: creation of CDA parser", "informations\"), \"hdrl\": (\"headers\", \"Headers\"), \"strl\": (\"stream[]\", \"Stream header list\"), \"movi\":", "\"vids\": (parseVideoFormat, 40), \"auds\": (parseAudioFormat, 16) } handler = parseRawFormat", "code\", strip=\" \\0\", charset=\"ASCII\") if self[\"stream_type\"].value == \"vids\": yield Enum(field,", "(tag %s)\" % tag class ChunkAVI(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({", "= self[\"type\"].value if tag == \"AVI \": desc = u\"Microsoft", "(\"icon[]\", parseIcon, \"Icon\"), }) class RiffFile(Parser): PARSER_TAGS = { \"id\":", "alignValue(self[\"size\"].value, 2)) * 8 tag = self[\"tag\"].value if tag in", "subtag = self[\"subtag\"].value if subtag in self.subtag_info: info = self.subtag_info[subtag]", "String(self, \"language\", 2, \"Stream language\", charset=\"ASCII\", strip=\"\\0\") yield UInt32(self, \"init_frames\",", "time\"), # TODO: Todo: see below # \"strn\": Stream description", "= u\"Microsoft AVI video\" if \"headers/avi_hdr\" in self: header =", "number of frames in the video\") yield UInt32(self, \"init_frame\", \"Initial", "microsec) if \"total_frame\" in header and header[\"total_frame\"].value: delta = timedelta(seconds=float(header[\"total_frame\"].value)", "microsec) desc += \", \" + humanDuration(delta) return desc else:", "track\") yield textHandler(UInt32(self, \"disc_serial\", \"Disc serial number\"), formatSerialNumber) yield UInt32(self,", "- What is an animated cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm Authors: * <NAME>", "UInt32(self, \"xpels_meter\", \"Video format: XPelsPerMeter\") yield UInt32(self, \"ypels_meter\", \"Video format:", "# -*- coding: UTF-8 -*- \"\"\" RIFF parser, able to", "extra information\") if size >= 28: # and self[\"a_channel\"].value >", "# \"dc\": \"Compressed video frame\", # \"wb\": \"Audio data\", #", "(sn >> 16, sn & 0xFFFF) def parseCDDA(self): \"\"\" HSG", "\"strl\": (\"stream[]\", \"Stream header list\"), \"movi\": (\"movie\", \"Movie stream\"), \"odml\":", "(\"comment\", parseText, \"Comment\"), \"ICOP\": (\"copyright\", parseText, \"Copyright\"), \"IENG\": (\"author\", parseText,", "parseAviHeader(self): yield UInt32(self, \"microsec_per_frame\", \"Microsecond per frame\") yield UInt32(self, \"max_byte_per_sec\",", "yield RawBytes(self, \"raw_content\", self[\"size\"].value) padding = self.seekBit(self._size) if padding: yield", "28: # and self[\"a_channel\"].value > 2 yield UInt16(self, \"reserved\", \"Audio", "textHandler(UInt32(self, \"disc_serial\", \"Disc serial number\"), formatSerialNumber) yield UInt32(self, \"hsg_offset\", \"Track", "(16, 18): self.warning(\"Format with size of %s bytes is not", "self[\"size\"].value) yield UInt32(self, \"nb_frame\", \"Number of unique Icons in this", "parseODML, \"ODML header\"), }) class ChunkCDDA(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({", "% self[\"size\"].value) yield UInt32(self, \"nb_frame\", \"Number of unique Icons in", "size (%s)\" % self[\"size\"].value) yield UInt32(self, \"nb_frame\", \"Number of unique", "\"sample_size\", \"Size of samples\") yield UInt16(self, \"left\", \"Destination rectangle (left)\")", "\"dc\": \"Compressed video frame\", # \"wb\": \"Audio data\", # \"pc\":", "\"text\", self[\"size\"].value, strip=\" \\0\", truncate=\"\\0\", charset=\"ISO-8859-1\") def parseRawFormat(self, size): yield", "}) class ChunkWAVE(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"format\",", "(\"ACONanih\", 8*8), ), \"description\": \"Microsoft RIFF container\" } VALID_TYPES =", "= { # This dictionnary is edited by RiffFile.validate() \"LIST\":", "yield RawBytes(self, \"padding[]\", (self.size-self.current_size)/8) def createMimeType(self): try: return self.VALID_TYPES[self[\"type\"].value][1] except", "yield Bit(self, \"was_capture_file\") yield Bit(self, \"is_copyrighted\") yield NullBits(self, \"reserved[]\", 14)", "charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"size\", \"Size\")) if not self[\"size\"].value: return if", "60 return humanDuration(timedelta(seconds=sec)) def parseAnimationRate(self): while not self.eof: yield textHandler(UInt32(self,", "charset=\"ISO-8859-1\") def parseRawFormat(self, size): yield RawBytes(self, \"raw_format\", size) def parseVideoFormat(self,", "sample\") def parseWAVFact(self): yield UInt32(self, \"nb_sample\", \"Number of samples in", "\"%04X-%04X\" % (sn >> 16, sn & 0xFFFF) def parseCDDA(self):", "edited by RiffFile.validate() \"LIST\": (\"list[]\", None, \"Sub-field list\"), \"JUNK\": (\"junk[]\",", "\"cx\") yield UInt32(self, \"cy\") yield UInt32(self, \"bit_count\") yield UInt32(self, \"planes\")", "\"strn\": Stream description # TWOCC code, movie/field[]/tag.value[2:4]: # \"db\": \"Uncompressed", "createDescription(self): tag = self[\"tag\"].display return u\"Chunk (tag %s)\" % tag", "= self.__class__(self, \"field[]\") yield field if (field.size/8) % 2 !=", "self.tag_info[2] else: self.tag_info = (\"field[]\", None, None) def createFields(self): yield", "\"rate[]\"), formatJiffie) def parseIcon(self): yield SubFile(self, \"icon_file\", self[\"size\"].value, parser_class=IcoFile) class", "self.VALID_TYPES[self[\"type\"].value][0] except KeyError: chunk_cls = Chunk # Parse all chunks", "SubFile) from lib.hachoir_core.tools import alignValue, humanDuration from lib.hachoir_core.endian import LITTLE_ENDIAN", "\"bit_per_sample\", \"Bits per sample\") def parseWAVFact(self): yield UInt32(self, \"nb_sample\", \"Number", "timedelta(seconds=float(header[\"total_frame\"].value) * microsec) desc += \", \" + humanDuration(delta) return", "\"xpels_meter\", \"Video format: XPelsPerMeter\") yield UInt32(self, \"ypels_meter\", \"Video format: YPelsPerMeter\")", "% (1000000.0 / microsec) if \"total_frame\" in header and header[\"total_frame\"].value:", "field def parseAVIStreamHeader(self): if self[\"size\"].value != 56: raise ParserError(\"Invalid stream", "WAVE audio\", \".wav\"), \"CDDA\": (ChunkCDDA, u\"audio/x-cda\", u\"Microsoft Windows audio CD", "pixels\" % (header[\"width\"].value, header[\"height\"].value) microsec = header[\"microsec_per_frame\"].value if microsec: desc", "parseAnimationRate(self): while not self.eof: yield textHandler(UInt32(self, \"rate[]\"), formatJiffie) def parseIcon(self):", "self.eof: yield RawBytes(self, \"padding[]\", (self.size-self.current_size)/8) def createMimeType(self): try: return self.VALID_TYPES[self[\"type\"].value][1]", "\"Height in pixel\") yield UInt32(self, \"scale\") yield UInt32(self, \"rate\") yield", "\"ODML\"), } def __init__(self, *args, **kw): FieldSet.__init__(self, *args, **kw) self._size", "\"sample_rate\", \"Audio format: Sample rate\") yield UInt32(self, \"bit_rate\", \"Audio format:", "\"max_byte_per_sec\", \"Maximum byte per second\") yield NullBytes(self, \"reserved\", 4) #", "ffmpeg library http://ffmpeg.mplayerhq.hu/ - Video for Windows Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt", "text: text.upper()) else: yield field yield UInt32(self, \"flags\", \"Stream flags\")", "8*8), (\"ACONanih\", 8*8), ), \"description\": \"Microsoft RIFF container\" } VALID_TYPES", "stream\") def parseAviHeader(self): yield UInt32(self, \"microsec_per_frame\", \"Microsecond per frame\") yield", "(\"avi_hdr\", parseAviHeader, \"AVI header\"), \"idx1\": (\"index\", parseIndex, \"Stream index\"), \"dmlh\":", "UInt32(self, \"cy\") yield UInt32(self, \"bit_count\") yield UInt32(self, \"planes\") yield UInt32(self,", "\"length\") def parseODML(self): yield UInt32(self, \"total_frame\", \"Real number of frame", "\"strf\": (\"stream_fmt\", parseAVIStreamFormat, \"Stream format\"), \"avih\": (\"avi_hdr\", parseAviHeader, \"AVI header\"),", "chunk type depending on file type try: chunk_cls = self.VALID_TYPES[self[\"type\"].value][0]", "\"\"\" sn = field.value return \"%04X-%04X\" % (sn >> 16,", "audio stream\") def parseAviHeader(self): yield UInt32(self, \"microsec_per_frame\", \"Microsecond per frame\")", "/ microsec) if \"total_frame\" in header and header[\"total_frame\"].value: delta =", "self.VALID_TYPES[self[\"type\"].value][1] except KeyError: return None def createDescription(self): tag = self[\"type\"].value", "yield UInt32(self, \"microsec_per_frame\", \"Microsecond per frame\") yield UInt32(self, \"max_byte_per_sec\", \"Maximum", "yield UInt32(self, \"planes\") yield UInt32(self, \"jiffie_rate\", \"Default Jiffies (1/60th of", "== \"LIST\": subtag = self[\"subtag\"].value if subtag in self.subtag_info: info", "type\" return True def createFields(self): yield String(self, \"signature\", 4, \"AVI", "number of frame of OpenDML video\") padding = self[\"size\"].value -", "=> \"0008-5C48\" \"\"\" sn = field.value return \"%04X-%04X\" % (sn", "is an animated cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm Authors: * <NAME> * <NAME>", "2005-06-21: creation of WAV parser by <NAME> * 2005-06-08: creation", "yield Bit(self, \"has_index\") yield Bit(self, \"must_use_index\") yield NullBits(self, \"reserved[]\", 2)", "8 tag = self[\"tag\"].value if tag in self.TAG_INFO: self.tag_info =", "yield NullBits(self, \"reserved[]\", 4) yield Bit(self, \"was_capture_file\") yield Bit(self, \"is_copyrighted\")", "streams\") yield UInt32(self, \"sug_buf_size\", \"Suggested buffer size\") yield UInt32(self, \"width\",", "\"index[]\") class Chunk(FieldSet): TAG_INFO = { # This dictionnary is", "(\"title\", parseText, \"Document title\"), \"IART\": (\"artist\", parseText, \"Artist\"), \"ICMT\": (\"comment\",", "channels placement bitmask\") yield UInt32(self, \"subformat\", \"Audio format: Subformat id\")", "String(self, \"type\", 4, \"Content type (\\\"AVI \\\", \\\"WAVE\\\", ...)\", charset=\"ASCII\")", "rectangle (bottom)\") class RedBook(FieldSet): \"\"\" RedBook offset parser, used in", "header list\"), \"movi\": (\"movie\", \"Movie stream\"), \"odml\": (\"odml\", \"ODML\"), }", "String, PaddingBytes, SubFile) from lib.hachoir_core.tools import alignValue, humanDuration from lib.hachoir_core.endian", "yield UInt32(self, \"sample_per_sec\", \"Sample per second\") yield UInt32(self, \"byte_per_sec\", \"Average", "4) yield Bit(self, \"has_index\") yield Bit(self, \"must_use_index\") yield NullBits(self, \"reserved[]\",", "yield UInt32(self, \"init_frame\", \"Initial frame (used in interleaved video)\") yield", "ChunkWAVE(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"format\", parseWAVFormat, \"Audio", "\"file_ext\": (\"avi\", \"cda\", \"wav\", \"ani\"), \"min_size\": 16*8, \"mime\": (u\"video/x-msvideo\", u\"audio/x-wav\",", "\"hdrl\": (\"headers\", \"Headers\"), \"strl\": (\"stream[]\", \"Stream header list\"), \"movi\": (\"movie\",", "Changelog: * 2007-03-30: support ACON (animated icons) * 2006-08-08: merge", "+ frame + 150 (from RB offset) HSG length =", "CD file (cda)\", \".cda\"), \"AVI \": (ChunkAVI, u\"video/x-msvideo\", u\"Microsoft AVI", "a second) if rate chunk not present\") yield Bit(self, \"is_icon\")", "WAV audio container * CDA file Documents: - libavformat source", "codec\"), audio_codec_name) yield UInt16(self, \"nb_channel\", \"Number of audio channel\") yield", "\"Size\")) if not self[\"size\"].value: return if self[\"tag\"].value == \"LIST\": yield", "+= \", %.1f fps\" % (1000000.0 / microsec) if \"total_frame\"", "\"Stream header\"), \"strf\": (\"stream_fmt\", parseAVIStreamFormat, \"Stream format\"), \"avih\": (\"avi_hdr\", parseAviHeader,", "(\"WAVEfmt \", 8*8), (\"CDDAfmt \", 8*8), (\"ACONanih\", 8*8), ), \"description\":", "(currently 1)\") yield UInt16(self, \"track_no\", \"Number of track\") yield textHandler(UInt32(self,", "Chunk(FieldSet): TAG_INFO = { # This dictionnary is edited by", "- 4 if 0 < padding: yield NullBytes(self, \"padding[]\", padding)", "\"Animation sequence\"), 'rate': (\"anim_rate\", parseAnimationRate, \"Animation sequence\"), 'icon': (\"icon[]\", parseIcon,", "\"Disc serial number\"), formatSerialNumber) yield UInt32(self, \"hsg_offset\", \"Track offset (HSG", "TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"format\", parseWAVFormat, \"Audio format\"),", "parseAnimationSequence(self): while not self.eof: yield UInt32(self, \"icon[]\") def formatJiffie(field): sec", "format: number of 1/75 second HSG offset = (minute*60 +", "\"ACON\": (ChunkACON, u\"image/x-ani\", u\"Microsoft Windows animated cursor\", \".ani\"), } endian", "\"is_copyrighted\") yield NullBits(self, \"reserved[]\", 14) yield UInt32(self, \"total_frame\", \"Total number", "\"headers/avi_hdr\" in self: header = self[\"headers/avi_hdr\"] desc += \": %ux%u", "WAV and CDA parsers into RIFF parser * 2006-08-03: creation", "NullBits(self, \"reserved[]\", 4) yield Bit(self, \"was_capture_file\") yield Bit(self, \"is_copyrighted\") yield", "\"Video format: Image size\") yield UInt32(self, \"xpels_meter\", \"Video format: XPelsPerMeter\")", "Sample rate\") yield UInt32(self, \"bit_rate\", \"Audio format: Bit rate\") yield", "* 2007-03-30: support ACON (animated icons) * 2006-08-08: merge AVI,", "cursor\") yield UInt32(self, \"nb_step\", \"Number of Blits before the animation", "* 8 tag = self[\"tag\"].value if tag in self.TAG_INFO: self.tag_info", "Bit(self, \"is_interleaved\") yield NullBits(self, \"reserved[]\", 2) yield Bit(self, \"trust_cktype\") yield", "code, movie/field[]/tag.value[2:4]: # \"db\": \"Uncompressed video frame\", # \"dc\": \"Compressed", "yield field yield UInt32(self, \"flags\", \"Stream flags\") yield UInt16(self, \"priority\",", "offset (Red-book format)\") yield RedBook(self, \"rb_length\", \"Track length (Red-book format)\")", "format: XPelsPerMeter\") yield UInt32(self, \"ypels_meter\", \"Video format: YPelsPerMeter\") yield UInt32(self,", "http://www.opennet.ru/docs/formats/avi.txt - What is an animated cursor? http://www.gdgsoft.com/anituner/help/aniformat.htm Authors: *", "size) yield Enum(UInt16(self, \"codec\", \"Audio codec\"), audio_codec_name) yield UInt16(self, \"nb_channel\",", "strip=\"\\0\") yield UInt32(self, \"init_frames\", \"InitialFrames\") yield UInt32(self, \"scale\", \"Time scale\")", "CDA parsers into RIFF parser * 2006-08-03: creation of CDA", "Block align\") if size >= 16: yield UInt16(self, \"bits_per_sample\", \"Audio", "yield UInt32(self, \"hdr_size\", \"Size of header (36 bytes)\") if self[\"hdr_size\"].value", "36: self.warning(\"Animation header with unknown size (%s)\" % self[\"size\"].value) yield", "Parser from lib.hachoir_core.field import (FieldSet, ParserError, UInt8, UInt16, UInt32, Enum,", "8 return min(size, self.stream.size) def createFilenameSuffix(self): try: return self.VALID_TYPES[self[\"type\"].value][3] except", "format)\") yield RedBook(self, \"rb_offset\", \"Track offset (Red-book format)\") yield RedBook(self,", "(ChunkACON, u\"image/x-ani\", u\"Microsoft Windows animated cursor\", \".ani\"), } endian =", "LITTLE_ENDIAN from lib.hachoir_core.text_handler import filesizeHandler, textHandler from lib.hachoir_parser.video.fourcc import audio_codec_name,", "\"tag\", 4, \"Tag\", charset=\"ASCII\") yield filesizeHandler(UInt32(self, \"size\", \"Size\")) if not", "of track\") yield textHandler(UInt32(self, \"disc_serial\", \"Disc serial number\"), formatSerialNumber) yield", "(36 bytes)\") if self[\"hdr_size\"].value != 36: self.warning(\"Animation header with unknown", "u\"video/x-msvideo\", u\"Microsoft AVI video\", \".avi\"), \"ACON\": (ChunkACON, u\"image/x-ani\", u\"Microsoft Windows", "NullBytes(self, \"reserved\", 4) # Flags yield NullBits(self, \"reserved[]\", 4) yield", "\"reserved\", 4) # Flags yield NullBits(self, \"reserved[]\", 4) yield Bit(self,", "return \"%04X-%04X\" % (sn >> 16, sn & 0xFFFF) def", "yield UInt8(self, \"minute\") yield PaddingBytes(self, \"notused\", 1) def formatSerialNumber(field): \"\"\"", "Eg. 0x00085C48 => \"0008-5C48\" \"\"\" sn = field.value return \"%04X-%04X\"", "# FIXME: Use regex \"RIFF.{4}(WAVE|CDDA|AVI )\" \"magic\": ( (\"AVI LIST\",", "yield RawBytes(self, \"raw_format\", size) def parseVideoFormat(self, size): yield UInt32(self, \"video_size\",", "if info[1] <= size: handler = info[0] for field in", "yield UInt32(self, \"video_size\", \"Video format: Size\") yield UInt32(self, \"width\", \"Video", "charset=\"ASCII\") yield UInt32(self, \"flags\") yield UInt32(self, \"start\", \"Offset from start", "tag == \"LIST\": subtag = self[\"subtag\"].value if subtag in self.subtag_info:", "number\"), formatSerialNumber) yield UInt32(self, \"hsg_offset\", \"Track offset (HSG format)\") yield", "handler = info[0] for field in handler(self, size): yield field", "None) def createFields(self): yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield", "\"Compressed video frame\", # \"wb\": \"Audio data\", # \"pc\": \"Palette", "Bit(self, \"has_index\") yield Bit(self, \"must_use_index\") yield NullBits(self, \"reserved[]\", 2) yield", "offset (HSG format)\") yield UInt32(self, \"hsg_length\", \"Track length (HSG format)\")", "buffer size\") yield UInt32(self, \"quality\", \"Stream quality\") yield UInt32(self, \"sample_size\",", "size: handler = info[0] for field in handler(self, size): yield", "\"minute\") yield PaddingBytes(self, \"notused\", 1) def formatSerialNumber(field): \"\"\" Format an", "RIFF parser, able to parse: * AVI video container *", "\"start\", \"Offset from start of movie data\") yield UInt32(self, \"length\")", "parser_class=IcoFile) class ChunkACON(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'anih': (\"anim_hdr\", parseAnimationHeader,", "\"Audio format\"), 'fact': (\"nb_sample\", parseWAVFact, \"Number of samples\"), 'data': (\"audio_data\",", "strip=\" \\0\", charset=\"ASCII\") if self[\"stream_type\"].value == \"vids\": yield Enum(field, video_fourcc_name,", "yield UInt8(self, \"second\") yield UInt8(self, \"minute\") yield PaddingBytes(self, \"notused\", 1)", "of CDA parser by <NAME> * 2005-06-21: creation of WAV", "try: return self.VALID_TYPES[self[\"type\"].value][1] except KeyError: return None def createDescription(self): tag", "charset=\"ASCII\", strip=\"\\0\") yield UInt32(self, \"init_frames\", \"InitialFrames\") yield UInt32(self, \"scale\", \"Time", "except KeyError: return u\"Microsoft RIFF container\" def createContentSize(self): size =", "length (unit: rate/scale)\") yield UInt32(self, \"buf_size\", \"Suggested buffer size\") yield", "\"reserved\", \"Audio format: \") yield UInt32(self, \"channel_mask\", \"Audio format: channels", "http://www.gdgsoft.com/anituner/help/aniformat.htm Authors: * <NAME> * <NAME> * <NAME> Changelog: *", "creation of AVI parser by <NAME> and <NAME> Thanks to:", "alignValue, humanDuration from lib.hachoir_core.endian import LITTLE_ENDIAN from lib.hachoir_core.text_handler import filesizeHandler,", "def parseText(self): yield String(self, \"text\", self[\"size\"].value, strip=\" \\0\", truncate=\"\\0\", charset=\"ISO-8859-1\")", "file Documents: - libavformat source code from ffmpeg library http://ffmpeg.mplayerhq.hu/", "TAG_INFO.update({ 'fmt ': (\"cdda\", parseCDDA, \"CD audio informations\"), }) class", "\"ypels_meter\", \"Video format: YPelsPerMeter\") yield UInt32(self, \"clr_used\", \"Video format: ClrUsed\")", "# Choose chunk type depending on file type try: chunk_cls", "parseText(self): yield String(self, \"text\", self[\"size\"].value, strip=\" \\0\", truncate=\"\\0\", charset=\"ISO-8859-1\") def", "u\"audio/x-cda\"), # FIXME: Use regex \"RIFF.{4}(WAVE|CDDA|AVI )\" \"magic\": ( (\"AVI", "yield PaddingBytes(self, \"notused\", 1) def formatSerialNumber(field): \"\"\" Format an disc", "second) if rate chunk not present\") yield Bit(self, \"is_icon\") yield", "of Blits before the animation cycles\") yield UInt32(self, \"cx\") yield", "format: Width\") yield UInt32(self, \"height\", \"Video format: Height\") yield UInt16(self,", "while self.current_size < self[\"filesize\"].value*8+8: yield chunk_cls(self, \"chunk[]\") if not self.eof:", "4, \"Sub-tag\", charset=\"ASCII\") handler = self.tag_info[1] while 8 < (self.size", "self[\"hdr_size\"].value != 36: self.warning(\"Animation header with unknown size (%s)\" %", "container\" } VALID_TYPES = { \"WAVE\": (ChunkWAVE, u\"audio/x-wav\", u\"Microsoft WAVE", "textHandler from lib.hachoir_parser.video.fourcc import audio_codec_name, video_fourcc_name from lib.hachoir_parser.image.ico import IcoFile", "audio informations\"), }) class ChunkWAVE(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt", "number. Eg. 0x00085C48 => \"0008-5C48\" \"\"\" sn = field.value return", "up to filesize while self.current_size < self[\"filesize\"].value*8+8: yield chunk_cls(self, \"chunk[]\")", "format: Size\") yield UInt32(self, \"width\", \"Video format: Width\") yield UInt32(self,", "Bit(self, \"trust_cktype\") yield NullBits(self, \"reserved[]\", 4) yield Bit(self, \"was_capture_file\") yield", "\"Sample per second\") yield UInt32(self, \"byte_per_sec\", \"Average byte per second\")", "(\"avi\", \"cda\", \"wav\", \"ani\"), \"min_size\": 16*8, \"mime\": (u\"video/x-msvideo\", u\"audio/x-wav\", u\"audio/x-cda\"),", "!= 56: raise ParserError(\"Invalid stream header size\") yield String(self, \"stream_type\",", "(FieldSet, ParserError, UInt8, UInt16, UInt32, Enum, Bit, NullBits, NullBytes, RawBytes,", "def createFields(self): yield String(self, \"tag\", 4, \"Tag\", charset=\"ASCII\") yield filesizeHandler(UInt32(self,", "lib.hachoir_core.tools import alignValue, humanDuration from lib.hachoir_core.endian import LITTLE_ENDIAN from lib.hachoir_core.text_handler", "\"Total number of frames in the video\") yield UInt32(self, \"init_frame\",", "(info[0], None, info[1]) self._name = self.tag_info[0] self._description = self.tag_info[2] else:", "= { \"INFO\": (\"info\", \"File informations\"), \"hdrl\": (\"headers\", \"Headers\"), \"strl\":", "Subformat id\") def parseAVIStreamFormat(self): size = self[\"size\"].value strtype = self[\"../stream_hdr/stream_type\"].value", "UInt32(self, \"cx\") yield UInt32(self, \"cy\") yield UInt32(self, \"bit_count\") yield UInt32(self,", "self[\"tag\"].value if tag in self.TAG_INFO: self.tag_info = self.TAG_INFO[tag] if tag", "UInt32(self, \"scale\") yield UInt32(self, \"rate\") yield UInt32(self, \"start\") yield UInt32(self,", "(from RB length) \"\"\" yield UInt16(self, \"cda_version\", \"CD file version", "NullBits(self, \"reserved[]\", 2) yield Bit(self, \"trust_cktype\") yield NullBits(self, \"reserved[]\", 4)", "format: channels placement bitmask\") yield UInt32(self, \"subformat\", \"Audio format: Subformat", "= { \"WAVE\": (ChunkWAVE, u\"audio/x-wav\", u\"Microsoft WAVE audio\", \".wav\"), \"CDDA\":", "\"Number of streams\") yield UInt32(self, \"sug_buf_size\", \"Suggested buffer size\") yield", "\"Sub-field list\"), \"JUNK\": (\"junk[]\", None, \"Junk (padding)\"), # Metadata \"INAM\":", "if microsec: desc += \", %.1f fps\" % (1000000.0 /", "(animated icons) * 2006-08-08: merge AVI, WAV and CDA parsers", "movie/field[]/tag.value[2:4]: # \"db\": \"Uncompressed video frame\", # \"dc\": \"Compressed video", "createContentSize(self): size = (self[\"filesize\"].value + 8) * 8 return min(size,", "UInt32(self, \"width\", \"Video format: Width\") yield UInt32(self, \"height\", \"Video format:", "lib.hachoir_parser.image.ico import IcoFile from datetime import timedelta def parseText(self): yield", "2) yield Bit(self, \"is_interleaved\") yield NullBits(self, \"reserved[]\", 2) yield Bit(self,", "String(self, \"text\", self[\"size\"].value, strip=\" \\0\", truncate=\"\\0\", charset=\"ISO-8859-1\") def parseRawFormat(self, size):", "UInt16, UInt32, Enum, Bit, NullBits, NullBytes, RawBytes, String, PaddingBytes, SubFile)", "pixel\") yield UInt32(self, \"height\", \"Height in pixel\") yield UInt32(self, \"scale\")", "class ChunkCDDA(Chunk): TAG_INFO = Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"cdda\", parseCDDA,", "strtype = self[\"../stream_hdr/stream_type\"].value TYPE_HANDLER = { \"vids\": (parseVideoFormat, 40), \"auds\":", "<NAME> * 2005-06-21: creation of WAV parser by <NAME> *", "Chunk.TAG_INFO.copy() TAG_INFO.update({ 'fmt ': (\"cdda\", parseCDDA, \"CD audio informations\"), })", "self.eof: yield AVIIndexEntry(self, \"index[]\") class Chunk(FieldSet): TAG_INFO = { #", "\"Stream length (unit: rate/scale)\") yield UInt32(self, \"buf_size\", \"Suggested buffer size\")", "16, sn & 0xFFFF) def parseCDDA(self): \"\"\" HSG address format:", "tag = self[\"tag\"].value if tag in self.TAG_INFO: self.tag_info = self.TAG_INFO[tag]", "format: Size of extra information\") if size >= 28: #", "field = self.__class__(self, \"field[]\") yield field if (field.size/8) % 2", "per sample\") def parseWAVFact(self): yield UInt32(self, \"nb_sample\", \"Number of samples", "UInt32(self, \"bit_count\") yield UInt32(self, \"planes\") yield UInt32(self, \"jiffie_rate\", \"Default Jiffies" ]
[ "return re.sub( r'([^\\s\\w]|_)+', u' ', line.replace('\\n', ' ').replace('\\t', ' '),", "for sublist in list_of_lines for val in sublist] return filter(lambda", "replace_unwanted_characters(line: str) -> str: return re.sub( r'([^\\s\\w]|_)+', u' ', line.replace('\\n',", "list_of_lines for val in sublist] return filter(lambda x: x !=", "str: return group_path.split(\"\\\\\")[-1] def replace_unwanted_characters(line: str) -> str: return re.sub(", "def clean_document(document_file) -> list: document = document_file.read().lower().split(\"\\n\\n\") cleaned_lines = list(map(replace_unwanted_characters,", "find subfolders of :return: list of relative paths to any", "of :return: list of relative paths to any subfolders \"\"\"", "folder_relative_path: Relative path of folder to find subfolders of :return:", "if f.is_dir()] def get_group_name(group_path: str) -> str: return group_path.split(\"\\\\\")[-1] def", "= document_file.read().lower().split(\"\\n\\n\") cleaned_lines = list(map(replace_unwanted_characters, document[1:])) # lambda x, y:", "group_path.split(\"\\\\\")[-1] def replace_unwanted_characters(line: str) -> str: return re.sub( r'([^\\s\\w]|_)+', u'", "get_group_name(group_path: str) -> str: return group_path.split(\"\\\\\")[-1] def replace_unwanted_characters(line: str) ->", "for f in os.scandir(folder_relative_path) if f.is_dir()] def get_group_name(group_path: str) ->", "Relative path of folder to find subfolders of :return: list", "map(lambda x: x.split(\" \"), cleaned_lines) flattened_list_of_lines = [val for sublist", "import os import re def get_subfolder_paths(folder_relative_path: str) -> list: \"\"\"", "of folder to find subfolders of :return: list of relative", "flags=re.UNICODE ) def clean_document(document_file) -> list: document = document_file.read().lower().split(\"\\n\\n\") cleaned_lines", "'), flags=re.UNICODE ) def clean_document(document_file) -> list: document = document_file.read().lower().split(\"\\n\\n\")", "b list_of_lines = map(lambda x: x.split(\" \"), cleaned_lines) flattened_list_of_lines =", "re def get_subfolder_paths(folder_relative_path: str) -> list: \"\"\" Gets all subfolders", "[f.path for f in os.scandir(folder_relative_path) if f.is_dir()] def get_group_name(group_path: str)", "[val for sublist in list_of_lines for val in sublist] return", "a, b list_of_lines = map(lambda x: x.split(\" \"), cleaned_lines) flattened_list_of_lines", "get_subfolder_paths(folder_relative_path: str) -> list: \"\"\" Gets all subfolders of a", "u' ', line.replace('\\n', ' ').replace('\\t', ' '), flags=re.UNICODE ) def", "' ').replace('\\t', ' '), flags=re.UNICODE ) def clean_document(document_file) -> list:", "-> str: return re.sub( r'([^\\s\\w]|_)+', u' ', line.replace('\\n', ' ').replace('\\t',", "+ y, a, b list_of_lines = map(lambda x: x.split(\" \"),", "x.split(\" \"), cleaned_lines) flattened_list_of_lines = [val for sublist in list_of_lines", "list of relative paths to any subfolders \"\"\" return [f.path", "\"\"\" Gets all subfolders of a given path :param folder_relative_path:", "= list(map(replace_unwanted_characters, document[1:])) # lambda x, y: x + y,", "cleaned_lines = list(map(replace_unwanted_characters, document[1:])) # lambda x, y: x +", "all subfolders of a given path :param folder_relative_path: Relative path", "document_file.read().lower().split(\"\\n\\n\") cleaned_lines = list(map(replace_unwanted_characters, document[1:])) # lambda x, y: x", "' '), flags=re.UNICODE ) def clean_document(document_file) -> list: document =", "list(map(replace_unwanted_characters, document[1:])) # lambda x, y: x + y, a,", "list_of_lines = map(lambda x: x.split(\" \"), cleaned_lines) flattened_list_of_lines = [val", "').replace('\\t', ' '), flags=re.UNICODE ) def clean_document(document_file) -> list: document", "to find subfolders of :return: list of relative paths to", "cleaned_lines) flattened_list_of_lines = [val for sublist in list_of_lines for val", "path :param folder_relative_path: Relative path of folder to find subfolders", "= [val for sublist in list_of_lines for val in sublist]", "given path :param folder_relative_path: Relative path of folder to find", "def get_group_name(group_path: str) -> str: return group_path.split(\"\\\\\")[-1] def replace_unwanted_characters(line: str)", "line.replace('\\n', ' ').replace('\\t', ' '), flags=re.UNICODE ) def clean_document(document_file) ->", "subfolders of a given path :param folder_relative_path: Relative path of", "str) -> str: return group_path.split(\"\\\\\")[-1] def replace_unwanted_characters(line: str) -> str:", "in os.scandir(folder_relative_path) if f.is_dir()] def get_group_name(group_path: str) -> str: return", "document[1:])) # lambda x, y: x + y, a, b", "-> str: return group_path.split(\"\\\\\")[-1] def replace_unwanted_characters(line: str) -> str: return", "str: return re.sub( r'([^\\s\\w]|_)+', u' ', line.replace('\\n', ' ').replace('\\t', '", ":param folder_relative_path: Relative path of folder to find subfolders of", "y, a, b list_of_lines = map(lambda x: x.split(\" \"), cleaned_lines)", "<filename>Utils.py import os import re def get_subfolder_paths(folder_relative_path: str) -> list:", "import re def get_subfolder_paths(folder_relative_path: str) -> list: \"\"\" Gets all", "= map(lambda x: x.split(\" \"), cleaned_lines) flattened_list_of_lines = [val for", "return [f.path for f in os.scandir(folder_relative_path) if f.is_dir()] def get_group_name(group_path:", "of a given path :param folder_relative_path: Relative path of folder", ") def clean_document(document_file) -> list: document = document_file.read().lower().split(\"\\n\\n\") cleaned_lines =", "val in sublist] return filter(lambda x: x != '', flattened_list_of_lines)", "-> list: \"\"\" Gets all subfolders of a given path", "document = document_file.read().lower().split(\"\\n\\n\") cleaned_lines = list(map(replace_unwanted_characters, document[1:])) # lambda x,", "str) -> list: \"\"\" Gets all subfolders of a given", "in list_of_lines for val in sublist] return filter(lambda x: x", "def replace_unwanted_characters(line: str) -> str: return re.sub( r'([^\\s\\w]|_)+', u' ',", "sublist in list_of_lines for val in sublist] return filter(lambda x:", "for val in sublist] return filter(lambda x: x != '',", "os.scandir(folder_relative_path) if f.is_dir()] def get_group_name(group_path: str) -> str: return group_path.split(\"\\\\\")[-1]", "of relative paths to any subfolders \"\"\" return [f.path for", "Gets all subfolders of a given path :param folder_relative_path: Relative", "', line.replace('\\n', ' ').replace('\\t', ' '), flags=re.UNICODE ) def clean_document(document_file)", "-> list: document = document_file.read().lower().split(\"\\n\\n\") cleaned_lines = list(map(replace_unwanted_characters, document[1:])) #", "any subfolders \"\"\" return [f.path for f in os.scandir(folder_relative_path) if", "x, y: x + y, a, b list_of_lines = map(lambda", "def get_subfolder_paths(folder_relative_path: str) -> list: \"\"\" Gets all subfolders of", "path of folder to find subfolders of :return: list of", "os import re def get_subfolder_paths(folder_relative_path: str) -> list: \"\"\" Gets", "folder to find subfolders of :return: list of relative paths", "str) -> str: return re.sub( r'([^\\s\\w]|_)+', u' ', line.replace('\\n', '", "relative paths to any subfolders \"\"\" return [f.path for f", "paths to any subfolders \"\"\" return [f.path for f in", "r'([^\\s\\w]|_)+', u' ', line.replace('\\n', ' ').replace('\\t', ' '), flags=re.UNICODE )", "flattened_list_of_lines = [val for sublist in list_of_lines for val in", "list: \"\"\" Gets all subfolders of a given path :param", "re.sub( r'([^\\s\\w]|_)+', u' ', line.replace('\\n', ' ').replace('\\t', ' '), flags=re.UNICODE", ":return: list of relative paths to any subfolders \"\"\" return", "to any subfolders \"\"\" return [f.path for f in os.scandir(folder_relative_path)", "y: x + y, a, b list_of_lines = map(lambda x:", "list: document = document_file.read().lower().split(\"\\n\\n\") cleaned_lines = list(map(replace_unwanted_characters, document[1:])) # lambda", "subfolders of :return: list of relative paths to any subfolders", "subfolders \"\"\" return [f.path for f in os.scandir(folder_relative_path) if f.is_dir()]", "f in os.scandir(folder_relative_path) if f.is_dir()] def get_group_name(group_path: str) -> str:", "# lambda x, y: x + y, a, b list_of_lines", "f.is_dir()] def get_group_name(group_path: str) -> str: return group_path.split(\"\\\\\")[-1] def replace_unwanted_characters(line:", "a given path :param folder_relative_path: Relative path of folder to", "return group_path.split(\"\\\\\")[-1] def replace_unwanted_characters(line: str) -> str: return re.sub( r'([^\\s\\w]|_)+',", "\"), cleaned_lines) flattened_list_of_lines = [val for sublist in list_of_lines for", "clean_document(document_file) -> list: document = document_file.read().lower().split(\"\\n\\n\") cleaned_lines = list(map(replace_unwanted_characters, document[1:]))", "\"\"\" return [f.path for f in os.scandir(folder_relative_path) if f.is_dir()] def", "lambda x, y: x + y, a, b list_of_lines =", "x + y, a, b list_of_lines = map(lambda x: x.split(\"", "x: x.split(\" \"), cleaned_lines) flattened_list_of_lines = [val for sublist in" ]
[ "back later.\".format(len(end), len(begin))) else: elapsed_time = 0 for i in", "begin.append(line[:23]) elif 'Index creation finished' in line: end.append(line[:23]) if len(begin)", "wrong. Please check debug.log\") elif len(begin) != len(end): print(\"{}/{} Done.", "begin = [] end = [] for line in log:", "= datetime.strptime(end[i],'%Y-%m-%d %H:%M:%S.%f') elapsed_time += (end_tmp-begin_tmp).total_seconds() print(\"Done in {} s\".format(elapsed_time))", "elif 'Index creation finished' in line: end.append(line[:23]) if len(begin) ==", "went wrong. Please check debug.log\") elif len(begin) != len(end): print(\"{}/{}", "!= len(end): print(\"{}/{} Done. Please come back later.\".format(len(end), len(begin))) else:", "len(end): print(\"{}/{} Done. Please come back later.\".format(len(end), len(begin))) else: elapsed_time", "datetime import datetime with open('/home/neo4j/neo4j-community-3.5.1/logs/debug.log', 'r') as log: begin =", "Please check debug.log\") elif len(begin) != len(end): print(\"{}/{} Done. Please", "end_tmp = datetime.strptime(end[i],'%Y-%m-%d %H:%M:%S.%f') elapsed_time += (end_tmp-begin_tmp).total_seconds() print(\"Done in {}", "come back later.\".format(len(end), len(begin))) else: elapsed_time = 0 for i", "in line: begin.append(line[:23]) elif 'Index creation finished' in line: end.append(line[:23])", "'r') as log: begin = [] end = [] for", "log: begin = [] end = [] for line in", "debug.log\") elif len(begin) != len(end): print(\"{}/{} Done. Please come back", "population started' in line: begin.append(line[:23]) elif 'Index creation finished' in", "[] for line in log: if 'Index population started' in", "= [] for line in log: if 'Index population started'", "or len(begin) > 9: print(\"Something went wrong. Please check debug.log\")", "[] end = [] for line in log: if 'Index", "as log: begin = [] end = [] for line", "len(begin) > 9: print(\"Something went wrong. Please check debug.log\") elif", "%H:%M:%S.%f') end_tmp = datetime.strptime(end[i],'%Y-%m-%d %H:%M:%S.%f') elapsed_time += (end_tmp-begin_tmp).total_seconds() print(\"Done in", "in log: if 'Index population started' in line: begin.append(line[:23]) elif", "9: print(\"Something went wrong. Please check debug.log\") elif len(begin) !=", "> 9: print(\"Something went wrong. Please check debug.log\") elif len(begin)", "print(\"Something went wrong. Please check debug.log\") elif len(begin) != len(end):", "Done. Please come back later.\".format(len(end), len(begin))) else: elapsed_time = 0", "0 for i in range(0,9): begin_tmp = datetime.strptime(begin[i], '%Y-%m-%d %H:%M:%S.%f')", "begin_tmp = datetime.strptime(begin[i], '%Y-%m-%d %H:%M:%S.%f') end_tmp = datetime.strptime(end[i],'%Y-%m-%d %H:%M:%S.%f') elapsed_time", "in line: end.append(line[:23]) if len(begin) == 0 or len(begin) >", "import datetime with open('/home/neo4j/neo4j-community-3.5.1/logs/debug.log', 'r') as log: begin = []", "= [] end = [] for line in log: if", "later.\".format(len(end), len(begin))) else: elapsed_time = 0 for i in range(0,9):", "Please come back later.\".format(len(end), len(begin))) else: elapsed_time = 0 for", "if len(begin) == 0 or len(begin) > 9: print(\"Something went", "if 'Index population started' in line: begin.append(line[:23]) elif 'Index creation", "end = [] for line in log: if 'Index population", "line in log: if 'Index population started' in line: begin.append(line[:23])", "elif len(begin) != len(end): print(\"{}/{} Done. Please come back later.\".format(len(end),", "else: elapsed_time = 0 for i in range(0,9): begin_tmp =", "from datetime import datetime with open('/home/neo4j/neo4j-community-3.5.1/logs/debug.log', 'r') as log: begin", "i in range(0,9): begin_tmp = datetime.strptime(begin[i], '%Y-%m-%d %H:%M:%S.%f') end_tmp =", "len(begin) == 0 or len(begin) > 9: print(\"Something went wrong.", "= datetime.strptime(begin[i], '%Y-%m-%d %H:%M:%S.%f') end_tmp = datetime.strptime(end[i],'%Y-%m-%d %H:%M:%S.%f') elapsed_time +=", "datetime.strptime(begin[i], '%Y-%m-%d %H:%M:%S.%f') end_tmp = datetime.strptime(end[i],'%Y-%m-%d %H:%M:%S.%f') elapsed_time += (end_tmp-begin_tmp).total_seconds()", "finished' in line: end.append(line[:23]) if len(begin) == 0 or len(begin)", "check debug.log\") elif len(begin) != len(end): print(\"{}/{} Done. Please come", "for line in log: if 'Index population started' in line:", "with open('/home/neo4j/neo4j-community-3.5.1/logs/debug.log', 'r') as log: begin = [] end =", "== 0 or len(begin) > 9: print(\"Something went wrong. Please", "len(begin) != len(end): print(\"{}/{} Done. Please come back later.\".format(len(end), len(begin)))", "print(\"{}/{} Done. Please come back later.\".format(len(end), len(begin))) else: elapsed_time =", "datetime with open('/home/neo4j/neo4j-community-3.5.1/logs/debug.log', 'r') as log: begin = [] end", "'Index population started' in line: begin.append(line[:23]) elif 'Index creation finished'", "= 0 for i in range(0,9): begin_tmp = datetime.strptime(begin[i], '%Y-%m-%d", "end.append(line[:23]) if len(begin) == 0 or len(begin) > 9: print(\"Something", "line: begin.append(line[:23]) elif 'Index creation finished' in line: end.append(line[:23]) if", "for i in range(0,9): begin_tmp = datetime.strptime(begin[i], '%Y-%m-%d %H:%M:%S.%f') end_tmp", "range(0,9): begin_tmp = datetime.strptime(begin[i], '%Y-%m-%d %H:%M:%S.%f') end_tmp = datetime.strptime(end[i],'%Y-%m-%d %H:%M:%S.%f')", "0 or len(begin) > 9: print(\"Something went wrong. Please check", "elapsed_time = 0 for i in range(0,9): begin_tmp = datetime.strptime(begin[i],", "log: if 'Index population started' in line: begin.append(line[:23]) elif 'Index", "in range(0,9): begin_tmp = datetime.strptime(begin[i], '%Y-%m-%d %H:%M:%S.%f') end_tmp = datetime.strptime(end[i],'%Y-%m-%d", "len(begin))) else: elapsed_time = 0 for i in range(0,9): begin_tmp", "'%Y-%m-%d %H:%M:%S.%f') end_tmp = datetime.strptime(end[i],'%Y-%m-%d %H:%M:%S.%f') elapsed_time += (end_tmp-begin_tmp).total_seconds() print(\"Done", "open('/home/neo4j/neo4j-community-3.5.1/logs/debug.log', 'r') as log: begin = [] end = []", "started' in line: begin.append(line[:23]) elif 'Index creation finished' in line:", "'Index creation finished' in line: end.append(line[:23]) if len(begin) == 0", "creation finished' in line: end.append(line[:23]) if len(begin) == 0 or", "line: end.append(line[:23]) if len(begin) == 0 or len(begin) > 9:" ]
[ "# package_data={}, package_data={\"school_sdk\": ['check_code/model.pkl']}, include_package_data=True, platforms='any', zip_safe=False, install_requires=[ 'requests', 'pyquery',", "], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers',", "Content', 'Topic :: Software Development :: Libraries :: Python Modules'", "'torchvision', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience ::", "System :: OS Independent', 'Programming Language :: Python :: 3.8',", "'Programming Language :: Python :: 3.8', 'Topic :: Internet ::", "= path.abspath(path.dirname(__file__)) with open(path.join(basedir, \"README.md\"), encoding='utf-8') as f: long_description =", "'Pillow', 'fake-headers', 'torch', 'torchvision', ], classifiers=[ 'Environment :: Web Environment',", ":: Python Modules' ] ) # python zf-setup.py bdist_wheel sdist", "'Environment :: Web Environment', 'Intended Audience :: Developers', 'License ::", "OSI Approved :: MIT License', 'Operating System :: OS Independent',", ":: 3.8', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',", ":: Dynamic Content', 'Topic :: Software Development :: Libraries ::", "package_data={}, package_data={\"school_sdk\": ['check_code/model.pkl']}, include_package_data=True, platforms='any', zip_safe=False, install_requires=[ 'requests', 'pyquery', 'bs4',", "package_data={\"school_sdk\": ['check_code/model.pkl']}, include_package_data=True, platforms='any', zip_safe=False, install_requires=[ 'requests', 'pyquery', 'bs4', 'Pillow',", "coding: utf-8 -*- ''' :file: setup.py :author: -Farmer :url: https://blog.farmer233.top", "license='MIT', author_email=\"<EMAIL>\", description=\"zf School SDK for Python\", long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk',", ":url: https://blog.farmer233.top :date: 2021/09/20 11:11:54 ''' from os import path", "'requests', 'pyquery', 'bs4', 'Pillow', 'fake-headers', 'torch', 'torchvision', ], classifiers=[ 'Environment", "encoding='utf-8') as f: long_description = f.read() setup( name=\"zf-school-sdk\", author=\"farmer.chillax\", version=\"1.3.2\",", "2021/09/20 11:11:54 ''' from os import path from setuptools import", "'torch', 'torchvision', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience", "platforms='any', zip_safe=False, install_requires=[ 'requests', 'pyquery', 'bs4', 'Pillow', 'fake-headers', 'torch', 'torchvision',", "MIT License', 'Operating System :: OS Independent', 'Programming Language ::", ":: OS Independent', 'Programming Language :: Python :: 3.8', 'Topic", "setup.py :author: -Farmer :url: https://blog.farmer233.top :date: 2021/09/20 11:11:54 ''' from", "basedir = path.abspath(path.dirname(__file__)) with open(path.join(basedir, \"README.md\"), encoding='utf-8') as f: long_description", "packages=find_packages(), # package_data={}, package_data={\"school_sdk\": ['check_code/model.pkl']}, include_package_data=True, platforms='any', zip_safe=False, install_requires=[ 'requests',", "'Intended Audience :: Developers', 'License :: OSI Approved :: MIT", "Language :: Python :: 3.8', 'Topic :: Internet :: WWW/HTTP", "Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved", ":: Web Environment', 'Intended Audience :: Developers', 'License :: OSI", ":: Developers', 'License :: OSI Approved :: MIT License', 'Operating", "open(path.join(basedir, \"README.md\"), encoding='utf-8') as f: long_description = f.read() setup( name=\"zf-school-sdk\",", "'Topic :: Software Development :: Libraries :: Python Modules' ]", "include_package_data=True, platforms='any', zip_safe=False, install_requires=[ 'requests', 'pyquery', 'bs4', 'Pillow', 'fake-headers', 'torch',", "School SDK for Python\", long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(), # package_data={},", "path.abspath(path.dirname(__file__)) with open(path.join(basedir, \"README.md\"), encoding='utf-8') as f: long_description = f.read()", "long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(), # package_data={}, package_data={\"school_sdk\": ['check_code/model.pkl']}, include_package_data=True, platforms='any',", "long_description = f.read() setup( name=\"zf-school-sdk\", author=\"farmer.chillax\", version=\"1.3.2\", license='MIT', author_email=\"<EMAIL>\", description=\"zf", ":: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software", "Approved :: MIT License', 'Operating System :: OS Independent', 'Programming", "utf-8 -*- ''' :file: setup.py :author: -Farmer :url: https://blog.farmer233.top :date:", ":: Libraries :: Python Modules' ] ) # python zf-setup.py", "-*- ''' :file: setup.py :author: -Farmer :url: https://blog.farmer233.top :date: 2021/09/20", "f.read() setup( name=\"zf-school-sdk\", author=\"farmer.chillax\", version=\"1.3.2\", license='MIT', author_email=\"<EMAIL>\", description=\"zf School SDK", "OS Independent', 'Programming Language :: Python :: 3.8', 'Topic ::", "'Operating System :: OS Independent', 'Programming Language :: Python ::", ":file: setup.py :author: -Farmer :url: https://blog.farmer233.top :date: 2021/09/20 11:11:54 '''", "with open(path.join(basedir, \"README.md\"), encoding='utf-8') as f: long_description = f.read() setup(", "'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic ::", "Python Modules' ] ) # python zf-setup.py bdist_wheel sdist #", ":date: 2021/09/20 11:11:54 ''' from os import path from setuptools", "License', 'Operating System :: OS Independent', 'Programming Language :: Python", ":: OSI Approved :: MIT License', 'Operating System :: OS", "Dynamic Content', 'Topic :: Software Development :: Libraries :: Python", "['check_code/model.pkl']}, include_package_data=True, platforms='any', zip_safe=False, install_requires=[ 'requests', 'pyquery', 'bs4', 'Pillow', 'fake-headers',", "author=\"farmer.chillax\", version=\"1.3.2\", license='MIT', author_email=\"<EMAIL>\", description=\"zf School SDK for Python\", long_description=long_description,", "author_email=\"<EMAIL>\", description=\"zf School SDK for Python\", long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(),", "Developers', 'License :: OSI Approved :: MIT License', 'Operating System", "Libraries :: Python Modules' ] ) # python zf-setup.py bdist_wheel", "-Farmer :url: https://blog.farmer233.top :date: 2021/09/20 11:11:54 ''' from os import", "Modules' ] ) # python zf-setup.py bdist_wheel sdist # twine", "import path from setuptools import setup, find_packages basedir = path.abspath(path.dirname(__file__))", "f: long_description = f.read() setup( name=\"zf-school-sdk\", author=\"farmer.chillax\", version=\"1.3.2\", license='MIT', author_email=\"<EMAIL>\",", "description=\"zf School SDK for Python\", long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(), #", "WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries", "''' from os import path from setuptools import setup, find_packages", "'fake-headers', 'torch', 'torchvision', ], classifiers=[ 'Environment :: Web Environment', 'Intended", "from setuptools import setup, find_packages basedir = path.abspath(path.dirname(__file__)) with open(path.join(basedir,", "3.8', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic", "= f.read() setup( name=\"zf-school-sdk\", author=\"farmer.chillax\", version=\"1.3.2\", license='MIT', author_email=\"<EMAIL>\", description=\"zf School", "Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development", "https://blog.farmer233.top :date: 2021/09/20 11:11:54 ''' from os import path from", "11:11:54 ''' from os import path from setuptools import setup,", "name=\"zf-school-sdk\", author=\"farmer.chillax\", version=\"1.3.2\", license='MIT', author_email=\"<EMAIL>\", description=\"zf School SDK for Python\",", "setup, find_packages basedir = path.abspath(path.dirname(__file__)) with open(path.join(basedir, \"README.md\"), encoding='utf-8') as", ":: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development ::", "'pyquery', 'bs4', 'Pillow', 'fake-headers', 'torch', 'torchvision', ], classifiers=[ 'Environment ::", "as f: long_description = f.read() setup( name=\"zf-school-sdk\", author=\"farmer.chillax\", version=\"1.3.2\", license='MIT',", ":: Python :: 3.8', 'Topic :: Internet :: WWW/HTTP ::", "from os import path from setuptools import setup, find_packages basedir", "for Python\", long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(), # package_data={}, package_data={\"school_sdk\": ['check_code/model.pkl']},", "'License :: OSI Approved :: MIT License', 'Operating System ::", ") # python zf-setup.py bdist_wheel sdist # twine upload dist/*", "version=\"1.3.2\", license='MIT', author_email=\"<EMAIL>\", description=\"zf School SDK for Python\", long_description=long_description, long_description_content_type='text/markdown',", "install_requires=[ 'requests', 'pyquery', 'bs4', 'Pillow', 'fake-headers', 'torch', 'torchvision', ], classifiers=[", "'bs4', 'Pillow', 'fake-headers', 'torch', 'torchvision', ], classifiers=[ 'Environment :: Web", "find_packages basedir = path.abspath(path.dirname(__file__)) with open(path.join(basedir, \"README.md\"), encoding='utf-8') as f:", "zip_safe=False, install_requires=[ 'requests', 'pyquery', 'bs4', 'Pillow', 'fake-headers', 'torch', 'torchvision', ],", "Environment', 'Intended Audience :: Developers', 'License :: OSI Approved ::", "Independent', 'Programming Language :: Python :: 3.8', 'Topic :: Internet", "path from setuptools import setup, find_packages basedir = path.abspath(path.dirname(__file__)) with", "-*- coding: utf-8 -*- ''' :file: setup.py :author: -Farmer :url:", "setuptools import setup, find_packages basedir = path.abspath(path.dirname(__file__)) with open(path.join(basedir, \"README.md\"),", ":author: -Farmer :url: https://blog.farmer233.top :date: 2021/09/20 11:11:54 ''' from os", ":: Software Development :: Libraries :: Python Modules' ] )", ":: MIT License', 'Operating System :: OS Independent', 'Programming Language", "Python\", long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(), # package_data={}, package_data={\"school_sdk\": ['check_code/model.pkl']}, include_package_data=True,", "# -*- coding: utf-8 -*- ''' :file: setup.py :author: -Farmer", "Python :: 3.8', 'Topic :: Internet :: WWW/HTTP :: Dynamic", "url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(), # package_data={}, package_data={\"school_sdk\": ['check_code/model.pkl']}, include_package_data=True, platforms='any', zip_safe=False, install_requires=[", "Audience :: Developers', 'License :: OSI Approved :: MIT License',", "] ) # python zf-setup.py bdist_wheel sdist # twine upload", "import setup, find_packages basedir = path.abspath(path.dirname(__file__)) with open(path.join(basedir, \"README.md\"), encoding='utf-8')", "SDK for Python\", long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(), # package_data={}, package_data={\"school_sdk\":", "long_description_content_type='text/markdown', url='https://github.com/Farmer-chong/new-school-sdk', packages=find_packages(), # package_data={}, package_data={\"school_sdk\": ['check_code/model.pkl']}, include_package_data=True, platforms='any', zip_safe=False,", "<filename>zf-setup.py<gh_stars>0 # -*- coding: utf-8 -*- ''' :file: setup.py :author:", "Software Development :: Libraries :: Python Modules' ] ) #", "classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License", "os import path from setuptools import setup, find_packages basedir =", "''' :file: setup.py :author: -Farmer :url: https://blog.farmer233.top :date: 2021/09/20 11:11:54", "Development :: Libraries :: Python Modules' ] ) # python", "setup( name=\"zf-school-sdk\", author=\"farmer.chillax\", version=\"1.3.2\", license='MIT', author_email=\"<EMAIL>\", description=\"zf School SDK for", "\"README.md\"), encoding='utf-8') as f: long_description = f.read() setup( name=\"zf-school-sdk\", author=\"farmer.chillax\"," ]
[ "4, '7': 5, '8': 6, '9': 7, '10': 8, 'J':", "[-1, -1, -1, -1], 'hand': [-1, -1, -1] } }", "'9': 20, '10': 21, 'J': 22, 'Q': 23, 'K': 24,", "'Q': 23, 'K': 24, 'A': 25 } # Heart Red", "Heart Red = { '2': 26, '3': 27, '4': 28,", "'player2': { 'head': [-1, -1, -1], 'mid': [-1, -1, -1,", "44, '8': 45, '9': 46, '10': 47, 'J': 48, 'Q':", "'8': 45, '9': 46, '10': 47, 'J': 48, 'Q': 49,", "'4': 28, '5': 29, '6': 30, '7': 31, '8': 32,", "'5': 3, '6': 4, '7': 5, '8': 6, '9': 7,", "8, 'J': 9, 'Q': 10, 'K': 11, 'A': 12 }", "'K': 11, 'A': 12 } # Plum Green = {", "# Plum Green = { '2': 13, '3': 14, '4':", "43, '7': 44, '8': 45, '9': 46, '10': 47, 'J':", "'K': 50, 'A': 51 } POKER_SCOPE = [ '2', '3',", "'A': 25 } # Heart Red = { '2': 26,", "-1] }, 'player2': { 'head': [-1, -1, -1], 'mid': [-1,", "'tail': [-1, -1, -1, -1, -1], 'drop': [-1, -1, -1,", "-1, -1, -1], 'hand': [-1, -1, -1] }, 'player2': {", "'4': 41, '5': 42, '6': 43, '7': 44, '8': 45,", "'7': 31, '8': 32, '9': 33, '10': 34, 'J': 35,", "29, '6': 30, '7': 31, '8': 32, '9': 33, '10':", "'8': 6, '9': 7, '10': 8, 'J': 9, 'Q': 10,", "'drop': [-1, -1, -1, -1], 'hand': [-1, -1, -1] },", "'6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A' ]", "-1, -1, -1, -1], 'tail': [-1, -1, -1, -1, -1],", "-1, -1], 'hand': [-1, -1, -1] } } # Square", "48, 'Q': 49, 'K': 50, 'A': 51 } POKER_SCOPE =", "} # Spade Black = { '2': 39, '3': 40,", "5, '8': 6, '9': 7, '10': 8, 'J': 9, 'Q':", "# Heart Red = { '2': 26, '3': 27, '4':", "[-1, -1, -1, -1], 'hand': [-1, -1, -1] }, 'player2':", "'10': 47, 'J': 48, 'Q': 49, 'K': 50, 'A': 51", "[-1, -1, -1, -1, -1], 'tail': [-1, -1, -1, -1,", "'K': 24, 'A': 25 } # Heart Red = {", "=> RGB蓝色(Blue) # Plum 梅花 => pl => RGB绿色(Green) #", "= { '2': 0, '3': 1, '4': 2, '5': 3,", "=> sq => RGB蓝色(Blue) # Plum 梅花 => pl =>", "19, '9': 20, '10': 21, 'J': 22, 'Q': 23, 'K':", "-1, -1], 'tail': [-1, -1, -1, -1, -1], 'drop': [-1,", "RGB绿色(Green) # Spade 黑桃 => sp => RGB黑色(Black) # Heart", "50, 'A': 51 } POKER_SCOPE = [ '2', '3', '4',", "-1, -1], 'mid': [-1, -1, -1, -1, -1], 'tail': [-1,", "= { 'local': { 'head': [-1, -1, -1], 'mid': [-1,", "49, 'K': 50, 'A': 51 } POKER_SCOPE = [ '2',", "'hand': [-1, -1, -1] }, 'player1': { 'head': [-1, -1,", "RGB红色(Red) init_poker = { 'local': { 'head': [-1, -1, -1],", "=> RGB绿色(Green) # Spade 黑桃 => sp => RGB黑色(Black) #", "'10': 8, 'J': 9, 'Q': 10, 'K': 11, 'A': 12", "17, '7': 18, '8': 19, '9': 20, '10': 21, 'J':", "22, 'Q': 23, 'K': 24, 'A': 25 } # Heart", "}, 'player2': { 'head': [-1, -1, -1], 'mid': [-1, -1,", "-1], 'mid': [-1, -1, -1, -1, -1], 'tail': [-1, -1,", "'6': 17, '7': 18, '8': 19, '9': 20, '10': 21,", "33, '10': 34, 'J': 35, 'Q': 36, 'K': 37, 'A':", "}, 'player1': { 'head': [-1, -1, -1], 'mid': [-1, -1,", "'player1': { 'head': [-1, -1, -1], 'mid': [-1, -1, -1,", "'2': 39, '3': 40, '4': 41, '5': 42, '6': 43,", "{ '2': 13, '3': 14, '4': 15, '5': 16, '6':", "POKER_SCOPE = [ '2', '3', '4', '5', '6', '7', '8',", "sp => RGB黑色(Black) # Heart 红桃 => he => RGB红色(Red)", "'2': 0, '3': 1, '4': 2, '5': 3, '6': 4,", "47, 'J': 48, 'Q': 49, 'K': 50, 'A': 51 }", "30, '7': 31, '8': 32, '9': 33, '10': 34, 'J':", "18, '8': 19, '9': 20, '10': 21, 'J': 22, 'Q':", "[ '2', '3', '4', '5', '6', '7', '8', '9', '10',", "梅花 => pl => RGB绿色(Green) # Spade 黑桃 => sp", "-1, -1], 'drop': [-1, -1, -1, -1], 'hand': [-1, -1,", "-1, -1] }, 'player1': { 'head': [-1, -1, -1], 'mid':", "Red = { '2': 26, '3': 27, '4': 28, '5':", "=> pl => RGB绿色(Green) # Spade 黑桃 => sp =>", "} POKER_SCOPE = [ '2', '3', '4', '5', '6', '7',", "sq => RGB蓝色(Blue) # Plum 梅花 => pl => RGB绿色(Green)", "7, '10': 8, 'J': 9, 'Q': 10, 'K': 11, 'A':", "2, '5': 3, '6': 4, '7': 5, '8': 6, '9':", "34, 'J': 35, 'Q': 36, 'K': 37, 'A': 38 }", "'hand': [-1, -1, -1] } } # Square Blue =", "-1], 'hand': [-1, -1, -1] }, 'player2': { 'head': [-1,", "13, '3': 14, '4': 15, '5': 16, '6': 17, '7':", "24, 'A': 25 } # Heart Red = { '2':", "'Q': 49, 'K': 50, 'A': 51 } POKER_SCOPE = [", "9, 'Q': 10, 'K': 11, 'A': 12 } # Plum", "[-1, -1, -1, -1], 'hand': [-1, -1, -1] }, 'player1':", "he => RGB红色(Red) init_poker = { 'local': { 'head': [-1,", "init_poker = { 'local': { 'head': [-1, -1, -1], 'mid':", "'K': 37, 'A': 38 } # Spade Black = {", "=> he => RGB红色(Red) init_poker = { 'local': { 'head':", "41, '5': 42, '6': 43, '7': 44, '8': 45, '9':", "-1] } } # Square Blue = { '2': 0,", "0, '3': 1, '4': 2, '5': 3, '6': 4, '7':", "42, '6': 43, '7': 44, '8': 45, '9': 46, '10':", "21, 'J': 22, 'Q': 23, 'K': 24, 'A': 25 }", "'4': 15, '5': 16, '6': 17, '7': 18, '8': 19,", "'2': 26, '3': 27, '4': 28, '5': 29, '6': 30,", "'A': 12 } # Plum Green = { '2': 13,", "'A': 38 } # Spade Black = { '2': 39,", "35, 'Q': 36, 'K': 37, 'A': 38 } # Spade", "pl => RGB绿色(Green) # Spade 黑桃 => sp => RGB黑色(Black)", "{ 'head': [-1, -1, -1], 'mid': [-1, -1, -1, -1,", "'Q': 10, 'K': 11, 'A': 12 } # Plum Green", "-1, -1] }, 'player2': { 'head': [-1, -1, -1], 'mid':", "Square 方片 => sq => RGB蓝色(Blue) # Plum 梅花 =>", "=> sp => RGB黑色(Black) # Heart 红桃 => he =>", "'local': { 'head': [-1, -1, -1], 'mid': [-1, -1, -1,", "'6': 30, '7': 31, '8': 32, '9': 33, '10': 34,", "'J': 22, 'Q': 23, 'K': 24, 'A': 25 } #", "{ '2': 0, '3': 1, '4': 2, '5': 3, '6':", "'7': 18, '8': 19, '9': 20, '10': 21, 'J': 22,", "{ '2': 39, '3': 40, '4': 41, '5': 42, '6':", "15, '5': 16, '6': 17, '7': 18, '8': 19, '9':", "Black = { '2': 39, '3': 40, '4': 41, '5':", "'10': 21, 'J': 22, 'Q': 23, 'K': 24, 'A': 25", "# Square 方片 => sq => RGB蓝色(Blue) # Plum 梅花", "'mid': [-1, -1, -1, -1, -1], 'tail': [-1, -1, -1,", "-1], 'hand': [-1, -1, -1] } } # Square Blue", "37, 'A': 38 } # Spade Black = { '2':", "25 } # Heart Red = { '2': 26, '3':", "=> RGB红色(Red) init_poker = { 'local': { 'head': [-1, -1,", "'3': 27, '4': 28, '5': 29, '6': 30, '7': 31,", "} # Plum Green = { '2': 13, '3': 14,", "Blue = { '2': 0, '3': 1, '4': 2, '5':", "'8': 19, '9': 20, '10': 21, 'J': 22, 'Q': 23,", "28, '5': 29, '6': 30, '7': 31, '8': 32, '9':", "'5': 16, '6': 17, '7': 18, '8': 19, '9': 20,", "= { '2': 13, '3': 14, '4': 15, '5': 16,", "# Spade Black = { '2': 39, '3': 40, '4':", "= { '2': 39, '3': 40, '4': 41, '5': 42,", "'3': 1, '4': 2, '5': 3, '6': 4, '7': 5,", "Spade Black = { '2': 39, '3': 40, '4': 41,", "46, '10': 47, 'J': 48, 'Q': 49, 'K': 50, 'A':", "# Plum 梅花 => pl => RGB绿色(Green) # Spade 黑桃", "Spade 黑桃 => sp => RGB黑色(Black) # Heart 红桃 =>", "'9': 33, '10': 34, 'J': 35, 'Q': 36, 'K': 37,", "'9': 46, '10': 47, 'J': 48, 'Q': 49, 'K': 50,", "Plum Green = { '2': 13, '3': 14, '4': 15,", "'J': 35, 'Q': 36, 'K': 37, 'A': 38 } #", "Square Blue = { '2': 0, '3': 1, '4': 2,", "{ 'local': { 'head': [-1, -1, -1], 'mid': [-1, -1,", "-1], 'hand': [-1, -1, -1] }, 'player1': { 'head': [-1,", "6, '9': 7, '10': 8, 'J': 9, 'Q': 10, 'K':", "31, '8': 32, '9': 33, '10': 34, 'J': 35, 'Q':", "-1, -1] } } # Square Blue = { '2':", "Heart 红桃 => he => RGB红色(Red) init_poker = { 'local':", "51 } POKER_SCOPE = [ '2', '3', '4', '5', '6',", "-1, -1], 'hand': [-1, -1, -1] }, 'player1': { 'head':", "-1], 'tail': [-1, -1, -1, -1, -1], 'drop': [-1, -1,", "[-1, -1, -1, -1, -1], 'drop': [-1, -1, -1, -1],", "Green = { '2': 13, '3': 14, '4': 15, '5':", "{ '2': 26, '3': 27, '4': 28, '5': 29, '6':", "'7': 5, '8': 6, '9': 7, '10': 8, 'J': 9,", "'8': 32, '9': 33, '10': 34, 'J': 35, 'Q': 36,", "# Spade 黑桃 => sp => RGB黑色(Black) # Heart 红桃", "-1, -1, -1, -1], 'drop': [-1, -1, -1, -1], 'hand':", "# Square Blue = { '2': 0, '3': 1, '4':", "36, 'K': 37, 'A': 38 } # Spade Black =", "20, '10': 21, 'J': 22, 'Q': 23, 'K': 24, 'A':", "} # Square Blue = { '2': 0, '3': 1,", "'5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'", "<gh_stars>1-10 # Square 方片 => sq => RGB蓝色(Blue) # Plum", "} } # Square Blue = { '2': 0, '3':", "} # Heart Red = { '2': 26, '3': 27,", "'3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q',", "'4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K',", "RGB蓝色(Blue) # Plum 梅花 => pl => RGB绿色(Green) # Spade", "-1, -1, -1], 'hand': [-1, -1, -1] } } #", "40, '4': 41, '5': 42, '6': 43, '7': 44, '8':", "10, 'K': 11, 'A': 12 } # Plum Green =", "'2': 13, '3': 14, '4': 15, '5': 16, '6': 17,", "16, '6': 17, '7': 18, '8': 19, '9': 20, '10':", "'4': 2, '5': 3, '6': 4, '7': 5, '8': 6,", "'J': 48, 'Q': 49, 'K': 50, 'A': 51 } POKER_SCOPE", "'2', '3', '4', '5', '6', '7', '8', '9', '10', 'J',", "'3': 40, '4': 41, '5': 42, '6': 43, '7': 44,", "'10': 34, 'J': 35, 'Q': 36, 'K': 37, 'A': 38", "14, '4': 15, '5': 16, '6': 17, '7': 18, '8':", "[-1, -1, -1], 'mid': [-1, -1, -1, -1, -1], 'tail':", "'A': 51 } POKER_SCOPE = [ '2', '3', '4', '5',", "'Q': 36, 'K': 37, 'A': 38 } # Spade Black", "-1] }, 'player1': { 'head': [-1, -1, -1], 'mid': [-1,", "'5': 29, '6': 30, '7': 31, '8': 32, '9': 33,", "黑桃 => sp => RGB黑色(Black) # Heart 红桃 => he", "'drop': [-1, -1, -1, -1], 'hand': [-1, -1, -1] }", "[-1, -1, -1] } } # Square Blue = {", "-1, -1, -1], 'tail': [-1, -1, -1, -1, -1], 'drop':", "'6': 43, '7': 44, '8': 45, '9': 46, '10': 47,", "'7': 44, '8': 45, '9': 46, '10': 47, 'J': 48,", "-1, -1], 'hand': [-1, -1, -1] }, 'player2': { 'head':", "'head': [-1, -1, -1], 'mid': [-1, -1, -1, -1, -1],", "[-1, -1, -1] }, 'player1': { 'head': [-1, -1, -1],", "RGB黑色(Black) # Heart 红桃 => he => RGB红色(Red) init_poker =", "-1, -1, -1], 'hand': [-1, -1, -1] }, 'player1': {", "26, '3': 27, '4': 28, '5': 29, '6': 30, '7':", "'9': 7, '10': 8, 'J': 9, 'Q': 10, 'K': 11,", "12 } # Plum Green = { '2': 13, '3':", "= { '2': 26, '3': 27, '4': 28, '5': 29,", "[-1, -1, -1] }, 'player2': { 'head': [-1, -1, -1],", "Plum 梅花 => pl => RGB绿色(Green) # Spade 黑桃 =>", "45, '9': 46, '10': 47, 'J': 48, 'Q': 49, 'K':", "'3': 14, '4': 15, '5': 16, '6': 17, '7': 18,", "'hand': [-1, -1, -1] }, 'player2': { 'head': [-1, -1,", "32, '9': 33, '10': 34, 'J': 35, 'Q': 36, 'K':", "-1, -1, -1], 'drop': [-1, -1, -1, -1], 'hand': [-1,", "11, 'A': 12 } # Plum Green = { '2':", "38 } # Spade Black = { '2': 39, '3':", "=> RGB黑色(Black) # Heart 红桃 => he => RGB红色(Red) init_poker", "= [ '2', '3', '4', '5', '6', '7', '8', '9',", "'J': 9, 'Q': 10, 'K': 11, 'A': 12 } #", "红桃 => he => RGB红色(Red) init_poker = { 'local': {", "27, '4': 28, '5': 29, '6': 30, '7': 31, '8':", "23, 'K': 24, 'A': 25 } # Heart Red =", "# Heart 红桃 => he => RGB红色(Red) init_poker = {", "'5': 42, '6': 43, '7': 44, '8': 45, '9': 46,", "1, '4': 2, '5': 3, '6': 4, '7': 5, '8':", "3, '6': 4, '7': 5, '8': 6, '9': 7, '10':", "'6': 4, '7': 5, '8': 6, '9': 7, '10': 8,", "-1], 'drop': [-1, -1, -1, -1], 'hand': [-1, -1, -1]", "39, '3': 40, '4': 41, '5': 42, '6': 43, '7':", "方片 => sq => RGB蓝色(Blue) # Plum 梅花 => pl" ]
[]
[ "of key/value header data. Returns: dict: The restructured header data.", "'REMOTE_ADDR': message.get('remoteAddress', ''), # 'REMOTE_HOST': message.get('remoteAddress', ''), 'REQUEST_METHOD': method.upper(), 'SCRIPT_NAME':", "1 { \"command\": \"RunService\", \"apiToken\": \"abc123\", \"bodyVariable\": \"request.body\", \"headers\": [", "# add event to kwargs for blocking kwargs['request_key'] = request_key", "in bd: self.log.error(f'unhandled type - {type(b)}') else: self.log.error(f'unhandled type -", "# wait for thread event - (set on body write)", "'SERVER_NAME': '', 'SERVER_PORT': '', 'SERVER_PROTOCOL': 'HTTP/1.1', } # Add user", "+= bd.read() elif isinstance(bd, bytes): body += bd.decode() elif isinstance(bd,", "name='response-handler', target=self.process_run_service_response, args=args, kwargs=kwargs, ) if callable(self.api_event_callback): try: body_data: Any", "responses. ('200 OK', [('content-type', 'application/json'), ('content-length', '103')]) \"\"\" self.log.info('feature=api-service, event=response-received,", "dir - {dir(body)}') # write body to Redis self.key_value_store.create(request_key, 'response.body',", "= {'Errors': 0, 'Requests': 0, 'Responses': 0} # config callbacks", "service event responses. ('200 OK', [('content-type', 'application/json'), ('content-length', '103')]) \"\"\"", "} Args: message: The message payload from the server topic.", "Any from .common_service import CommonService class ApiService(CommonService): \"\"\"TcEx Framework API", "dict: \"\"\"Convert name/value array to a query string. Args: headers:", "for b in bd: self.log.error(f'unhandled type - {type(b)}') else: self.log.error(f'unhandled", "try: environ = { 'wsgi.errors': sys.stderr, 'wsgi.input': body, 'wsgi.multithread': True,", "import BytesIO from typing import Any from .common_service import CommonService", "string. Args: headers: The dict header data to be converted", "error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def process_run_service_response(self, *args, **kwargs) ->", "make values from message available in env in camel #", "(e.g., falcon -> req.env.get('request_url)) for key, value in message.items(): if", "for the request. Returns: str: The query params reformatted as", "process_run_service_response(self, *args, **kwargs) -> None: \"\"\"Handle service event responses. ('200", "on body write) self.log.trace(f'feature=api-service, event=response, args={args}') try: status_code, status =", "\"\"\"TcEx Framework API Service module.\"\"\" def __init__(self, tcex: object): \"\"\"Initialize", "for the current Service type.\"\"\" command_map = super().command_map command_map.update({'runservice': self.process_run_service_command})", "BytesIO from typing import Any from .common_service import CommonService class", "-> dict: \"\"\"Convert name/value array to a headers dict. Args:", "# set thread event to True to trigger response self.log.info('feature=api-service,", "Exception as e: self.log.error( f'feature=api-service, event=api-event-callback-failed, error=\"\"\"{e}\"\"\".' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors')", "Framework API Service module.\"\"\" def __init__(self, tcex: object): \"\"\"Initialize the", "read body from redis body_variable: str = message.pop('bodyVariable', None) if", "\"headers\": [ { key/value pairs } ], \"method\": \"GET\", \"queryParams\":", "list): for b in bd: self.log.error(f'unhandled type - {type(b)}') else:", "# add headers if headers.get('content-type') is not None: environ['CONTENT_TYPE'] =", "# make values from message available in env in camel", "the Class properties. Args: tcex: Instance of TcEx. \"\"\" super().__init__(tcex)", "a query string. Args: params: The query params for the", "None: environ['CONTENT_TYPE'] = headers.pop('content-type') # add content length if headers.get('content-length')", "message.pop('method') params: dict = message.pop('queryParams') path: str = message.pop('path') try:", "message.get('remoteAddress', ''), # 'REMOTE_HOST': message.get('remoteAddress', ''), 'REQUEST_METHOD': method.upper(), 'SCRIPT_NAME': '/',", "event=runservice-command, message=\"{message}\"') # thread event used to block response until", "The dict header data to be converted to key/value pairs.", "'SERVER_PORT': '', 'SERVER_PROTOCOL': 'HTTP/1.1', } # Add user config for", "to kwargs for blocking kwargs['request_key'] = request_key self.service_thread( name='response-handler', target=self.process_run_service_response,", "# pylint: disable=cell-var-from-loop 'status': status, 'statusCode': status_code, 'type': 'RunService', }", "be converted to key/value pairs. Returns: dict: The restructured header", "'', 'SERVER_PORT': '', 'SERVER_PROTOCOL': 'HTTP/1.1', } # Add user config", "error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) headers: dict = self.format_request_headers(message.pop('headers')) method: str = message.pop('method')", "typing import Any from .common_service import CommonService class ApiService(CommonService): \"\"\"TcEx", "Framework API Service module.\"\"\" # standard library import json import", "} # Add user config for TAXII or other service", "hasattr(body_data, 'read'): body = body_data.read() elif isinstance(body_data, list): for bd", "\"TLP:RED\" }], } Args: message: The message payload from the", "tcex: object): \"\"\"Initialize the Class properties. Args: tcex: Instance of", "'103')]) \"\"\" self.log.info('feature=api-service, event=response-received, status=waiting-for-body') kwargs.get('event').wait(30) # wait for thread", "def response_handler(*args, **kwargs): # pylint: disable=unused-argument \"\"\"Handle WSGI Response\"\"\" kwargs['event']", "headers: The dict of key/value header data. Returns: dict: The", "add event to kwargs for blocking kwargs['request_key'] = request_key self.service_thread(", "format_request_headers(self, headers: dict) -> dict: \"\"\"Convert name/value array to a", "e: self.log.error(f'feature=api-service, event=failed-reading-body, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) headers: dict = self.format_request_headers(message.pop('headers')) method:", "__init__(self, tcex: object): \"\"\"Initialize the Class properties. Args: tcex: Instance", "h[0], 'value': h[1]}) except AttributeError as e: self.log.error( f'feature=api-service, event=bad-headers-provided,", "headers_.setdefault(h.get('name').lower(), str(h.get('value'))) except AttributeError as e: self.log.error( f'feature=api-service, event=bad-headers-provided, '", "stop processing def response_handler(*args, **kwargs): # pylint: disable=unused-argument \"\"\"Handle WSGI", "key/value pairs } ], \"method\": \"GET\", \"queryParams\": [ { key/value", "{ \"command\": \"RunService\", \"apiToken\": \"abc123\", \"bodyVariable\": \"request.body\", \"headers\": [ {", "encoded body = BytesIO(body) except Exception as e: self.log.error(f'feature=api-service, event=failed-reading-body,", "= message.pop('method') params: dict = message.pop('queryParams') path: str = message.pop('path')", "Exception as e: self.log.error(f'feature=api-service, event=failed-building-environ, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) self.increment_metric('Errors') return #", "import Any from .common_service import CommonService class ApiService(CommonService): \"\"\"TcEx Framework", "'wsgi.version': (1, 0), 'PATH_INFO': path, 'QUERY_STRING': self.format_query_string(params), 'REMOTE_ADDR': message.get('remoteAddress', ''),", "type - {type(body)}') self.log.error(f'unhandled type dir - {dir(body)}') # write", "from typing import Any from .common_service import CommonService class ApiService(CommonService):", "'RunService', } self.log.info('feature=api-service, event=response-sent') self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic) self.increment_metric('Responses') except Exception as", "-> dict: \"\"\"Convert name/value array to a query string. Args:", "self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'), # pylint: disable=cell-var-from-loop 'status': status, 'statusCode': status_code,", "def format_query_string(self, params: dict) -> str: \"\"\"Convert name/value array to", "False, 'wsgi.run_once': True, 'wsgi.url_scheme': 'https', 'wsgi.version': (1, 0), 'PATH_INFO': path,", "event = threading.Event() # process message request_key: str = message.get('requestKey')", "= {} try: for h in headers: # TODO: either", "message.pop('queryParams') path: str = message.pop('path') try: environ = { 'wsgi.errors':", "= message.pop('queryParams') path: str = message.pop('path') try: environ = {", "{ key/value pairs } ], \"requestKey\": \"123abc\", \"userConfig\": [{ \"name\":", "body += bd.decode() elif isinstance(bd, list): for b in bd:", "except Exception as e: self.log.error( f'feature=api-service, event=failed-creating-response-body, error=\"\"\"{e}\"\"\"' ) self.log.trace(traceback.format_exc())", "{ 'bodyVariable': 'response.body', 'command': 'Acknowledged', 'headers': self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'), #", "response_handler ) # process body body = '' if hasattr(body_data,", "params: The query params for the request. Returns: str: The", "written event = threading.Event() # process message request_key: str =", "body_data: Any = self.api_event_callback( # pylint: disable=not-callable environ, response_handler )", "\"\"\"Convert name/value array to a query string. Args: params: The", "-> str: \"\"\"Convert name/value array to a query string. Args:", "self.log.error(f'feature=api-service, event=failed-reading-body, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) headers: dict = self.format_request_headers(message.pop('headers')) method: str", "try: for q in params: query_string.append(f'''{q.get('name')}={q.get('value')}''') except AttributeError as e:", "OK', [('content-type', 'application/json'), ('content-length', '103')]) \"\"\" self.log.info('feature=api-service, event=response-received, status=waiting-for-body') kwargs.get('event').wait(30)", "self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic) self.increment_metric('Responses') except Exception as e: self.log.error( f'feature=api-service, event=failed-creating-response-body,", "for h in headers: # TODO: either support tuple or", "# 'REMOTE_HOST': message.get('remoteAddress', ''), 'REQUEST_METHOD': method.upper(), 'SCRIPT_NAME': '/', 'SERVER_NAME': '',", "params: dict) -> str: \"\"\"Convert name/value array to a query", "environ: environ[self.tcex.utils.camel_to_snake(key)] = value self.log.trace(f'feature=api-service, environ={environ}') self.increment_metric('Requests') except Exception as", "bd.decode() elif isinstance(bd, list): for b in bd: self.log.error(f'unhandled type", "CommonService class ApiService(CommonService): \"\"\"TcEx Framework API Service module.\"\"\" def __init__(self,", "'', 'SERVER_PROTOCOL': 'HTTP/1.1', } # Add user config for TAXII", "= [] try: for q in params: query_string.append(f'''{q.get('name')}={q.get('value')}''') except AttributeError", "data to be converted to key/value pairs. Returns: dict: The", "code-block:: python :linenos: :lineno-start: 1 { \"command\": \"RunService\", \"apiToken\": \"abc123\",", "pairs } ], \"method\": \"GET\", \"queryParams\": [ { key/value pairs", "service that supports the data type environ['user_config'] = message.get('userConfig', [])", "Exception as e: self.log.error(f'feature=api-service, event=failed-reading-body, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) headers: dict =", "= event # add event to kwargs for blocking kwargs['request_key']", "Service type.\"\"\" command_map = super().command_map command_map.update({'runservice': self.process_run_service_command}) return command_map def", "value self.log.trace(f'feature=api-service, environ={environ}') self.increment_metric('Requests') except Exception as e: self.log.error(f'feature=api-service, event=failed-building-environ,", ") self.log.trace(traceback.format_exc()) return headers_ def format_response_headers(self, headers: dict) -> dict:", "array to a headers dict. Args: headers: The dict of", "event=failed-reading-body, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) headers: dict = self.format_request_headers(message.pop('headers')) method: str =", "in headers.items(): environ[f'HTTP_{header}'.upper()] = value # make values from message", "pairs } ], \"requestKey\": \"123abc\", \"userConfig\": [{ \"name\": \"tlpExportSetting\", \"value\":", "# stop processing def response_handler(*args, **kwargs): # pylint: disable=unused-argument \"\"\"Handle", "in Redis is not b64 encoded body = BytesIO(body) except", "restructured header data. \"\"\" headers_ = {} try: for h", "other service that supports the data type environ['user_config'] = message.get('userConfig',", "write body to Redis self.key_value_store.create(request_key, 'response.body', body) # set thread", "for API service the data in Redis is not b64", "**kwargs): # pylint: disable=unused-argument \"\"\"Handle WSGI Response\"\"\" kwargs['event'] = event", "error=\"\"\"{e}\"\"\"' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') def process_run_service_command(self, message: dict) -> None:", "import CommonService class ApiService(CommonService): \"\"\"TcEx Framework API Service module.\"\"\" def", "'wsgi.run_once': True, 'wsgi.url_scheme': 'https', 'wsgi.version': (1, 0), 'PATH_INFO': path, 'QUERY_STRING':", "'REQUEST_METHOD': method.upper(), 'SCRIPT_NAME': '/', 'SERVER_NAME': '', 'SERVER_PORT': '', 'SERVER_PROTOCOL': 'HTTP/1.1',", "add headers if headers.get('content-type') is not None: environ['CONTENT_TYPE'] = headers.pop('content-type')", "\"requestKey\": \"123abc\", \"userConfig\": [{ \"name\": \"tlpExportSetting\", \"value\": \"TLP:RED\" }], }", "tcex: Instance of TcEx. \"\"\" super().__init__(tcex) # properties self._metrics =", "event # add event to kwargs for blocking kwargs['request_key'] =", "return # stop processing def response_handler(*args, **kwargs): # pylint: disable=unused-argument", "= message.pop('bodyVariable', None) if body_variable is not None: body: Any", "error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) self.increment_metric('Errors') return # stop processing def response_handler(*args, **kwargs):", ") self.log.trace(traceback.format_exc()) return headers_ def process_run_service_response(self, *args, **kwargs) -> None:", "register config apiToken (before any logging) self.token.register_token( self.thread_name, message.get('apiToken'), message.get('expireSeconds')", "as e: self.log.error( f'feature=api-service, event=failed-creating-response-body, error=\"\"\"{e}\"\"\"' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') def", "- {dir(body)}') # write body to Redis self.key_value_store.create(request_key, 'response.body', body)", "command_map = super().command_map command_map.update({'runservice': self.process_run_service_command}) return command_map def format_query_string(self, params:", "try: status_code, status = args[0].split(' ', 1) response = {", "WSGI Response\"\"\" kwargs['event'] = event # add event to kwargs", "request. Returns: str: The query params reformatted as a string.", "if key not in environ and self.tcex.utils.camel_to_snake(key) not in environ:", "\"bodyVariable\": \"request.body\", \"headers\": [ { key/value pairs } ], \"method\":", "\"userConfig\": [{ \"name\": \"tlpExportSetting\", \"value\": \"TLP:RED\" }], } Args: message:", "}], } Args: message: The message payload from the server", "The restructured header data. \"\"\" headers_ = [] try: for", "event=response-received, status=waiting-for-body') kwargs.get('event').wait(30) # wait for thread event - (set", "'' if hasattr(body_data, 'read'): body = body_data.read() elif isinstance(body_data, list):", "length if headers.get('content-length') is not None: environ['CONTENT_LENGTH'] = headers.pop('content-length') for", "'Requests': 0, 'Responses': 0} # config callbacks self.api_event_callback = None", "string. \"\"\" query_string = [] try: for q in params:", "csv list of values # headers_.setdefault(h.get('name').lower(), []).append(h.get('value')) headers_.setdefault(h.get('name').lower(), str(h.get('value'))) except", "'wsgi.multiprocess': False, 'wsgi.run_once': True, 'wsgi.url_scheme': 'https', 'wsgi.version': (1, 0), 'PATH_INFO':", "= request_key self.service_thread( name='response-handler', target=self.process_run_service_response, args=args, kwargs=kwargs, ) if callable(self.api_event_callback):", "Args: tcex: Instance of TcEx. \"\"\" super().__init__(tcex) # properties self._metrics", ") self.log.info(f'feature=api-service, event=runservice-command, message=\"{message}\"') # thread event used to block", "disable=cell-var-from-loop 'status': status, 'statusCode': status_code, 'type': 'RunService', } self.log.info('feature=api-service, event=response-sent')", "body: Any = self.key_value_store.read(request_key, body_variable) if body is not None:", "TODO: either support tuple or csv list of values #", "the data type environ['user_config'] = message.get('userConfig', []) # add headers", "*args, **kwargs) -> None: \"\"\"Handle service event responses. ('200 OK',", "in environ and self.tcex.utils.camel_to_snake(key) not in environ: environ[self.tcex.utils.camel_to_snake(key)] = value", "'type': 'RunService', } self.log.info('feature=api-service, event=response-sent') self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic) self.increment_metric('Responses') except Exception", "self.log.info('feature=api-service, event=response-received, status=waiting-for-body') kwargs.get('event').wait(30) # wait for thread event -", "to block response until body is written event = threading.Event()", "response = { 'bodyVariable': 'response.body', 'command': 'Acknowledged', 'headers': self.format_response_headers(args[1]), 'requestKey':", "params: query_string.append(f'''{q.get('name')}={q.get('value')}''') except AttributeError as e: self.log.error( f'feature=api-service, event=bad-params-provided, params={params},", "'Acknowledged', 'headers': self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'), # pylint: disable=cell-var-from-loop 'status': status,", "query string. Args: params: The query params for the request.", "e: self.log.error(f'feature=api-service, event=failed-building-environ, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) self.increment_metric('Errors') return # stop processing", "Args: headers: The dict of key/value header data. Returns: dict:", "(set on body write) self.log.trace(f'feature=api-service, event=response, args={args}') try: status_code, status", "} ], \"requestKey\": \"123abc\", \"userConfig\": [{ \"name\": \"tlpExportSetting\", \"value\": \"TLP:RED\"", "key not in environ and self.tcex.utils.camel_to_snake(key) not in environ: environ[self.tcex.utils.camel_to_snake(key)]", "event - (set on body write) self.log.trace(f'feature=api-service, event=response, args={args}') try:", "headers: dict = self.format_request_headers(message.pop('headers')) method: str = message.pop('method') params: dict", "self.log.trace(traceback.format_exc()) headers: dict = self.format_request_headers(message.pop('headers')) method: str = message.pop('method') params:", "e: self.log.error( f'feature=api-service, event=bad-params-provided, params={params}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return '&'.join(query_string)", "dict = message.pop('queryParams') path: str = message.pop('path') try: environ =", "if callable(self.api_event_callback): try: body_data: Any = self.api_event_callback( # pylint: disable=not-callable", "return command_map def format_query_string(self, params: dict) -> str: \"\"\"Convert name/value", "as e: self.log.error(f'feature=api-service, event=failed-building-environ, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) self.increment_metric('Errors') return # stop", "The query params for the request. Returns: str: The query", "RunService command. .. code-block:: python :linenos: :lineno-start: 1 { \"command\":", "Exception as e: self.log.error( f'feature=api-service, event=failed-creating-response-body, error=\"\"\"{e}\"\"\"' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors')", "0, 'Requests': 0, 'Responses': 0} # config callbacks self.api_event_callback =", "dict) -> dict: \"\"\"Convert name/value array to a query string.", "message.get('requestKey') body = None try: # read body from redis", "either support tuple or csv list of values # headers_.setdefault(h.get('name').lower(),", "array to a query string. Args: params: The query params", "[] try: for h in headers: headers_.append({'name': h[0], 'value': h[1]})", "wait for thread event - (set on body write) self.log.trace(f'feature=api-service,", "headers: # TODO: either support tuple or csv list of", "str = message.pop('bodyVariable', None) if body_variable is not None: body:", "\"queryParams\": [ { key/value pairs } ], \"requestKey\": \"123abc\", \"userConfig\":", "# Add user config for TAXII or other service that", "(1, 0), 'PATH_INFO': path, 'QUERY_STRING': self.format_query_string(params), 'REMOTE_ADDR': message.get('remoteAddress', ''), #", "Any = self.key_value_store.read(request_key, body_variable) if body is not None: #", "name/value array to a query string. Args: headers: The dict", "body is written event = threading.Event() # process message request_key:", "\"name\": \"tlpExportSetting\", \"value\": \"TLP:RED\" }], } Args: message: The message", "set thread event to True to trigger response self.log.info('feature=api-service, event=response-body-written')", "the RunService command. .. code-block:: python :linenos: :lineno-start: 1 {", "json import sys import threading import traceback from io import", "= body_data.read() elif isinstance(body_data, list): for bd in body_data: if", "{'Errors': 0, 'Requests': 0, 'Responses': 0} # config callbacks self.api_event_callback", "Returns: dict: The restructured header data. \"\"\" headers_ = []", "event=bad-headers-provided, ' f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def process_run_service_response(self,", "values # headers_.setdefault(h.get('name').lower(), []).append(h.get('value')) headers_.setdefault(h.get('name').lower(), str(h.get('value'))) except AttributeError as e:", "f'feature=api-service, event=api-event-callback-failed, error=\"\"\"{e}\"\"\".' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') # unregister config apiToken", "[ { key/value pairs } ], \"requestKey\": \"123abc\", \"userConfig\": [{", "query_string.append(f'''{q.get('name')}={q.get('value')}''') except AttributeError as e: self.log.error( f'feature=api-service, event=bad-params-provided, params={params}, error=\"\"\"{e})\"\"\"'", ") self.log.trace(traceback.format_exc()) return '&'.join(query_string) def format_request_headers(self, headers: dict) -> dict:", "python :linenos: :lineno-start: 1 { \"command\": \"RunService\", \"apiToken\": \"abc123\", \"bodyVariable\":", "'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': True, 'wsgi.url_scheme': 'https', 'wsgi.version': (1,", "environ['user_config'] = message.get('userConfig', []) # add headers if headers.get('content-type') is", "{ 'wsgi.errors': sys.stderr, 'wsgi.input': body, 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once':", "disable=unused-argument \"\"\"Handle WSGI Response\"\"\" kwargs['event'] = event # add event", "pylint: disable=cell-var-from-loop 'status': status, 'statusCode': status_code, 'type': 'RunService', } self.log.info('feature=api-service,", "self.log.trace(traceback.format_exc()) return headers_ def process_run_service_response(self, *args, **kwargs) -> None: \"\"\"Handle", "a headers dict. Args: headers: The dict of key/value header", "self.log.error( f'feature=api-service, event=api-event-callback-failed, error=\"\"\"{e}\"\"\".' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') # unregister config", "# pylint: disable=not-callable environ, response_handler ) # process body body", "config callbacks self.api_event_callback = None @property def command_map(self) -> dict:", "= BytesIO(body) except Exception as e: self.log.error(f'feature=api-service, event=failed-reading-body, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc())", "status, 'statusCode': status_code, 'type': 'RunService', } self.log.info('feature=api-service, event=response-sent') self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic)", "for header, value in headers.items(): environ[f'HTTP_{header}'.upper()] = value # make", "self.increment_metric('Requests') except Exception as e: self.log.error(f'feature=api-service, event=failed-building-environ, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) self.increment_metric('Errors')", "data. Returns: dict: The restructured header data. \"\"\" headers_ =", "0} # config callbacks self.api_event_callback = None @property def command_map(self)", "env in camel # case (e.g., falcon -> req.env.get('request_url)) for", "message request_key: str = message.get('requestKey') body = None try: #", "header data. \"\"\" headers_ = {} try: for h in", "target=self.process_run_service_response, args=args, kwargs=kwargs, ) if callable(self.api_event_callback): try: body_data: Any =", "f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def process_run_service_response(self, *args, **kwargs)", "format_response_headers(self, headers: dict) -> dict: \"\"\"Convert name/value array to a", "isinstance(bd, list): for b in bd: self.log.error(f'unhandled type - {type(b)}')", "e: self.log.error( f'feature=api-service, event=api-event-callback-failed, error=\"\"\"{e}\"\"\".' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') # unregister", "headers_ = {} try: for h in headers: # TODO:", "server topic. \"\"\" # register config apiToken (before any logging)", "''), # 'REMOTE_HOST': message.get('remoteAddress', ''), 'REQUEST_METHOD': method.upper(), 'SCRIPT_NAME': '/', 'SERVER_NAME':", "{} try: for h in headers: # TODO: either support", "restructured header data. \"\"\" headers_ = [] try: for h", "None: \"\"\"Handle service event responses. ('200 OK', [('content-type', 'application/json'), ('content-length',", "body_variable: str = message.pop('bodyVariable', None) if body_variable is not None:", "None @property def command_map(self) -> dict: \"\"\"Return the command map", "or csv list of values # headers_.setdefault(h.get('name').lower(), []).append(h.get('value')) headers_.setdefault(h.get('name').lower(), str(h.get('value')))", "is written event = threading.Event() # process message request_key: str", "= message.get('requestKey') body = None try: # read body from", "], \"requestKey\": \"123abc\", \"userConfig\": [{ \"name\": \"tlpExportSetting\", \"value\": \"TLP:RED\" }],", "pylint: disable=not-callable environ, response_handler ) # process body body =", "redis body_variable: str = message.pop('bodyVariable', None) if body_variable is not", "body write) self.log.trace(f'feature=api-service, event=response, args={args}') try: status_code, status = args[0].split('", "value in headers.items(): environ[f'HTTP_{header}'.upper()] = value # make values from", "io import BytesIO from typing import Any from .common_service import", "API Service module.\"\"\" def __init__(self, tcex: object): \"\"\"Initialize the Class", "not in environ: environ[self.tcex.utils.camel_to_snake(key)] = value self.log.trace(f'feature=api-service, environ={environ}') self.increment_metric('Requests') except", "\"\"\"Handle WSGI Response\"\"\" kwargs['event'] = event # add event to", "' f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def process_run_service_response(self, *args,", "kwargs=kwargs, ) if callable(self.api_event_callback): try: body_data: Any = self.api_event_callback( #", "Redis is not b64 encoded body = BytesIO(body) except Exception", "<filename>tcex/services/api_service.py \"\"\"TcEx Framework API Service module.\"\"\" # standard library import", "self.log.trace(f'feature=api-service, environ={environ}') self.increment_metric('Requests') except Exception as e: self.log.error(f'feature=api-service, event=failed-building-environ, error=\"\"\"{e}\"\"\"')", "environ[f'HTTP_{header}'.upper()] = value # make values from message available in", "module.\"\"\" # standard library import json import sys import threading", "is not None: body: Any = self.key_value_store.read(request_key, body_variable) if body", "key/value header data. Returns: dict: The restructured header data. \"\"\"", "as a string. \"\"\" query_string = [] try: for q", "\"\"\"TcEx Framework API Service module.\"\"\" # standard library import json", "= headers.pop('content-type') # add content length if headers.get('content-length') is not", "threading.Event() # process message request_key: str = message.get('requestKey') body =", "headers if headers.get('content-type') is not None: environ['CONTENT_TYPE'] = headers.pop('content-type') #", "headers: dict) -> dict: \"\"\"Convert name/value array to a headers", "= super().command_map command_map.update({'runservice': self.process_run_service_command}) return command_map def format_query_string(self, params: dict)", "processing def response_handler(*args, **kwargs): # pylint: disable=unused-argument \"\"\"Handle WSGI Response\"\"\"", "**kwargs) -> None: \"\"\"Handle service event responses. ('200 OK', [('content-type',", "data. \"\"\" headers_ = {} try: for h in headers:", "from redis body_variable: str = message.pop('bodyVariable', None) if body_variable is", "\"request.body\", \"headers\": [ { key/value pairs } ], \"method\": \"GET\",", "Class properties. Args: tcex: Instance of TcEx. \"\"\" super().__init__(tcex) #", "if headers.get('content-length') is not None: environ['CONTENT_LENGTH'] = headers.pop('content-length') for header,", "'headers': self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'), # pylint: disable=cell-var-from-loop 'status': status, 'statusCode':", "def process_run_service_response(self, *args, **kwargs) -> None: \"\"\"Handle service event responses.", "body, 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': True, 'wsgi.url_scheme': 'https', 'wsgi.version':", "isinstance(bd, bytes): body += bd.decode() elif isinstance(bd, list): for b", "key/value pairs } ], \"requestKey\": \"123abc\", \"userConfig\": [{ \"name\": \"tlpExportSetting\",", "-> req.env.get('request_url)) for key, value in message.items(): if key not", "apiToken (before any logging) self.token.register_token( self.thread_name, message.get('apiToken'), message.get('expireSeconds') ) self.log.info(f'feature=api-service,", "request_key: str = message.get('requestKey') body = None try: # read", "# TODO: either support tuple or csv list of values", "pairs. Returns: dict: The restructured header data. \"\"\" headers_ =", "message.get('remoteAddress', ''), 'REQUEST_METHOD': method.upper(), 'SCRIPT_NAME': '/', 'SERVER_NAME': '', 'SERVER_PORT': '',", "self.tcex.utils.camel_to_snake(key) not in environ: environ[self.tcex.utils.camel_to_snake(key)] = value self.log.trace(f'feature=api-service, environ={environ}') self.increment_metric('Requests')", "-> dict: \"\"\"Return the command map for the current Service", "to Redis self.key_value_store.create(request_key, 'response.body', body) # set thread event to", "event=bad-params-provided, params={params}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return '&'.join(query_string) def format_request_headers(self, headers:", "converted to key/value pairs. Returns: dict: The restructured header data.", "\"\"\" # register config apiToken (before any logging) self.token.register_token( self.thread_name,", "# register config apiToken (before any logging) self.token.register_token( self.thread_name, message.get('apiToken'),", "self.service_thread( name='response-handler', target=self.process_run_service_response, args=args, kwargs=kwargs, ) if callable(self.api_event_callback): try: body_data:", "command_map.update({'runservice': self.process_run_service_command}) return command_map def format_query_string(self, params: dict) -> str:", "not None: environ['CONTENT_LENGTH'] = headers.pop('content-length') for header, value in headers.items():", "body body = '' if hasattr(body_data, 'read'): body = body_data.read()", "\"RunService\", \"apiToken\": \"abc123\", \"bodyVariable\": \"request.body\", \"headers\": [ { key/value pairs", "bd.read() elif isinstance(bd, bytes): body += bd.decode() elif isinstance(bd, list):", "reformatted as a string. \"\"\" query_string = [] try: for", "try: for h in headers: headers_.append({'name': h[0], 'value': h[1]}) except", "body = None try: # read body from redis body_variable:", "bd: self.log.error(f'unhandled type - {type(b)}') else: self.log.error(f'unhandled type - {type(body)}')", "\"value\": \"TLP:RED\" }], } Args: message: The message payload from", "'SCRIPT_NAME': '/', 'SERVER_NAME': '', 'SERVER_PORT': '', 'SERVER_PROTOCOL': 'HTTP/1.1', } #", "self.log.error( f'feature=api-service, event=bad-params-provided, params={params}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return '&'.join(query_string) def", "'application/json'), ('content-length', '103')]) \"\"\" self.log.info('feature=api-service, event=response-received, status=waiting-for-body') kwargs.get('event').wait(30) # wait", "if body is not None: # for API service the", "data. \"\"\" headers_ = [] try: for h in headers:", "'status': status, 'statusCode': status_code, 'type': 'RunService', } self.log.info('feature=api-service, event=response-sent') self.message_broker.publish(json.dumps(response),", "('200 OK', [('content-type', 'application/json'), ('content-length', '103')]) \"\"\" self.log.info('feature=api-service, event=response-received, status=waiting-for-body')", "for blocking kwargs['request_key'] = request_key self.service_thread( name='response-handler', target=self.process_run_service_response, args=args, kwargs=kwargs,", "list): for bd in body_data: if hasattr(bd, 'read'): body +=", "return '&'.join(query_string) def format_request_headers(self, headers: dict) -> dict: \"\"\"Convert name/value", "-> None: \"\"\"Process the RunService command. .. code-block:: python :linenos:", "'/', 'SERVER_NAME': '', 'SERVER_PORT': '', 'SERVER_PROTOCOL': 'HTTP/1.1', } # Add", "'SERVER_PROTOCOL': 'HTTP/1.1', } # Add user config for TAXII or", "# pylint: disable=unused-argument \"\"\"Handle WSGI Response\"\"\" kwargs['event'] = event #", "\"abc123\", \"bodyVariable\": \"request.body\", \"headers\": [ { key/value pairs } ],", "('content-length', '103')]) \"\"\" self.log.info('feature=api-service, event=response-received, status=waiting-for-body') kwargs.get('event').wait(30) # wait for", "except AttributeError as e: self.log.error( f'feature=api-service, event=bad-headers-provided, ' f'headers={headers}, error=\"\"\"{e})\"\"\"'", "if headers.get('content-type') is not None: environ['CONTENT_TYPE'] = headers.pop('content-type') # add", "message.items(): if key not in environ and self.tcex.utils.camel_to_snake(key) not in", "self.log.trace(f'feature=api-service, event=response, args={args}') try: status_code, status = args[0].split(' ', 1)", "TcEx. \"\"\" super().__init__(tcex) # properties self._metrics = {'Errors': 0, 'Requests':", "config apiToken (before any logging) self.token.register_token( self.thread_name, message.get('apiToken'), message.get('expireSeconds') )", "\"\"\"Convert name/value array to a headers dict. Args: headers: The", "= headers.pop('content-length') for header, value in headers.items(): environ[f'HTTP_{header}'.upper()] = value", "\"\"\" headers_ = [] try: for h in headers: headers_.append({'name':", "for h in headers: headers_.append({'name': h[0], 'value': h[1]}) except AttributeError", "type dir - {dir(body)}') # write body to Redis self.key_value_store.create(request_key,", "self.log.info('feature=api-service, event=response-sent') self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic) self.increment_metric('Responses') except Exception as e: self.log.error(", "bd in body_data: if hasattr(bd, 'read'): body += bd.read() elif", "e: self.log.error( f'feature=api-service, event=bad-headers-provided, ' f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return", "Instance of TcEx. \"\"\" super().__init__(tcex) # properties self._metrics = {'Errors':", "dict: The restructured header data. \"\"\" headers_ = {} try:", "self.process_run_service_command}) return command_map def format_query_string(self, params: dict) -> str: \"\"\"Convert", "is not None: # for API service the data in", "self.api_event_callback = None @property def command_map(self) -> dict: \"\"\"Return the", "''), 'REQUEST_METHOD': method.upper(), 'SCRIPT_NAME': '/', 'SERVER_NAME': '', 'SERVER_PORT': '', 'SERVER_PROTOCOL':", "falcon -> req.env.get('request_url)) for key, value in message.items(): if key", "None: # for API service the data in Redis is", "except AttributeError as e: self.log.error( f'feature=api-service, event=bad-params-provided, params={params}, error=\"\"\"{e})\"\"\"' )", "self.key_value_store.read(request_key, body_variable) if body is not None: # for API", "f'feature=api-service, event=failed-creating-response-body, error=\"\"\"{e}\"\"\"' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') def process_run_service_command(self, message: dict)", "from the server topic. \"\"\" # register config apiToken (before", "supports the data type environ['user_config'] = message.get('userConfig', []) # add", ") self.log.trace(traceback.format_exc()) self.increment_metric('Errors') def process_run_service_command(self, message: dict) -> None: \"\"\"Process", "for key, value in message.items(): if key not in environ", "self.log.info('feature=api-service, event=response-body-written') event.set() except Exception as e: self.log.error( f'feature=api-service, event=api-event-callback-failed,", "is not None: environ['CONTENT_TYPE'] = headers.pop('content-type') # add content length", "for q in params: query_string.append(f'''{q.get('name')}={q.get('value')}''') except AttributeError as e: self.log.error(", "def format_response_headers(self, headers: dict) -> dict: \"\"\"Convert name/value array to", "process body body = '' if hasattr(body_data, 'read'): body =", "for bd in body_data: if hasattr(bd, 'read'): body += bd.read()", "self.thread_name, message.get('apiToken'), message.get('expireSeconds') ) self.log.info(f'feature=api-service, event=runservice-command, message=\"{message}\"') # thread event", "str = message.pop('path') try: environ = { 'wsgi.errors': sys.stderr, 'wsgi.input':", "b in bd: self.log.error(f'unhandled type - {type(b)}') else: self.log.error(f'unhandled type", "params: dict = message.pop('queryParams') path: str = message.pop('path') try: environ", "event to kwargs for blocking kwargs['request_key'] = request_key self.service_thread( name='response-handler',", "', 1) response = { 'bodyVariable': 'response.body', 'command': 'Acknowledged', 'headers':", "params for the request. Returns: str: The query params reformatted", "= None try: # read body from redis body_variable: str", "= threading.Event() # process message request_key: str = message.get('requestKey') body", "disable=not-callable environ, response_handler ) # process body body = ''", "a query string. Args: headers: The dict header data to", "list of values # headers_.setdefault(h.get('name').lower(), []).append(h.get('value')) headers_.setdefault(h.get('name').lower(), str(h.get('value'))) except AttributeError", "\"\"\"Return the command map for the current Service type.\"\"\" command_map", "header data. \"\"\" headers_ = [] try: for h in", "headers.get('content-length') is not None: environ['CONTENT_LENGTH'] = headers.pop('content-length') for header, value", "in environ: environ[self.tcex.utils.camel_to_snake(key)] = value self.log.trace(f'feature=api-service, environ={environ}') self.increment_metric('Requests') except Exception", "or other service that supports the data type environ['user_config'] =", "except Exception as e: self.log.error(f'feature=api-service, event=failed-reading-body, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) headers: dict", "dict) -> None: \"\"\"Process the RunService command. .. code-block:: python", "= self.api_event_callback( # pylint: disable=not-callable environ, response_handler ) # process", "The query params reformatted as a string. \"\"\" query_string =", "environ['CONTENT_TYPE'] = headers.pop('content-type') # add content length if headers.get('content-length') is", "path, 'QUERY_STRING': self.format_query_string(params), 'REMOTE_ADDR': message.get('remoteAddress', ''), # 'REMOTE_HOST': message.get('remoteAddress', ''),", "} self.log.info('feature=api-service, event=response-sent') self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic) self.increment_metric('Responses') except Exception as e:", "body = body_data.read() elif isinstance(body_data, list): for bd in body_data:", "trigger response self.log.info('feature=api-service, event=response-body-written') event.set() except Exception as e: self.log.error(", "= { 'bodyVariable': 'response.body', 'command': 'Acknowledged', 'headers': self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'),", "str: The query params reformatted as a string. \"\"\" query_string", "message=\"{message}\"') # thread event used to block response until body", "'Responses': 0} # config callbacks self.api_event_callback = None @property def", "\"\"\"Convert name/value array to a query string. Args: headers: The", "event=response-sent') self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic) self.increment_metric('Responses') except Exception as e: self.log.error( f'feature=api-service,", "kwargs['request_key'] = request_key self.service_thread( name='response-handler', target=self.process_run_service_response, args=args, kwargs=kwargs, ) if", "body += bd.read() elif isinstance(bd, bytes): body += bd.decode() elif", "dict of key/value header data. Returns: dict: The restructured header", "'read'): body += bd.read() elif isinstance(bd, bytes): body += bd.decode()", "body_data.read() elif isinstance(body_data, list): for bd in body_data: if hasattr(bd,", "block response until body is written event = threading.Event() #", "and self.tcex.utils.camel_to_snake(key) not in environ: environ[self.tcex.utils.camel_to_snake(key)] = value self.log.trace(f'feature=api-service, environ={environ}')", "as e: self.log.error( f'feature=api-service, event=bad-headers-provided, ' f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc())", "message payload from the server topic. \"\"\" # register config", "headers.items(): environ[f'HTTP_{header}'.upper()] = value # make values from message available", "is not None: environ['CONTENT_LENGTH'] = headers.pop('content-length') for header, value in", "{ key/value pairs } ], \"method\": \"GET\", \"queryParams\": [ {", "isinstance(body_data, list): for bd in body_data: if hasattr(bd, 'read'): body", "callbacks self.api_event_callback = None @property def command_map(self) -> dict: \"\"\"Return", "args={args}') try: status_code, status = args[0].split(' ', 1) response =", "key/value pairs. Returns: dict: The restructured header data. \"\"\" headers_", "environ, response_handler ) # process body body = '' if", "# case (e.g., falcon -> req.env.get('request_url)) for key, value in", "self.key_value_store.create(request_key, 'response.body', body) # set thread event to True to", "command_map(self) -> dict: \"\"\"Return the command map for the current", "case (e.g., falcon -> req.env.get('request_url)) for key, value in message.items():", "query_string = [] try: for q in params: query_string.append(f'''{q.get('name')}={q.get('value')}''') except", "message available in env in camel # case (e.g., falcon", "'&'.join(query_string) def format_request_headers(self, headers: dict) -> dict: \"\"\"Convert name/value array", "[]) # add headers if headers.get('content-type') is not None: environ['CONTENT_TYPE']", "str(h.get('value'))) except AttributeError as e: self.log.error( f'feature=api-service, event=bad-headers-provided, ' f'headers={headers},", "elif isinstance(body_data, list): for bd in body_data: if hasattr(bd, 'read'):", "for TAXII or other service that supports the data type", "Args: headers: The dict header data to be converted to", "not in environ and self.tcex.utils.camel_to_snake(key) not in environ: environ[self.tcex.utils.camel_to_snake(key)] =", "import sys import threading import traceback from io import BytesIO", "\"tlpExportSetting\", \"value\": \"TLP:RED\" }], } Args: message: The message payload", "pylint: disable=unused-argument \"\"\"Handle WSGI Response\"\"\" kwargs['event'] = event # add", "status = args[0].split(' ', 1) response = { 'bodyVariable': 'response.body',", "None: \"\"\"Process the RunService command. .. code-block:: python :linenos: :lineno-start:", "The message payload from the server topic. \"\"\" # register", ") # process body body = '' if hasattr(body_data, 'read'):", "bytes): body += bd.decode() elif isinstance(bd, list): for b in", "from io import BytesIO from typing import Any from .common_service", "message.get('userConfig', []) # add headers if headers.get('content-type') is not None:", "event responses. ('200 OK', [('content-type', 'application/json'), ('content-length', '103')]) \"\"\" self.log.info('feature=api-service,", "in params: query_string.append(f'''{q.get('name')}={q.get('value')}''') except AttributeError as e: self.log.error( f'feature=api-service, event=bad-params-provided,", "headers_ = [] try: for h in headers: headers_.append({'name': h[0],", "h in headers: headers_.append({'name': h[0], 'value': h[1]}) except AttributeError as", "method: str = message.pop('method') params: dict = message.pop('queryParams') path: str", "elif isinstance(bd, list): for b in bd: self.log.error(f'unhandled type -", "super().command_map command_map.update({'runservice': self.process_run_service_command}) return command_map def format_query_string(self, params: dict) ->", "thread event to True to trigger response self.log.info('feature=api-service, event=response-body-written') event.set()", "is not b64 encoded body = BytesIO(body) except Exception as", "kwargs['event'] = event # add event to kwargs for blocking", "to key/value pairs. Returns: dict: The restructured header data. \"\"\"", "message.get('apiToken'), message.get('expireSeconds') ) self.log.info(f'feature=api-service, event=runservice-command, message=\"{message}\"') # thread event used", "'wsgi.input': body, 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': True, 'wsgi.url_scheme': 'https',", "message.get('expireSeconds') ) self.log.info(f'feature=api-service, event=runservice-command, message=\"{message}\"') # thread event used to", "message.pop('path') try: environ = { 'wsgi.errors': sys.stderr, 'wsgi.input': body, 'wsgi.multithread':", "# write body to Redis self.key_value_store.create(request_key, 'response.body', body) # set", "dict: \"\"\"Convert name/value array to a headers dict. Args: headers:", "event to True to trigger response self.log.info('feature=api-service, event=response-body-written') event.set() except", "0), 'PATH_INFO': path, 'QUERY_STRING': self.format_query_string(params), 'REMOTE_ADDR': message.get('remoteAddress', ''), # 'REMOTE_HOST':", "args[0].split(' ', 1) response = { 'bodyVariable': 'response.body', 'command': 'Acknowledged',", "headers: dict) -> dict: \"\"\"Convert name/value array to a query", "= { 'wsgi.errors': sys.stderr, 'wsgi.input': body, 'wsgi.multithread': True, 'wsgi.multiprocess': False,", "except Exception as e: self.log.error(f'feature=api-service, event=failed-building-environ, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) self.increment_metric('Errors') return", "f'feature=api-service, event=bad-headers-provided, ' f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def", "= value self.log.trace(f'feature=api-service, environ={environ}') self.increment_metric('Requests') except Exception as e: self.log.error(f'feature=api-service,", ".common_service import CommonService class ApiService(CommonService): \"\"\"TcEx Framework API Service module.\"\"\"", "threading import traceback from io import BytesIO from typing import", "None: body: Any = self.key_value_store.read(request_key, body_variable) if body is not", "to trigger response self.log.info('feature=api-service, event=response-body-written') event.set() except Exception as e:", "f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def format_response_headers(self, headers: dict)", "'response.body', 'command': 'Acknowledged', 'headers': self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'), # pylint: disable=cell-var-from-loop", "as e: self.log.error(f'feature=api-service, event=failed-reading-body, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) headers: dict = self.format_request_headers(message.pop('headers'))", "environ[self.tcex.utils.camel_to_snake(key)] = value self.log.trace(f'feature=api-service, environ={environ}') self.increment_metric('Requests') except Exception as e:", "AttributeError as e: self.log.error( f'feature=api-service, event=bad-params-provided, params={params}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc())", "], \"method\": \"GET\", \"queryParams\": [ { key/value pairs } ],", "# thread event used to block response until body is", "response self.log.info('feature=api-service, event=response-body-written') event.set() except Exception as e: self.log.error( f'feature=api-service,", "message: dict) -> None: \"\"\"Process the RunService command. .. code-block::", "if hasattr(bd, 'read'): body += bd.read() elif isinstance(bd, bytes): body", "add content length if headers.get('content-length') is not None: environ['CONTENT_LENGTH'] =", "except Exception as e: self.log.error( f'feature=api-service, event=api-event-callback-failed, error=\"\"\"{e}\"\"\".' ) self.log.trace(traceback.format_exc())", "= [] try: for h in headers: headers_.append({'name': h[0], 'value':", "data type environ['user_config'] = message.get('userConfig', []) # add headers if", "Returns: dict: The restructured header data. \"\"\" headers_ = {}", "environ={environ}') self.increment_metric('Requests') except Exception as e: self.log.error(f'feature=api-service, event=failed-building-environ, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc())", "event=response, args={args}') try: status_code, status = args[0].split(' ', 1) response", "event used to block response until body is written event", "not b64 encoded body = BytesIO(body) except Exception as e:", "e: self.log.error( f'feature=api-service, event=failed-creating-response-body, error=\"\"\"{e}\"\"\"' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') def process_run_service_command(self,", "\"\"\" query_string = [] try: for q in params: query_string.append(f'''{q.get('name')}={q.get('value')}''')", "body to Redis self.key_value_store.create(request_key, 'response.body', body) # set thread event", "as e: self.log.error( f'feature=api-service, event=bad-params-provided, params={params}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return", "message: The message payload from the server topic. \"\"\" #", "self.log.trace(traceback.format_exc()) return '&'.join(query_string) def format_request_headers(self, headers: dict) -> dict: \"\"\"Convert", "error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return '&'.join(query_string) def format_request_headers(self, headers: dict) ->", "thread event used to block response until body is written", "None try: # read body from redis body_variable: str =", "thread event - (set on body write) self.log.trace(f'feature=api-service, event=response, args={args}')", "query params for the request. Returns: str: The query params", "True to trigger response self.log.info('feature=api-service, event=response-body-written') event.set() except Exception as", "h[1]}) except AttributeError as e: self.log.error( f'feature=api-service, event=bad-headers-provided, ' f'headers={headers},", "body from redis body_variable: str = message.pop('bodyVariable', None) if body_variable", "\"123abc\", \"userConfig\": [{ \"name\": \"tlpExportSetting\", \"value\": \"TLP:RED\" }], } Args:", "{dir(body)}') # write body to Redis self.key_value_store.create(request_key, 'response.body', body) #", "dict = self.format_request_headers(message.pop('headers')) method: str = message.pop('method') params: dict =", "True, 'wsgi.multiprocess': False, 'wsgi.run_once': True, 'wsgi.url_scheme': 'https', 'wsgi.version': (1, 0),", "callable(self.api_event_callback): try: body_data: Any = self.api_event_callback( # pylint: disable=not-callable environ,", "format_query_string(self, params: dict) -> str: \"\"\"Convert name/value array to a", "class ApiService(CommonService): \"\"\"TcEx Framework API Service module.\"\"\" def __init__(self, tcex:", "type environ['user_config'] = message.get('userConfig', []) # add headers if headers.get('content-type')", "= self.key_value_store.read(request_key, body_variable) if body is not None: # for", "body = BytesIO(body) except Exception as e: self.log.error(f'feature=api-service, event=failed-reading-body, error=\"\"\"{e}\"\"\"')", "event=failed-building-environ, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) self.increment_metric('Errors') return # stop processing def response_handler(*args,", "service the data in Redis is not b64 encoded body", "for thread event - (set on body write) self.log.trace(f'feature=api-service, event=response,", "headers.pop('content-length') for header, value in headers.items(): environ[f'HTTP_{header}'.upper()] = value #", "'QUERY_STRING': self.format_query_string(params), 'REMOTE_ADDR': message.get('remoteAddress', ''), # 'REMOTE_HOST': message.get('remoteAddress', ''), 'REQUEST_METHOD':", "request_key self.service_thread( name='response-handler', target=self.process_run_service_response, args=args, kwargs=kwargs, ) if callable(self.api_event_callback): try:", "headers: The dict header data to be converted to key/value", "params reformatted as a string. \"\"\" query_string = [] try:", "= None @property def command_map(self) -> dict: \"\"\"Return the command", "TAXII or other service that supports the data type environ['user_config']", "req.env.get('request_url)) for key, value in message.items(): if key not in", "status_code, status = args[0].split(' ', 1) response = { 'bodyVariable':", "as e: self.log.error( f'feature=api-service, event=api-event-callback-failed, error=\"\"\"{e}\"\"\".' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') #", "kwargs for blocking kwargs['request_key'] = request_key self.service_thread( name='response-handler', target=self.process_run_service_response, args=args,", "import threading import traceback from io import BytesIO from typing", "= message.get('userConfig', []) # add headers if headers.get('content-type') is not", "# add content length if headers.get('content-length') is not None: environ['CONTENT_LENGTH']", "self.format_query_string(params), 'REMOTE_ADDR': message.get('remoteAddress', ''), # 'REMOTE_HOST': message.get('remoteAddress', ''), 'REQUEST_METHOD': method.upper(),", "self.log.error(f'unhandled type dir - {dir(body)}') # write body to Redis", "body_variable is not None: body: Any = self.key_value_store.read(request_key, body_variable) if", "object): \"\"\"Initialize the Class properties. Args: tcex: Instance of TcEx.", "event=api-event-callback-failed, error=\"\"\"{e}\"\"\".' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') # unregister config apiToken self.token.unregister_token(self.thread_name)", "The dict of key/value header data. Returns: dict: The restructured", "'value': h[1]}) except AttributeError as e: self.log.error( f'feature=api-service, event=bad-headers-provided, '", "array to a query string. Args: headers: The dict header", "# for API service the data in Redis is not", "the data in Redis is not b64 encoded body =", "in env in camel # case (e.g., falcon -> req.env.get('request_url))", "Redis self.key_value_store.create(request_key, 'response.body', body) # set thread event to True", "'requestKey': kwargs.get('request_key'), # pylint: disable=cell-var-from-loop 'status': status, 'statusCode': status_code, 'type':", "\"command\": \"RunService\", \"apiToken\": \"abc123\", \"bodyVariable\": \"request.body\", \"headers\": [ { key/value", "the request. Returns: str: The query params reformatted as a", "str = message.pop('method') params: dict = message.pop('queryParams') path: str =", "= '' if hasattr(body_data, 'read'): body = body_data.read() elif isinstance(body_data,", "topic. \"\"\" # register config apiToken (before any logging) self.token.register_token(", "not None: # for API service the data in Redis", "to a query string. Args: params: The query params for", "name/value array to a headers dict. Args: headers: The dict", "\"GET\", \"queryParams\": [ { key/value pairs } ], \"requestKey\": \"123abc\",", "body) # set thread event to True to trigger response", "hasattr(bd, 'read'): body += bd.read() elif isinstance(bd, bytes): body +=", "+= bd.decode() elif isinstance(bd, list): for b in bd: self.log.error(f'unhandled", "not None: environ['CONTENT_TYPE'] = headers.pop('content-type') # add content length if", "# process message request_key: str = message.get('requestKey') body = None", "from .common_service import CommonService class ApiService(CommonService): \"\"\"TcEx Framework API Service", "logging) self.token.register_token( self.thread_name, message.get('apiToken'), message.get('expireSeconds') ) self.log.info(f'feature=api-service, event=runservice-command, message=\"{message}\"') #", "in headers: # TODO: either support tuple or csv list", "\"\"\"Initialize the Class properties. Args: tcex: Instance of TcEx. \"\"\"", "'https', 'wsgi.version': (1, 0), 'PATH_INFO': path, 'QUERY_STRING': self.format_query_string(params), 'REMOTE_ADDR': message.get('remoteAddress',", "dict) -> dict: \"\"\"Convert name/value array to a headers dict.", "the server topic. \"\"\" # register config apiToken (before any", "headers.pop('content-type') # add content length if headers.get('content-length') is not None:", "str = message.get('requestKey') body = None try: # read body", "[{ \"name\": \"tlpExportSetting\", \"value\": \"TLP:RED\" }], } Args: message: The", "'response.body', body) # set thread event to True to trigger", "not None: body: Any = self.key_value_store.read(request_key, body_variable) if body is", "status_code, 'type': 'RunService', } self.log.info('feature=api-service, event=response-sent') self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic) self.increment_metric('Responses') except", "import traceback from io import BytesIO from typing import Any", ".. code-block:: python :linenos: :lineno-start: 1 { \"command\": \"RunService\", \"apiToken\":", "dict header data to be converted to key/value pairs. Returns:", "} ], \"method\": \"GET\", \"queryParams\": [ { key/value pairs }", "map for the current Service type.\"\"\" command_map = super().command_map command_map.update({'runservice':", "in message.items(): if key not in environ and self.tcex.utils.camel_to_snake(key) not", "ApiService(CommonService): \"\"\"TcEx Framework API Service module.\"\"\" def __init__(self, tcex: object):", "traceback from io import BytesIO from typing import Any from", "[ { key/value pairs } ], \"method\": \"GET\", \"queryParams\": [", "command. .. code-block:: python :linenos: :lineno-start: 1 { \"command\": \"RunService\",", "self.increment_metric('Errors') return # stop processing def response_handler(*args, **kwargs): # pylint:", "tuple or csv list of values # headers_.setdefault(h.get('name').lower(), []).append(h.get('value')) headers_.setdefault(h.get('name').lower(),", "API service the data in Redis is not b64 encoded", "@property def command_map(self) -> dict: \"\"\"Return the command map for", "event=response-body-written') event.set() except Exception as e: self.log.error( f'feature=api-service, event=api-event-callback-failed, error=\"\"\"{e}\"\"\".'", "'statusCode': status_code, 'type': 'RunService', } self.log.info('feature=api-service, event=response-sent') self.message_broker.publish(json.dumps(response), self.args.tc_svc_client_topic) self.increment_metric('Responses')", "# headers_.setdefault(h.get('name').lower(), []).append(h.get('value')) headers_.setdefault(h.get('name').lower(), str(h.get('value'))) except AttributeError as e: self.log.error(", "[] try: for q in params: query_string.append(f'''{q.get('name')}={q.get('value')}''') except AttributeError as", "any logging) self.token.register_token( self.thread_name, message.get('apiToken'), message.get('expireSeconds') ) self.log.info(f'feature=api-service, event=runservice-command, message=\"{message}\"')", "user config for TAXII or other service that supports the", "def command_map(self) -> dict: \"\"\"Return the command map for the", "to True to trigger response self.log.info('feature=api-service, event=response-body-written') event.set() except Exception", "process_run_service_command(self, message: dict) -> None: \"\"\"Process the RunService command. ..", "event=failed-creating-response-body, error=\"\"\"{e}\"\"\"' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') def process_run_service_command(self, message: dict) ->", "kwargs.get('event').wait(30) # wait for thread event - (set on body", "self.log.error(f'feature=api-service, event=failed-building-environ, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) self.increment_metric('Errors') return # stop processing def", "self._metrics = {'Errors': 0, 'Requests': 0, 'Responses': 0} # config", "self.increment_metric('Responses') except Exception as e: self.log.error( f'feature=api-service, event=failed-creating-response-body, error=\"\"\"{e}\"\"\"' )", "body is not None: # for API service the data", "available in env in camel # case (e.g., falcon ->", "= message.pop('path') try: environ = { 'wsgi.errors': sys.stderr, 'wsgi.input': body,", "\"\"\" super().__init__(tcex) # properties self._metrics = {'Errors': 0, 'Requests': 0,", "body_variable) if body is not None: # for API service", "module.\"\"\" def __init__(self, tcex: object): \"\"\"Initialize the Class properties. Args:", "self.log.error( f'feature=api-service, event=bad-headers-provided, ' f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_", "kwargs.get('request_key'), # pylint: disable=cell-var-from-loop 'status': status, 'statusCode': status_code, 'type': 'RunService',", "= args[0].split(' ', 1) response = { 'bodyVariable': 'response.body', 'command':", "Add user config for TAXII or other service that supports", "def process_run_service_command(self, message: dict) -> None: \"\"\"Process the RunService command.", ") if callable(self.api_event_callback): try: body_data: Any = self.api_event_callback( # pylint:", "path: str = message.pop('path') try: environ = { 'wsgi.errors': sys.stderr,", "self.log.trace(traceback.format_exc()) self.increment_metric('Errors') return # stop processing def response_handler(*args, **kwargs): #", "query params reformatted as a string. \"\"\" query_string = []", "environ = { 'wsgi.errors': sys.stderr, 'wsgi.input': body, 'wsgi.multithread': True, 'wsgi.multiprocess':", "str: \"\"\"Convert name/value array to a query string. Args: params:", "standard library import json import sys import threading import traceback", "data in Redis is not b64 encoded body = BytesIO(body)", "True, 'wsgi.url_scheme': 'https', 'wsgi.version': (1, 0), 'PATH_INFO': path, 'QUERY_STRING': self.format_query_string(params),", "{type(b)}') else: self.log.error(f'unhandled type - {type(body)}') self.log.error(f'unhandled type dir -", "try: body_data: Any = self.api_event_callback( # pylint: disable=not-callable environ, response_handler", "'wsgi.url_scheme': 'https', 'wsgi.version': (1, 0), 'PATH_INFO': path, 'QUERY_STRING': self.format_query_string(params), 'REMOTE_ADDR':", "'read'): body = body_data.read() elif isinstance(body_data, list): for bd in", "dict) -> str: \"\"\"Convert name/value array to a query string.", "b64 encoded body = BytesIO(body) except Exception as e: self.log.error(f'feature=api-service,", "self.log.error(f'unhandled type - {type(b)}') else: self.log.error(f'unhandled type - {type(body)}') self.log.error(f'unhandled", "dict. Args: headers: The dict of key/value header data. Returns:", ":linenos: :lineno-start: 1 { \"command\": \"RunService\", \"apiToken\": \"abc123\", \"bodyVariable\": \"request.body\",", "- {type(body)}') self.log.error(f'unhandled type dir - {dir(body)}') # write body", "headers_ def format_response_headers(self, headers: dict) -> dict: \"\"\"Convert name/value array", "support tuple or csv list of values # headers_.setdefault(h.get('name').lower(), []).append(h.get('value'))", "h in headers: # TODO: either support tuple or csv", "# config callbacks self.api_event_callback = None @property def command_map(self) ->", "\"\"\" headers_ = {} try: for h in headers: #", "headers_.setdefault(h.get('name').lower(), []).append(h.get('value')) headers_.setdefault(h.get('name').lower(), str(h.get('value'))) except AttributeError as e: self.log.error( f'feature=api-service,", "to a headers dict. Args: headers: The dict of key/value", "process message request_key: str = message.get('requestKey') body = None try:", "Service module.\"\"\" def __init__(self, tcex: object): \"\"\"Initialize the Class properties.", "AttributeError as e: self.log.error( f'feature=api-service, event=bad-headers-provided, ' f'headers={headers}, error=\"\"\"{e})\"\"\"' )", "command map for the current Service type.\"\"\" command_map = super().command_map", "to a query string. Args: headers: The dict header data", "None: environ['CONTENT_LENGTH'] = headers.pop('content-length') for header, value in headers.items(): environ[f'HTTP_{header}'.upper()]", "from message available in env in camel # case (e.g.,", "'wsgi.errors': sys.stderr, 'wsgi.input': body, 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': True,", "Args: params: The query params for the request. Returns: str:", "self.api_event_callback( # pylint: disable=not-callable environ, response_handler ) # process body", "type - {type(b)}') else: self.log.error(f'unhandled type - {type(body)}') self.log.error(f'unhandled type", "to be converted to key/value pairs. Returns: dict: The restructured", "0, 'Responses': 0} # config callbacks self.api_event_callback = None @property", "= value # make values from message available in env", "event=bad-headers-provided, ' f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def format_response_headers(self,", "try: for h in headers: # TODO: either support tuple", "properties self._metrics = {'Errors': 0, 'Requests': 0, 'Responses': 0} #", "- {type(b)}') else: self.log.error(f'unhandled type - {type(body)}') self.log.error(f'unhandled type dir", "value in message.items(): if key not in environ and self.tcex.utils.camel_to_snake(key)", "in headers: headers_.append({'name': h[0], 'value': h[1]}) except AttributeError as e:", "self.log.trace(traceback.format_exc()) self.increment_metric('Errors') def process_run_service_command(self, message: dict) -> None: \"\"\"Process the", "self.log.trace(traceback.format_exc()) return headers_ def format_response_headers(self, headers: dict) -> dict: \"\"\"Convert", "else: self.log.error(f'unhandled type - {type(body)}') self.log.error(f'unhandled type dir - {dir(body)}')", "'HTTP/1.1', } # Add user config for TAXII or other", "type.\"\"\" command_map = super().command_map command_map.update({'runservice': self.process_run_service_command}) return command_map def format_query_string(self,", "def format_request_headers(self, headers: dict) -> dict: \"\"\"Convert name/value array to", "of TcEx. \"\"\" super().__init__(tcex) # properties self._metrics = {'Errors': 0,", "API Service module.\"\"\" # standard library import json import sys", "self.log.error( f'feature=api-service, event=failed-creating-response-body, error=\"\"\"{e}\"\"\"' ) self.log.trace(traceback.format_exc()) self.increment_metric('Errors') def process_run_service_command(self, message:", "header data. Returns: dict: The restructured header data. \"\"\" headers_", "key, value in message.items(): if key not in environ and", "args=args, kwargs=kwargs, ) if callable(self.api_event_callback): try: body_data: Any = self.api_event_callback(", "Any = self.api_event_callback( # pylint: disable=not-callable environ, response_handler ) #", "library import json import sys import threading import traceback from", "the current Service type.\"\"\" command_map = super().command_map command_map.update({'runservice': self.process_run_service_command}) return", "used to block response until body is written event =", "[]).append(h.get('value')) headers_.setdefault(h.get('name').lower(), str(h.get('value'))) except AttributeError as e: self.log.error( f'feature=api-service, event=bad-headers-provided,", "sys.stderr, 'wsgi.input': body, 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': True, 'wsgi.url_scheme':", "\"\"\"Handle service event responses. ('200 OK', [('content-type', 'application/json'), ('content-length', '103')])", "body = '' if hasattr(body_data, 'read'): body = body_data.read() elif", "self.token.register_token( self.thread_name, message.get('apiToken'), message.get('expireSeconds') ) self.log.info(f'feature=api-service, event=runservice-command, message=\"{message}\"') # thread", "self.log.error(f'unhandled type - {type(body)}') self.log.error(f'unhandled type dir - {dir(body)}') #", "Response\"\"\" kwargs['event'] = event # add event to kwargs for", ":lineno-start: 1 { \"command\": \"RunService\", \"apiToken\": \"abc123\", \"bodyVariable\": \"request.body\", \"headers\":", "name/value array to a query string. Args: params: The query", "- (set on body write) self.log.trace(f'feature=api-service, event=response, args={args}') try: status_code,", "of values # headers_.setdefault(h.get('name').lower(), []).append(h.get('value')) headers_.setdefault(h.get('name').lower(), str(h.get('value'))) except AttributeError as", "self.args.tc_svc_client_topic) self.increment_metric('Responses') except Exception as e: self.log.error( f'feature=api-service, event=failed-creating-response-body, error=\"\"\"{e}\"\"\"'", "event.set() except Exception as e: self.log.error( f'feature=api-service, event=api-event-callback-failed, error=\"\"\"{e}\"\"\".' )", "if body_variable is not None: body: Any = self.key_value_store.read(request_key, body_variable)", "= self.format_request_headers(message.pop('headers')) method: str = message.pop('method') params: dict = message.pop('queryParams')", "header, value in headers.items(): environ[f'HTTP_{header}'.upper()] = value # make values", "camel # case (e.g., falcon -> req.env.get('request_url)) for key, value", "if hasattr(body_data, 'read'): body = body_data.read() elif isinstance(body_data, list): for", "(before any logging) self.token.register_token( self.thread_name, message.get('apiToken'), message.get('expireSeconds') ) self.log.info(f'feature=api-service, event=runservice-command,", "that supports the data type environ['user_config'] = message.get('userConfig', []) #", "properties. Args: tcex: Instance of TcEx. \"\"\" super().__init__(tcex) # properties", "' f'headers={headers}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def format_response_headers(self, headers:", "in camel # case (e.g., falcon -> req.env.get('request_url)) for key,", "{type(body)}') self.log.error(f'unhandled type dir - {dir(body)}') # write body to", "command_map def format_query_string(self, params: dict) -> str: \"\"\"Convert name/value array", "q in params: query_string.append(f'''{q.get('name')}={q.get('value')}''') except AttributeError as e: self.log.error( f'feature=api-service,", "error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return headers_ def format_response_headers(self, headers: dict) ->", "environ['CONTENT_LENGTH'] = headers.pop('content-length') for header, value in headers.items(): environ[f'HTTP_{header}'.upper()] =", "\"\"\" self.log.info('feature=api-service, event=response-received, status=waiting-for-body') kwargs.get('event').wait(30) # wait for thread event", "return headers_ def process_run_service_response(self, *args, **kwargs) -> None: \"\"\"Handle service", "1) response = { 'bodyVariable': 'response.body', 'command': 'Acknowledged', 'headers': self.format_response_headers(args[1]),", "# process body body = '' if hasattr(body_data, 'read'): body", "until body is written event = threading.Event() # process message", "# standard library import json import sys import threading import", "payload from the server topic. \"\"\" # register config apiToken", "'PATH_INFO': path, 'QUERY_STRING': self.format_query_string(params), 'REMOTE_ADDR': message.get('remoteAddress', ''), # 'REMOTE_HOST': message.get('remoteAddress',", "\"\"\"Process the RunService command. .. code-block:: python :linenos: :lineno-start: 1", "response until body is written event = threading.Event() # process", "headers dict. Args: headers: The dict of key/value header data.", "'bodyVariable': 'response.body', 'command': 'Acknowledged', 'headers': self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'), # pylint:", "dict: \"\"\"Return the command map for the current Service type.\"\"\"", "content length if headers.get('content-length') is not None: environ['CONTENT_LENGTH'] = headers.pop('content-length')", "Returns: str: The query params reformatted as a string. \"\"\"", "status=waiting-for-body') kwargs.get('event').wait(30) # wait for thread event - (set on", "self.increment_metric('Errors') def process_run_service_command(self, message: dict) -> None: \"\"\"Process the RunService", "a string. \"\"\" query_string = [] try: for q in", "headers_ def process_run_service_response(self, *args, **kwargs) -> None: \"\"\"Handle service event", "message.pop('bodyVariable', None) if body_variable is not None: body: Any =", "in body_data: if hasattr(bd, 'read'): body += bd.read() elif isinstance(bd,", "Service module.\"\"\" # standard library import json import sys import", "self.format_request_headers(message.pop('headers')) method: str = message.pop('method') params: dict = message.pop('queryParams') path:", "dict: The restructured header data. \"\"\" headers_ = [] try:", "-> None: \"\"\"Handle service event responses. ('200 OK', [('content-type', 'application/json'),", "value # make values from message available in env in", "string. Args: params: The query params for the request. Returns:", "environ and self.tcex.utils.camel_to_snake(key) not in environ: environ[self.tcex.utils.camel_to_snake(key)] = value self.log.trace(f'feature=api-service,", "'REMOTE_HOST': message.get('remoteAddress', ''), 'REQUEST_METHOD': method.upper(), 'SCRIPT_NAME': '/', 'SERVER_NAME': '', 'SERVER_PORT':", "def __init__(self, tcex: object): \"\"\"Initialize the Class properties. Args: tcex:", "headers.get('content-type') is not None: environ['CONTENT_TYPE'] = headers.pop('content-type') # add content", "values from message available in env in camel # case", "return headers_ def format_response_headers(self, headers: dict) -> dict: \"\"\"Convert name/value", "response_handler(*args, **kwargs): # pylint: disable=unused-argument \"\"\"Handle WSGI Response\"\"\" kwargs['event'] =", "try: # read body from redis body_variable: str = message.pop('bodyVariable',", "query string. Args: headers: The dict header data to be", "BytesIO(body) except Exception as e: self.log.error(f'feature=api-service, event=failed-reading-body, error=\"\"\"{e}\"\"\"') self.log.trace(traceback.format_exc()) headers:", "super().__init__(tcex) # properties self._metrics = {'Errors': 0, 'Requests': 0, 'Responses':", "the command map for the current Service type.\"\"\" command_map =", "\"apiToken\": \"abc123\", \"bodyVariable\": \"request.body\", \"headers\": [ { key/value pairs }", "params={params}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return '&'.join(query_string) def format_request_headers(self, headers: dict)", "elif isinstance(bd, bytes): body += bd.decode() elif isinstance(bd, list): for", "current Service type.\"\"\" command_map = super().command_map command_map.update({'runservice': self.process_run_service_command}) return command_map", "# properties self._metrics = {'Errors': 0, 'Requests': 0, 'Responses': 0}", "Args: message: The message payload from the server topic. \"\"\"", "headers: headers_.append({'name': h[0], 'value': h[1]}) except AttributeError as e: self.log.error(", "header data to be converted to key/value pairs. Returns: dict:", "sys import threading import traceback from io import BytesIO from", "config for TAXII or other service that supports the data", "[('content-type', 'application/json'), ('content-length', '103')]) \"\"\" self.log.info('feature=api-service, event=response-received, status=waiting-for-body') kwargs.get('event').wait(30) #", "\"method\": \"GET\", \"queryParams\": [ { key/value pairs } ], \"requestKey\":", "# read body from redis body_variable: str = message.pop('bodyVariable', None)", "method.upper(), 'SCRIPT_NAME': '/', 'SERVER_NAME': '', 'SERVER_PORT': '', 'SERVER_PROTOCOL': 'HTTP/1.1', }", "blocking kwargs['request_key'] = request_key self.service_thread( name='response-handler', target=self.process_run_service_response, args=args, kwargs=kwargs, )", "self.log.info(f'feature=api-service, event=runservice-command, message=\"{message}\"') # thread event used to block response", "None) if body_variable is not None: body: Any = self.key_value_store.read(request_key,", "f'feature=api-service, event=bad-params-provided, params={params}, error=\"\"\"{e})\"\"\"' ) self.log.trace(traceback.format_exc()) return '&'.join(query_string) def format_request_headers(self,", "The restructured header data. \"\"\" headers_ = {} try: for", "body_data: if hasattr(bd, 'read'): body += bd.read() elif isinstance(bd, bytes):", "import json import sys import threading import traceback from io", "'command': 'Acknowledged', 'headers': self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'), # pylint: disable=cell-var-from-loop 'status':", "headers_.append({'name': h[0], 'value': h[1]}) except AttributeError as e: self.log.error( f'feature=api-service,", "write) self.log.trace(f'feature=api-service, event=response, args={args}') try: status_code, status = args[0].split(' '," ]
[ "= getattr(model, key) optimizers[key] = build_optimizer(module, cfg_) return optimizers else:", "cfg.copy() module = getattr(model, key) optimizers[key] = build_optimizer(module, cfg_) return", "= dict(type='SGD', lr=lr) The return is ``torch.optim.Optimizer``. Args: model (:obj:`nn.Module`):", "return dict is ``dict('model1': torch.optim.Optimizer, 'model2': torch.optim.Optimizer)`` 2) Single optimizer", "code-block:: python optimizer_cfg = dict( model1=dict(type='SGD', lr=lr), model2=dict(type='SGD', lr=lr)) The", "cfgs.items(): cfg_ = cfg.copy() module = getattr(model, key) optimizers[key] =", "model1=dict(type='SGD', lr=lr), model2=dict(type='SGD', lr=lr)) The return dict is ``dict('model1': torch.optim.Optimizer,", "dict( model1=dict(type='SGD', lr=lr), model2=dict(type='SGD', lr=lr)) The return dict is ``dict('model1':", "The config dict of the optimizer. Returns: dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`:", ".. code-block:: python optimizer_cfg = dict(type='SGD', lr=lr) The return is", "for optimizers, then a dict for each constructed optimizers will", "for optimizers if all(isinstance(v, dict) for v in cfgs.values()): for", "optimizers will be returned. If `cfgs` only contains one optimizer", "2) Single optimizer config: .. code-block:: python optimizer_cfg = dict(type='SGD',", "If `cfgs` only contains one optimizer config, the constructed optimizer", "itself will be returned. For example, 1) Multiple optimizer configs:", "return is ``torch.optim.Optimizer``. Args: model (:obj:`nn.Module`): The model with parameters", "dicts for optimizers, then a dict for each constructed optimizers", "optimized. cfgs (dict): The config dict of the optimizer. Returns:", "contains several dicts for optimizers, then a dict for each", "``dict('model1': torch.optim.Optimizer, 'model2': torch.optim.Optimizer)`` 2) Single optimizer config: .. code-block::", "optimizers if all(isinstance(v, dict) for v in cfgs.values()): for key,", "For example, 1) Multiple optimizer configs: .. code-block:: python optimizer_cfg", "1) Multiple optimizer configs: .. code-block:: python optimizer_cfg = dict(", "for v in cfgs.values()): for key, cfg in cfgs.items(): cfg_", "is ``dict('model1': torch.optim.Optimizer, 'model2': torch.optim.Optimizer)`` 2) Single optimizer config: ..", "= {} if hasattr(model, 'module'): model = model.module # determine", "several dicts for optimizers if all(isinstance(v, dict) for v in", "hasattr(model, 'module'): model = model.module # determine whether 'cfgs' has", "lr=lr), model2=dict(type='SGD', lr=lr)) The return dict is ``dict('model1': torch.optim.Optimizer, 'model2':", "cfgs (dict): The config dict of the optimizer. Returns: dict[:obj:`torch.optim.Optimizer`]", "(dict): The config dict of the optimizer. Returns: dict[:obj:`torch.optim.Optimizer`] |", "dicts for optimizers if all(isinstance(v, dict) for v in cfgs.values()):", "config, the constructed optimizer itself will be returned. For example,", "torch.optim.Optimizer, 'model2': torch.optim.Optimizer)`` 2) Single optimizer config: .. code-block:: python", "configs: .. code-block:: python optimizer_cfg = dict( model1=dict(type='SGD', lr=lr), model2=dict(type='SGD',", "Multiple optimizer configs: .. code-block:: python optimizer_cfg = dict( model1=dict(type='SGD',", "constructed optimizer itself will be returned. For example, 1) Multiple", "configs. If `cfgs` contains several dicts for optimizers, then a", "`cfgs` only contains one optimizer config, the constructed optimizer itself", "cfg_ = cfg.copy() module = getattr(model, key) optimizers[key] = build_optimizer(module,", "with parameters to be optimized. cfgs (dict): The config dict", "in cfgs.values()): for key, cfg in cfgs.items(): cfg_ = cfg.copy()", "only contains one optimizer config, the constructed optimizer itself will", "one optimizer config, the constructed optimizer itself will be returned.", "be returned. For example, 1) Multiple optimizer configs: .. code-block::", "for each constructed optimizers will be returned. If `cfgs` only", "torch.optim.Optimizer)`` 2) Single optimizer config: .. code-block:: python optimizer_cfg =", "Single optimizer config: .. code-block:: python optimizer_cfg = dict(type='SGD', lr=lr)", "optimizers, then a dict for each constructed optimizers will be", "a dict for each constructed optimizers will be returned. If", "dict(type='SGD', lr=lr) The return is ``torch.optim.Optimizer``. Args: model (:obj:`nn.Module`): The", "if hasattr(model, 'module'): model = model.module # determine whether 'cfgs'", "returned. If `cfgs` only contains one optimizer config, the constructed", "optimizer_cfg = dict(type='SGD', lr=lr) The return is ``torch.optim.Optimizer``. Args: model", "is ``torch.optim.Optimizer``. Args: model (:obj:`nn.Module`): The model with parameters to", "The model with parameters to be optimized. cfgs (dict): The", "cfgs.values()): for key, cfg in cfgs.items(): cfg_ = cfg.copy() module", "initialized optimizers. \"\"\" optimizers = {} if hasattr(model, 'module'): model", "\"\"\"Build multiple optimizers from configs. If `cfgs` contains several dicts", "then a dict for each constructed optimizers will be returned.", "getattr(model, key) optimizers[key] = build_optimizer(module, cfg_) return optimizers else: return", "dict of the optimizer. Returns: dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`: The initialized", "optimizer config: .. code-block:: python optimizer_cfg = dict(type='SGD', lr=lr) The", "model = model.module # determine whether 'cfgs' has several dicts", "build_optimizers(model, cfgs): \"\"\"Build multiple optimizers from configs. If `cfgs` contains", "v in cfgs.values()): for key, cfg in cfgs.items(): cfg_ =", "of the optimizer. Returns: dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`: The initialized optimizers.", "has several dicts for optimizers if all(isinstance(v, dict) for v", "The return is ``torch.optim.Optimizer``. Args: model (:obj:`nn.Module`): The model with", "will be returned. For example, 1) Multiple optimizer configs: ..", "the constructed optimizer itself will be returned. For example, 1)", "lr=lr) The return is ``torch.optim.Optimizer``. Args: model (:obj:`nn.Module`): The model", "dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`: The initialized optimizers. \"\"\" optimizers = {}", "'module'): model = model.module # determine whether 'cfgs' has several", "from configs. If `cfgs` contains several dicts for optimizers, then", "optimizer itself will be returned. For example, 1) Multiple optimizer", "config dict of the optimizer. Returns: dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`: The", "model with parameters to be optimized. cfgs (dict): The config", "optimizers. \"\"\" optimizers = {} if hasattr(model, 'module'): model =", "python optimizer_cfg = dict(type='SGD', lr=lr) The return is ``torch.optim.Optimizer``. Args:", "``torch.optim.Optimizer``. Args: model (:obj:`nn.Module`): The model with parameters to be", "\"\"\" optimizers = {} if hasattr(model, 'module'): model = model.module", "multiple optimizers from configs. If `cfgs` contains several dicts for", "`cfgs` contains several dicts for optimizers, then a dict for", ".. code-block:: python optimizer_cfg = dict( model1=dict(type='SGD', lr=lr), model2=dict(type='SGD', lr=lr))", ":obj:`torch.optim.Optimizer`: The initialized optimizers. \"\"\" optimizers = {} if hasattr(model,", "cfgs): \"\"\"Build multiple optimizers from configs. If `cfgs` contains several", "python optimizer_cfg = dict( model1=dict(type='SGD', lr=lr), model2=dict(type='SGD', lr=lr)) The return", "will be returned. If `cfgs` only contains one optimizer config,", "from mmcv.runner import build_optimizer def build_optimizers(model, cfgs): \"\"\"Build multiple optimizers", "optimizers = {} if hasattr(model, 'module'): model = model.module #", "for key, cfg in cfgs.items(): cfg_ = cfg.copy() module =", "several dicts for optimizers, then a dict for each constructed", "mmcv.runner import build_optimizer def build_optimizers(model, cfgs): \"\"\"Build multiple optimizers from", "code-block:: python optimizer_cfg = dict(type='SGD', lr=lr) The return is ``torch.optim.Optimizer``.", "dict is ``dict('model1': torch.optim.Optimizer, 'model2': torch.optim.Optimizer)`` 2) Single optimizer config:", "dict for each constructed optimizers will be returned. If `cfgs`", "If `cfgs` contains several dicts for optimizers, then a dict", "model2=dict(type='SGD', lr=lr)) The return dict is ``dict('model1': torch.optim.Optimizer, 'model2': torch.optim.Optimizer)``", "config: .. code-block:: python optimizer_cfg = dict(type='SGD', lr=lr) The return", "each constructed optimizers will be returned. If `cfgs` only contains", "if all(isinstance(v, dict) for v in cfgs.values()): for key, cfg", "determine whether 'cfgs' has several dicts for optimizers if all(isinstance(v,", "optimizers[key] = build_optimizer(module, cfg_) return optimizers else: return build_optimizer(model, cfgs)", "be returned. If `cfgs` only contains one optimizer config, the", "| :obj:`torch.optim.Optimizer`: The initialized optimizers. \"\"\" optimizers = {} if", "returned. For example, 1) Multiple optimizer configs: .. code-block:: python", "parameters to be optimized. cfgs (dict): The config dict of", "= dict( model1=dict(type='SGD', lr=lr), model2=dict(type='SGD', lr=lr)) The return dict is", "import build_optimizer def build_optimizers(model, cfgs): \"\"\"Build multiple optimizers from configs.", "build_optimizer def build_optimizers(model, cfgs): \"\"\"Build multiple optimizers from configs. If", "Args: model (:obj:`nn.Module`): The model with parameters to be optimized.", "'model2': torch.optim.Optimizer)`` 2) Single optimizer config: .. code-block:: python optimizer_cfg", "dict) for v in cfgs.values()): for key, cfg in cfgs.items():", "optimizer config, the constructed optimizer itself will be returned. For", "optimizer. Returns: dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`: The initialized optimizers. \"\"\" optimizers", "contains one optimizer config, the constructed optimizer itself will be", "The initialized optimizers. \"\"\" optimizers = {} if hasattr(model, 'module'):", "= cfg.copy() module = getattr(model, key) optimizers[key] = build_optimizer(module, cfg_)", "cfg in cfgs.items(): cfg_ = cfg.copy() module = getattr(model, key)", "to be optimized. cfgs (dict): The config dict of the", "all(isinstance(v, dict) for v in cfgs.values()): for key, cfg in", "model.module # determine whether 'cfgs' has several dicts for optimizers", "lr=lr)) The return dict is ``dict('model1': torch.optim.Optimizer, 'model2': torch.optim.Optimizer)`` 2)", "(:obj:`nn.Module`): The model with parameters to be optimized. cfgs (dict):", "model (:obj:`nn.Module`): The model with parameters to be optimized. cfgs", "def build_optimizers(model, cfgs): \"\"\"Build multiple optimizers from configs. If `cfgs`", "# determine whether 'cfgs' has several dicts for optimizers if", "<reponame>vsatyakumar/mmpose from mmcv.runner import build_optimizer def build_optimizers(model, cfgs): \"\"\"Build multiple", "in cfgs.items(): cfg_ = cfg.copy() module = getattr(model, key) optimizers[key]", "constructed optimizers will be returned. If `cfgs` only contains one", "optimizer_cfg = dict( model1=dict(type='SGD', lr=lr), model2=dict(type='SGD', lr=lr)) The return dict", "optimizers from configs. If `cfgs` contains several dicts for optimizers,", "= model.module # determine whether 'cfgs' has several dicts for", "module = getattr(model, key) optimizers[key] = build_optimizer(module, cfg_) return optimizers", "be optimized. cfgs (dict): The config dict of the optimizer.", "key) optimizers[key] = build_optimizer(module, cfg_) return optimizers else: return build_optimizer(model,", "Returns: dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`: The initialized optimizers. \"\"\" optimizers =", "{} if hasattr(model, 'module'): model = model.module # determine whether", "key, cfg in cfgs.items(): cfg_ = cfg.copy() module = getattr(model,", "the optimizer. Returns: dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`: The initialized optimizers. \"\"\"", "'cfgs' has several dicts for optimizers if all(isinstance(v, dict) for", "example, 1) Multiple optimizer configs: .. code-block:: python optimizer_cfg =", "The return dict is ``dict('model1': torch.optim.Optimizer, 'model2': torch.optim.Optimizer)`` 2) Single", "whether 'cfgs' has several dicts for optimizers if all(isinstance(v, dict)", "optimizer configs: .. code-block:: python optimizer_cfg = dict( model1=dict(type='SGD', lr=lr)," ]
[ "def register(response): if response.user.is_authenticated: return redirect(\"homepage\") else: if response.method ==", "= form.save() # messages.info(response, \"Thanks for registering. You are now", "You are now logged in.\") new_user = authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'], )", "redirect(\"homepage\") else: form = RegisterForm() return render(response, \"register/register.html\", {\"form\": form})", "new_user = form.save() # messages.info(response, \"Thanks for registering. You are", "HttpResponse from django.contrib.auth.forms import AuthenticationForm from django.conf import settings from", "for registering. You are now logged in.\") new_user = authenticate(username=form.cleaned_data['username'],", "messages.info(response, \"Thanks for registering. You are now logged in.\") new_user", "# Create your views here. def register(response): if response.user.is_authenticated: return", "if response.user.is_authenticated: return redirect(\"homepage\") else: if response.method == \"POST\": form", "django.conf import settings from django.contrib.auth import authenticate, login from django.http", "import logout from django.shortcuts import render, redirect from .forms import", "Create your views here. def register(response): if response.user.is_authenticated: return redirect(\"homepage\")", "if form.is_valid(): new_user = form.save() # messages.info(response, \"Thanks for registering.", "from .forms import RegisterForm from django.http import HttpResponse from django.contrib.auth.forms", "redirect from .forms import RegisterForm from django.http import HttpResponse from", "import messages # Create your views here. def register(response): if", "response.method == \"POST\": form = RegisterForm(response.POST) if form.is_valid(): new_user =", "import authenticate, login from django.http import HttpResponseRedirect from django.contrib import", "HttpResponseRedirect from django.contrib import messages # Create your views here.", "new_user) return redirect(\"homepage\") else: form = RegisterForm() return render(response, \"register/register.html\",", "if response.method == \"POST\": form = RegisterForm(response.POST) if form.is_valid(): new_user", "RegisterForm(response.POST) if form.is_valid(): new_user = form.save() # messages.info(response, \"Thanks for", "import settings from django.contrib.auth import authenticate, login from django.http import", ".forms import RegisterForm from django.http import HttpResponse from django.contrib.auth.forms import", "import RegisterForm from django.http import HttpResponse from django.contrib.auth.forms import AuthenticationForm", "== \"POST\": form = RegisterForm(response.POST) if form.is_valid(): new_user = form.save()", "messages # Create your views here. def register(response): if response.user.is_authenticated:", "else: if response.method == \"POST\": form = RegisterForm(response.POST) if form.is_valid():", "now logged in.\") new_user = authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'], ) login(response, new_user)", "return redirect(\"homepage\") else: if response.method == \"POST\": form = RegisterForm(response.POST)", "from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from", "in.\") new_user = authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'], ) login(response, new_user) return redirect(\"homepage\")", "here. def register(response): if response.user.is_authenticated: return redirect(\"homepage\") else: if response.method", "RegisterForm from django.http import HttpResponse from django.contrib.auth.forms import AuthenticationForm from", "form.save() # messages.info(response, \"Thanks for registering. You are now logged", "django.shortcuts import render, redirect from .forms import RegisterForm from django.http", "from django.http import HttpResponseRedirect from django.contrib import messages # Create", "import HttpResponseRedirect from django.contrib import messages # Create your views", "from django.contrib.auth.forms import AuthenticationForm from django.conf import settings from django.contrib.auth", "render, redirect from .forms import RegisterForm from django.http import HttpResponse", "django.http import HttpResponse from django.contrib.auth.forms import AuthenticationForm from django.conf import", "login from django.http import HttpResponseRedirect from django.contrib import messages #", "import render, redirect from .forms import RegisterForm from django.http import", "# messages.info(response, \"Thanks for registering. You are now logged in.\")", "authenticate, login from django.http import HttpResponseRedirect from django.contrib import messages", ") login(response, new_user) return redirect(\"homepage\") else: form = RegisterForm() return", "AuthenticationForm from django.conf import settings from django.contrib.auth import authenticate, login", "form = RegisterForm(response.POST) if form.is_valid(): new_user = form.save() # messages.info(response,", "\"POST\": form = RegisterForm(response.POST) if form.is_valid(): new_user = form.save() #", "settings from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect", "form.is_valid(): new_user = form.save() # messages.info(response, \"Thanks for registering. You", "new_user = authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'], ) login(response, new_user) return redirect(\"homepage\") else:", "registering. You are now logged in.\") new_user = authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'],", "from django.conf import settings from django.contrib.auth import authenticate, login from", "your views here. def register(response): if response.user.is_authenticated: return redirect(\"homepage\") else:", "\"Thanks for registering. You are now logged in.\") new_user =", "are now logged in.\") new_user = authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'], ) login(response,", "authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'], ) login(response, new_user) return redirect(\"homepage\") else: form =", "from django.contrib import messages # Create your views here. def", "import datetime from django.contrib.auth import logout from django.shortcuts import render,", "logout from django.shortcuts import render, redirect from .forms import RegisterForm", "register(response): if response.user.is_authenticated: return redirect(\"homepage\") else: if response.method == \"POST\":", "logged in.\") new_user = authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'], ) login(response, new_user) return", "django.http import HttpResponseRedirect from django.contrib import messages # Create your", "views here. def register(response): if response.user.is_authenticated: return redirect(\"homepage\") else: if", "django.contrib import messages # Create your views here. def register(response):", "from django.http import HttpResponse from django.contrib.auth.forms import AuthenticationForm from django.conf", "= RegisterForm(response.POST) if form.is_valid(): new_user = form.save() # messages.info(response, \"Thanks", "from django.contrib.auth import logout from django.shortcuts import render, redirect from", "import HttpResponse from django.contrib.auth.forms import AuthenticationForm from django.conf import settings", "django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from django.contrib", "response.user.is_authenticated: return redirect(\"homepage\") else: if response.method == \"POST\": form =", "django.contrib.auth import logout from django.shortcuts import render, redirect from .forms", "password=<PASSWORD>.cleaned_data['<PASSWORD>'], ) login(response, new_user) return redirect(\"homepage\") else: form = RegisterForm()", "= authenticate(username=form.cleaned_data['username'], password=<PASSWORD>.cleaned_data['<PASSWORD>'], ) login(response, new_user) return redirect(\"homepage\") else: form", "redirect(\"homepage\") else: if response.method == \"POST\": form = RegisterForm(response.POST) if", "import AuthenticationForm from django.conf import settings from django.contrib.auth import authenticate,", "return redirect(\"homepage\") else: form = RegisterForm() return render(response, \"register/register.html\", {\"form\":", "login(response, new_user) return redirect(\"homepage\") else: form = RegisterForm() return render(response,", "<reponame>angel-vazquez25/My-Backlog-Handler import datetime from django.contrib.auth import logout from django.shortcuts import", "datetime from django.contrib.auth import logout from django.shortcuts import render, redirect", "from django.shortcuts import render, redirect from .forms import RegisterForm from", "django.contrib.auth.forms import AuthenticationForm from django.conf import settings from django.contrib.auth import" ]
[ "] operations = [ migrations.CreateModel( name='Community', fields=[ ('name', models.CharField(max_length=64, primary_key=True,", "migrations, models class Migration(migrations.Migration): initial = True dependencies = [", "[ ] operations = [ migrations.CreateModel( name='Community', fields=[ ('name', models.CharField(max_length=64,", "# Generated by Django 3.1.7 on 2021-03-26 01:27 from django.db", "name='Community', fields=[ ('name', models.CharField(max_length=64, primary_key=True, serialize=False)), ('description', models.TextField()), ('private', models.BooleanField(default=False)),", "on 2021-03-26 01:27 from django.db import migrations, models class Migration(migrations.Migration):", "initial = True dependencies = [ ] operations = [", "class Migration(migrations.Migration): initial = True dependencies = [ ] operations", "= [ migrations.CreateModel( name='Community', fields=[ ('name', models.CharField(max_length=64, primary_key=True, serialize=False)), ('description',", "by Django 3.1.7 on 2021-03-26 01:27 from django.db import migrations,", "<filename>forum/migrations/0001_initial.py # Generated by Django 3.1.7 on 2021-03-26 01:27 from", "[ migrations.CreateModel( name='Community', fields=[ ('name', models.CharField(max_length=64, primary_key=True, serialize=False)), ('description', models.TextField()),", "primary_key=True, serialize=False)), ('description', models.TextField()), ('private', models.BooleanField(default=False)), ('slug', models.SlugField()), ], ),", "models.CharField(max_length=64, primary_key=True, serialize=False)), ('description', models.TextField()), ('private', models.BooleanField(default=False)), ('slug', models.SlugField()), ],", "('name', models.CharField(max_length=64, primary_key=True, serialize=False)), ('description', models.TextField()), ('private', models.BooleanField(default=False)), ('slug', models.SlugField()),", "Generated by Django 3.1.7 on 2021-03-26 01:27 from django.db import", "True dependencies = [ ] operations = [ migrations.CreateModel( name='Community',", "serialize=False)), ('description', models.TextField()), ('private', models.BooleanField(default=False)), ('slug', models.SlugField()), ], ), ]", "from django.db import migrations, models class Migration(migrations.Migration): initial = True", "django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies", "fields=[ ('name', models.CharField(max_length=64, primary_key=True, serialize=False)), ('description', models.TextField()), ('private', models.BooleanField(default=False)), ('slug',", "01:27 from django.db import migrations, models class Migration(migrations.Migration): initial =", "= [ ] operations = [ migrations.CreateModel( name='Community', fields=[ ('name',", "3.1.7 on 2021-03-26 01:27 from django.db import migrations, models class", "dependencies = [ ] operations = [ migrations.CreateModel( name='Community', fields=[", "models class Migration(migrations.Migration): initial = True dependencies = [ ]", "2021-03-26 01:27 from django.db import migrations, models class Migration(migrations.Migration): initial", "migrations.CreateModel( name='Community', fields=[ ('name', models.CharField(max_length=64, primary_key=True, serialize=False)), ('description', models.TextField()), ('private',", "= True dependencies = [ ] operations = [ migrations.CreateModel(", "Django 3.1.7 on 2021-03-26 01:27 from django.db import migrations, models", "Migration(migrations.Migration): initial = True dependencies = [ ] operations =", "operations = [ migrations.CreateModel( name='Community', fields=[ ('name', models.CharField(max_length=64, primary_key=True, serialize=False)),", "import migrations, models class Migration(migrations.Migration): initial = True dependencies =" ]
[ "language modeling, etc. task = tasks.setup_task(args) # Load valid dataset", "checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\") for old_chk in checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk): os.remove(old_chk) if", "is None: return False if args.patience <= 0: return False", "+= 1 if should_stop_early.num_runs >= args.patience: logger.info( \"early stop since", "as np import torch from fairseq import ( checkpoint_utils, distributed_utils,", "train iterator extra_state, epoch_itr = checkpoint_utils.load_checkpoint( args, trainer, # don't", "not OOM, overflow, ... # log mid-epoch stats num_updates =", "args.log_interval == 0: stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats, tag=\"train_inner\", step=num_updates) #", "epoch checkpoints; checkpoints are sorted in descending order checkpoints =", "old epoch checkpoints; checkpoints are sorted in descending order checkpoints", "progress.print(stats, tag=\"train\", step=num_updates) # reset epoch-level meters metrics.reset_meters(\"train\") return valid_losses,", "GPUs. \"\"\" import collections import logging import math import os", "and return validation losses.\"\"\" # Initialize data iterator itr =", "else \"simple\"), ) trainer.begin_epoch(epoch_itr.epoch) valid_losses = [None] valid_subsets = args.valid_subset.split(\",\")", "self.keep_best = [] def save_checkpoint(self, args, trainer, epoch_itr, val_loss): #", "a < b prev_best = getattr(should_stop_early, \"best\", None) if prev_best", "for p in model.parameters() if p.requires_grad), ) ) # (optionally)", "train for one epoch valid_losses, should_stop = train(args, trainer, task,", "(writing took {} seconds)\".format( checkpoints[0], epoch, updates, val_loss, write_timer.sum )", "in checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk): os.remove(old_chk) if args.keep_last_epochs > 0: #", "subset in subsets: logger.info('begin validation on \"{}\" subset'.format(subset)) # Initialize", "self.best = None self.keep_best = [] def save_checkpoint(self, args, trainer,", "valid_loss should_stop_early.num_runs = 0 return False else: should_stop_early.num_runs += 1", "trainer = Trainer(args, task, model, criterion, quantizer) else: trainer =", "with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function( \"train_step-%d\" % i ): log_output = trainer.train_step(samples)", "mid-epoch stats after each log interval # the end-of-epoch stats", "args.no_save: return trainer.consolidate_optimizer() if not trainer.is_data_parallel_master: return def is_better(a, b):", "saver) # Stopping conditions should_stop = ( should_stop_early(args, valid_losses[0]) or", ") logger.info( \"max tokens per GPU = {} and max", "criterion model = task.build_model(args) criterion = task.build_criterion(args) logger.info(model) logger.info(\"task: {}", "= self.keep_best[:args.keep_best_checkpoints] def main(args): saver = Saver() utils.import_user_module(args) assert (", "license found in the # LICENSE file in the root", "end_of_epoch, saver ) if should_stop: break # log end-of-epoch stats", "next epoch load_dataset=task.has_sharded_data(\"train\"), # don't cache epoch iterators for sharded", "below)\".format(epoch_itr.epoch)) stats = get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats, tag=\"train\", step=num_updates) # reset epoch-level", "None and not is_better(self.keep_best[-1][0], val_loss))): ckpt_name = \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix, val_loss)", "OOM, overflow, ... # log mid-epoch stats num_updates = trainer.get_num_updates()", "if val_loss is not None: best_function = max if args.maximize_best_checkpoint_metric", "= best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric] ) return stats def cli_main(modify_parser=None): parser", "quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update, ) else: quantizer = None #", "args.valid_subset.split(\",\") should_stop = False num_updates = trainer.get_num_updates() for i, samples", "__init__(self): self.best = None self.keep_best = [] def save_checkpoint(self, args,", "and restore the # corresponding train iterator extra_state, epoch_itr =", "# sharded data: get train iterator for next epoch load_dataset=task.has_sharded_data(\"train\"),", "modify_parser=modify_parser) if args.profile: with torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main) else:", "don't cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) #", "args.save_interval_updates > 0 and updates % args.save_interval_updates == 0 )", "meters from fairseq.checkpoint_utils import checkpoint_paths from fairseq.data import iterators from", "val_loss, write_timer.sum ) ) if not end_of_epoch and args.keep_interval_updates >", "( args.update_freq[epoch_itr.epoch - 1] if epoch_itr.epoch <= len(args.update_freq) else args.update_freq[-1]", "= save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates, suffix)] = ( not save_epoch_checkpoint and", "if args.maximize_best_checkpoint_metric else a <= b write_timer = meters.StopwatchMeter() write_timer.start()", "(GPUs/TPUs)\".format(args.distributed_world_size) ) logger.info( \"max tokens per GPU = {} and", "if not trainer.is_data_parallel_master: return def is_better(a, b): return a >=", "done in the current epoch if valid_loss is None: return", "cond ] if len(checkpoints) > 0: trainer.save_checkpoint(checkpoints[0], extra_state) for cp", "conditions should_stop = ( should_stop_early(args, valid_losses[0]) or num_updates >= max_update", "if args.no_save: return trainer.consolidate_optimizer() if not trainer.is_data_parallel_master: return def is_better(a,", "= \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix, val_loss) if save_epoch_checkpoint \\ else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates,", "epoch_itr, subsets, saver): \"\"\"Evaluate the model on the validation set(s)", "# only one worker should attempt to create the required", "criterion.__class__.__name__) ) logger.info( \"num. model params: {} (num. trained: {})\".format(", "\"\"\" Train a new model on one or across multiple", "== 0: stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats, tag=\"train_inner\", step=num_updates) # reset", "= [] def save_checkpoint(self, args, trainer, epoch_itr, val_loss): # only", "is not None: # set fixed seed for every validation", "progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else", "and args.keep_interval_updates > 0: # remove old checkpoints; checkpoints are", "# Load the latest checkpoint if one is available and", "# don't cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), )", "\"wall\").elapsed_time, 0) return stats def validate(args, trainer, task, epoch_itr, subsets,", "sum(p.numel() for p in model.parameters() if p.requires_grad), ) ) #", "iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) train_meter.stop() logger.info(\"done training in", "training in {:.1f} seconds\".format(train_meter.sum)) def should_stop_early(args, valid_loss): # skip check", "--batch-size\" metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print args", "order checkpoints = checkpoint_paths( args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" ) for old_chk in", "= tasks.setup_task(args) # Load valid dataset (we load training data", "epoch {} (average epoch stats below)\".format(epoch_itr.epoch)) stats = get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats,", "args.maximize_best_checkpoint_metric else min stats[key] = best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric] ) return", "in descending order checkpoints = checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\") for old_chk in", "epoch_itr.state_dict(), \"val_loss\": val_loss} if self.best is not None: extra_state.update({\"best\": self.best})", "valid dataset (we load training data below, based on the", "num_updates = trainer.get_num_updates() if num_updates % args.log_interval == 0: stats", "== 0 ) checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)] = save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates, suffix)]", "if args.model_parallel_size == 1: trainer = Trainer(args, task, model, criterion,", "else args.update_freq[-1] ) itr = iterators.GroupedIterator(itr, update_freq) if getattr(args, \"tpu\",", "save checkpoint\") saver.save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) return valid_losses, should_stop def", "logger.info(\"end of epoch {} (average epoch stats below)\".format(epoch_itr.epoch)) stats =", ") ) do_validate = ( (not end_of_epoch and do_save) #", "rate lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr = trainer.get_train_iterator( epoch_itr.next_epoch_idx, #", "gets too small max_epoch = args.max_epoch or math.inf lr =", "and max sentences per GPU = {}\".format( args.max_tokens, args.batch_size )", "step=num_updates) # reset epoch-level meters metrics.reset_meters(\"train\") return valid_losses, should_stop def", "stream=sys.stdout, ) logger = logging.getLogger(\"fairseq_cli.train\") class Saver: def __init__(self): self.best", "and its affiliates. # # This source code is licensed", "epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) train_meter.stop() logger.info(\"done training", "x) if os.path.lexists(x): os.remove(x) self.keep_best = self.keep_best[:args.keep_best_checkpoints] def main(args): saver", "True self.keep_best.append((val_loss, ckpt_name)) self.keep_best = sorted(self.keep_best) checkpoints = [ os.path.join(args.save_dir,", "metrics.reset_meters(\"train\") return valid_losses, should_stop def validate_and_save(args, trainer, task, epoch_itr, valid_subsets,", "suffix, val_loss) if save_epoch_checkpoint \\ else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates, suffix, val_loss)", "Trainer logging.basicConfig( format=\"%(asctime)s | %(levelname)s | %(name)s | %(message)s\", datefmt=\"%Y-%m-%d", "args.tensorboard_logdir if distributed_utils.is_master(args) else None ), default_log_format=(\"tqdm\" if not args.no_progress_bar", "num_updates > 0 and num_updates % args.validate_interval_updates == 0 )", "def validate(args, trainer, task, epoch_itr, subsets, saver): \"\"\"Evaluate the model", "data iterator itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args, \"tpu\", False): itr", "tasks, utils, ) from fairseq import meters from fairseq.checkpoint_utils import", "valid_losses def get_valid_stats(args, trainer, stats, saver): stats[\"num_updates\"] = trainer.get_num_updates() if", "since valid performance hasn't improved for last {} runs\".format( args.patience", "\"early stop since valid performance hasn't improved for last {}", "# corresponding train iterator extra_state, epoch_itr = checkpoint_utils.load_checkpoint( args, trainer,", "log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f\"valid on '{subset}' subset\", tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args)", "task, epoch_itr, valid_subsets, end_of_epoch, saver): num_updates = trainer.get_num_updates() max_update =", "do_validate = ( (not end_of_epoch and do_save) # validate during", "after each log interval # the end-of-epoch stats will still", "if should_stop: break # only use first validation loss to", "log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f\"valid on '{subset}' subset\", tensorboard_logdir=( args.tensorboard_logdir if", "if num_updates % args.log_interval == 0: stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats,", "per GPU = {}\".format( args.max_tokens, args.batch_size ) ) # Load", "'{subset}' subset\", tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ), default_log_format=(\"tqdm\"", "tag=\"train\", step=num_updates) # reset epoch-level meters metrics.reset_meters(\"train\") return valid_losses, should_stop", "interval # the end-of-epoch stats will still be preserved metrics.reset_meters(\"train_inner\")", "get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats, tag=\"train\", step=num_updates) # reset epoch-level meters metrics.reset_meters(\"train\") return", "os.remove(old_chk) if len(self.keep_best) > args.keep_best_checkpoints: for _, x in self.keep_best[args.keep_best_checkpoints:]:", "def main(args): saver = Saver() utils.import_user_module(args) assert ( args.max_tokens is", "update_freq = ( args.update_freq[epoch_itr.epoch - 1] if epoch_itr.epoch <= len(args.update_freq)", "trainer.get_num_updates() max_update = args.max_update or math.inf do_save = ( (end_of_epoch", "import os import sys import numpy as np import torch", "in checkpoints[1:]: PathManager.copy(checkpoints[0], cp, overwrite=True) write_timer.stop() logger.info( \"saved checkpoint {}", "from fairseq.file_io import PathManager from fairseq.logging import metrics, progress_bar from", "only one worker should attempt to create the required dir", "\"simple\"), ) # create a new root metrics aggregator so", "= {\"train_iterator\": epoch_itr.state_dict(), \"val_loss\": val_loss} if self.best is not None:", "or ( val_loss is not None and not is_better(self.keep_best[-1][0], val_loss))):", "valid_losses, should_stop = validate_and_save( args, trainer, task, epoch_itr, valid_subsets, end_of_epoch,", "epoch stats below)\".format(epoch_itr.epoch)) stats = get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats, tag=\"train\", step=num_updates) #", "end-of-epoch stats will still be preserved metrics.reset_meters(\"train_inner\") end_of_epoch = not", "of this source tree. \"\"\" Train a new model on", "for sample in progress: trainer.valid_step(sample) # log validation stats stats", "ckpt_name = \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix, val_loss) if save_epoch_checkpoint \\ else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch,", "stats logger.info(\"end of epoch {} (average epoch stats below)\".format(epoch_itr.epoch)) stats", "args = options.parse_args_and_arch(parser, modify_parser=modify_parser) if args.profile: with torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx():", "checkpoints; checkpoints are sorted in descending order checkpoints = checkpoint_paths(args.save_dir,", "is_better(val_loss, self.best) ) checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix) ] = not args.no_last_checkpoints extra_state", "{} (average epoch stats below)\".format(epoch_itr.epoch)) stats = get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats, tag=\"train\",", "import sys import numpy as np import torch from fairseq", "return a >= b if args.maximize_best_checkpoint_metric else a <= b", "\"criterion: {} ({})\".format(args.criterion, criterion.__class__.__name__) ) logger.info( \"num. model params: {}", "should_stop_early.best = valid_loss should_stop_early.num_runs = 0 return False else: should_stop_early.num_runs", "= max if args.maximize_best_checkpoint_metric else min stats[key] = best_function( saver.save_checkpoint.best,", "a new root metrics aggregator so validation metrics # don't", "epoch = epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch() updates = trainer.get_num_updates() suffix", "overwrite=True) write_timer.stop() logger.info( \"saved checkpoint {} (epoch {} @ {}", "logger.info('begin validation on \"{}\" subset'.format(subset)) # Initialize data iterator itr", "not end_of_epoch and args.keep_interval_updates > 0: # remove old checkpoints;", "= ( should_stop_early(args, valid_losses[0]) or num_updates >= max_update or (", "old_chk in checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk): os.remove(old_chk) if args.keep_last_epochs > 0:", "( val_loss is not None and not is_better(self.keep_best[-1][0], val_loss))): ckpt_name", "b if args.maximize_best_checkpoint_metric else a < b prev_best = getattr(should_stop_early,", "save_epoch_checkpoint and args.save_interval_updates > 0 and updates % args.save_interval_updates ==", "for cp in checkpoints[1:]: PathManager.copy(checkpoints[0], cp, overwrite=True) write_timer.stop() logger.info( \"saved", "if os.path.lexists(old_chk): os.remove(old_chk) if args.keep_last_epochs > 0: # remove old", "return stats def cli_main(modify_parser=None): parser = options.get_training_parser() args = options.parse_args_and_arch(parser,", "in model.parameters()), sum(p.numel() for p in model.parameters() if p.requires_grad), )", "% args.validate_interval_updates == 0 ) ) and not args.disable_validation #", ") logger.info( \"num. model params: {} (num. trained: {})\".format( sum(p.numel()", "are sorted in descending order checkpoints = checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\") for", "checkpoints are sorted in descending order checkpoints = checkpoint_paths( args.save_dir,", "on {} devices (GPUs/TPUs)\".format(args.distributed_world_size) ) logger.info( \"max tokens per GPU", "(average epoch stats below)\".format(epoch_itr.epoch)) stats = get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats, tag=\"train\", step=num_updates)", "cp in checkpoints[1:]: PathManager.copy(checkpoints[0], cp, overwrite=True) write_timer.stop() logger.info( \"saved checkpoint", "= options.get_training_parser() args = options.parse_args_and_arch(parser, modify_parser=modify_parser) if args.profile: with torch.cuda.profiler.profile():", "os import sys import numpy as np import torch from", "= utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f\"valid", "for old_chk in checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk): os.remove(old_chk) if args.keep_last_epochs >", "else \"simple\"), ) # create a new root metrics aggregator", "stats = get_valid_stats(args, trainer, agg.get_smoothed_values(), saver) progress.print(stats, tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric])", "args.batch_size ) ) # Load the latest checkpoint if one", "not trainer.is_data_parallel_master: return def is_better(a, b): return a >= b", "args.quantization_config_path is not None: quantizer = quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update,", "task, e.g., translation, language modeling, etc. task = tasks.setup_task(args) #", "epoch % args.save_interval == 0 ) checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)] = save_epoch_checkpoint", "epoch_itr, valid_subsets, saver) # Stopping conditions should_stop = ( should_stop_early(args,", "] = not args.no_last_checkpoints extra_state = {\"train_iterator\": epoch_itr.state_dict(), \"val_loss\": val_loss}", "extra_state.update({\"best\": self.best}) if args.keep_best_checkpoints > 0 and (len(self.keep_best) < args.keep_best_checkpoints", "on '{subset}' subset\", tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ),", "> 0: # remove old epoch checkpoints; checkpoints are sorted", "for one epoch and return validation losses.\"\"\" # Initialize data", "return valid_losses def get_valid_stats(args, trainer, stats, saver): stats[\"num_updates\"] = trainer.get_num_updates()", "itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args, \"tpu\", False): itr = utils.tpu_data_loader(itr)", "valid_losses = [None] if do_validate: valid_losses = validate(args, trainer, task,", "self.keep_best = sorted(self.keep_best) checkpoints = [ os.path.join(args.save_dir, fn) for fn,", "p in model.parameters()), sum(p.numel() for p in model.parameters() if p.requires_grad),", "args.max_epoch or math.inf lr = trainer.get_lr() train_meter = meters.StopwatchMeter() train_meter.start()", "Load the latest checkpoint if one is available and restore", "os.path.join(args.save_dir, x) if os.path.lexists(x): os.remove(x) self.keep_best = self.keep_best[:args.keep_best_checkpoints] def main(args):", ">= args.patience: logger.info( \"early stop since valid performance hasn't improved", "rate gets too small max_epoch = args.max_epoch or math.inf lr", "\\ else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates, suffix, val_loss) checkpoint_conds[ckpt_name] = True self.keep_best.append((val_loss,", "math.inf do_save = ( (end_of_epoch and epoch_itr.epoch % args.save_interval ==", "self.best is None or is_better(val_loss, self.best) ) checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix) ]", "validation stats stats = get_valid_stats(args, trainer, agg.get_smoothed_values(), saver) progress.print(stats, tag=subset,", "data iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx > args.curriculum), )", "end_of_epoch and not args.no_epoch_checkpoints and epoch % args.save_interval == 0", "from fairseq import meters from fairseq.checkpoint_utils import checkpoint_paths from fairseq.data", "is not None: quantizer = quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update, )", "= get_valid_stats(args, trainer, agg.get_smoothed_values(), saver) progress.print(stats, tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return", "trainer.is_data_parallel_master: return def is_better(a, b): return a >= b if", "> 0 and trainer.cumulative_training_time() / (60 * 60) > args.stop_time_hours", "tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses def get_valid_stats(args, trainer, stats, saver):", "return a > b if args.maximize_best_checkpoint_metric else a < b", "# log end-of-epoch stats logger.info(\"end of epoch {} (average epoch", "epoch valid_losses, should_stop = train(args, trainer, task, epoch_itr, saver) if", "from fairseq.checkpoint_utils import checkpoint_paths from fairseq.data import iterators from fairseq.file_io", "> 0 and (len(self.keep_best) < args.keep_best_checkpoints or ( val_loss is", "too small max_epoch = args.max_epoch or math.inf lr = trainer.get_lr()", "max_update or ( args.save_interval_updates > 0 and num_updates > 0", "distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print args logger.info(args) # Setup task, e.g.,", "epoch_itr = checkpoint_utils.load_checkpoint( args, trainer, # don't cache epoch iterators", "or is_better(valid_loss, prev_best): should_stop_early.best = valid_loss should_stop_early.num_runs = 0 return", "create a new root metrics aggregator so validation metrics #", "logger.info( \"saved checkpoint {} (epoch {} @ {} updates, score", "numpy as np import torch from fairseq import ( checkpoint_utils,", "model.__class__.__name__)) logger.info( \"criterion: {} ({})\".format(args.criterion, criterion.__class__.__name__) ) logger.info( \"num. model", "if log_output is not None: # not OOM, overflow, ...", "args.update_freq[-1] ) itr = iterators.GroupedIterator(itr, update_freq) if getattr(args, \"tpu\", False):", "(e.g., train meters) with metrics.aggregate(new_root=True) as agg: for sample in", "reset epoch-level meters metrics.reset_meters(\"train\") return valid_losses, should_stop def validate_and_save(args, trainer,", "= meters.StopwatchMeter() write_timer.start() epoch = epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch() updates", "trainer if args.model_parallel_size == 1: trainer = Trainer(args, task, model,", "in checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk): os.remove(old_chk) if len(self.keep_best) > args.keep_best_checkpoints: for", "required dir if args.distributed_rank == 0: os.makedirs(args.save_dir, exist_ok=True) prev_best =", "updates, suffix)] = ( not save_epoch_checkpoint and args.save_interval_updates > 0", "for every validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses = [] for subset", "== 0) or num_updates >= max_update or ( args.save_interval_updates >", "and epoch % args.save_interval == 0 ) checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)] =", "os.path.lexists(x): os.remove(x) self.keep_best = self.keep_best[:args.keep_best_checkpoints] def main(args): saver = Saver()", "fairseq.trainer import Trainer logging.basicConfig( format=\"%(asctime)s | %(levelname)s | %(name)s |", "quantizer = None # Build trainer if args.model_parallel_size == 1:", "0 and (len(self.keep_best) < args.keep_best_checkpoints or ( val_loss is not", "is not None: best_function = max if args.maximize_best_checkpoint_metric else min", "source code is licensed under the MIT license found in", "progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f\"valid on '{subset}' subset\", tensorboard_logdir=(", "ckpt_name)) self.keep_best = sorted(self.keep_best) checkpoints = [ os.path.join(args.save_dir, fn) for", "return valid_losses, should_stop def validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch,", "from fairseq.logging import metrics, progress_bar from fairseq.model_parallel.megatron_trainer import MegatronTrainer from", "lr = trainer.get_lr() train_meter = meters.StopwatchMeter() train_meter.start() while lr >", "args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver ) if should_stop:", "best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric] ) return stats def cli_main(modify_parser=None): parser =", "validation metrics # don't pollute other aggregators (e.g., train meters)", "task, epoch_itr, subsets, saver): \"\"\"Evaluate the model on the validation", "def validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver): num_updates =", "args.save_interval == 0) or num_updates >= max_update or ( args.save_interval_updates", "checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates, suffix)] = ( not save_epoch_checkpoint and args.save_interval_updates >", ") ) # Save checkpoint if do_save or should_stop: logger.info(\"begin", "# This source code is licensed under the MIT license", "= epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch() updates = trainer.get_num_updates() suffix =", "utils, ) from fairseq import meters from fairseq.checkpoint_utils import checkpoint_paths", "= {} and max sentences per GPU = {}\".format( args.max_tokens,", "one epoch and return validation losses.\"\"\" # Initialize data iterator", "seed for every validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses = [] for", ">= b if args.maximize_best_checkpoint_metric else a <= b write_timer =", "trainer, stats, saver): stats[\"num_updates\"] = trainer.get_num_updates() if hasattr(saver.save_checkpoint, \"best\"): key", "def get_training_stats(stats): stats[\"wall\"] = round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0) return stats def", "epoch_itr.next_epoch_idx, # sharded data: get train iterator for next epoch", "stats after each log interval # the end-of-epoch stats will", "criterion = task.build_criterion(args) logger.info(model) logger.info(\"task: {} ({})\".format(args.task, task.__class__.__name__)) logger.info(\"model: {}", "args.no_epoch_checkpoints and epoch % args.save_interval == 0 ) checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)]", "with --max-tokens or --batch-size\" metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir)", "level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(), stream=sys.stdout, ) logger = logging.getLogger(\"fairseq_cli.train\") class Saver: def", "return def is_better(a, b): return a >= b if args.maximize_best_checkpoint_metric", "write_timer.start() epoch = epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch() updates = trainer.get_num_updates()", "epoch and return validation losses.\"\"\" # Initialize data iterator itr", "quantization_utils, tasks, utils, ) from fairseq import meters from fairseq.checkpoint_utils", "its affiliates. # # This source code is licensed under", "(optionally) Configure quantization if args.quantization_config_path is not None: quantizer =", "else min self.best = best_function(val_loss, prev_best) if args.no_save: return trainer.consolidate_optimizer()", "while lr > args.min_lr and epoch_itr.next_epoch_idx <= max_epoch: # train", "num_updates > 0 and num_updates % args.save_interval_updates == 0 and", "# train for one epoch valid_losses, should_stop = train(args, trainer,", "task.__class__.__name__)) logger.info(\"model: {} ({})\".format(args.arch, model.__class__.__name__)) logger.info( \"criterion: {} ({})\".format(args.criterion, criterion.__class__.__name__)", "subsets: logger.info('begin validation on \"{}\" subset'.format(subset)) # Initialize data iterator", "and not is_better(self.keep_best[-1][0], val_loss))): ckpt_name = \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix, val_loss) if", "trainer.get_num_updates() if hasattr(saver.save_checkpoint, \"best\"): key = \"best_{0}\".format(args.best_checkpoint_metric) best_function = max", "logger.info(\"model: {} ({})\".format(args.arch, model.__class__.__name__)) logger.info( \"criterion: {} ({})\".format(args.criterion, criterion.__class__.__name__) )", "len(checkpoints) > 0: trainer.save_checkpoint(checkpoints[0], extra_state) for cp in checkpoints[1:]: PathManager.copy(checkpoints[0],", "stats = get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats, tag=\"train\", step=num_updates) # reset epoch-level meters", "validation losses.\"\"\" # Initialize data iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus,", "not save_epoch_checkpoint and args.save_interval_updates > 0 and updates % args.save_interval_updates", "0 and trainer.cumulative_training_time() / (60 * 60) > args.stop_time_hours )", "fairseq.checkpoint_utils import checkpoint_paths from fairseq.data import iterators from fairseq.file_io import", "checkpoints = checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\") for old_chk in checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk):", "[None] valid_subsets = args.valid_subset.split(\",\") should_stop = False num_updates = trainer.get_num_updates()", "in {:.1f} seconds\".format(train_meter.sum)) def should_stop_early(args, valid_loss): # skip check if", "if save_epoch_checkpoint \\ else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates, suffix, val_loss) checkpoint_conds[ckpt_name] =", "else: quantizer = None # Build trainer if args.model_parallel_size ==", "is not None or args.batch_size is not None ), \"Must", "( args.validate_interval_updates > 0 and num_updates > 0 and num_updates", "etc. task = tasks.setup_task(args) # Load valid dataset (we load", "the model on the validation set(s) and return the losses.\"\"\"", "| %(levelname)s | %(name)s | %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(),", "None: best_function = max if args.maximize_best_checkpoint_metric else min self.best =", "if not args.no_progress_bar else \"simple\"), ) # create a new", "devices (GPUs/TPUs)\".format(args.distributed_world_size) ) logger.info( \"max tokens per GPU = {}", "# Setup task, e.g., translation, language modeling, etc. task =", "0: trainer.save_checkpoint(checkpoints[0], extra_state) for cp in checkpoints[1:]: PathManager.copy(checkpoints[0], cp, overwrite=True)", "0: stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats, tag=\"train_inner\", step=num_updates) # reset mid-epoch", "(epoch {} @ {} updates, score {}) (writing took {}", "MegatronTrainer from fairseq.trainer import Trainer logging.basicConfig( format=\"%(asctime)s | %(levelname)s |", "break # only use first validation loss to update the", "False @metrics.aggregate(\"train\") def train(args, trainer, task, epoch_itr, saver): \"\"\"Train the", "= sorted(self.keep_best) checkpoints = [ os.path.join(args.save_dir, fn) for fn, cond", "60) > args.stop_time_hours ) ) # Save checkpoint if do_save", "import MegatronTrainer from fairseq.trainer import Trainer logging.basicConfig( format=\"%(asctime)s | %(levelname)s", "and num_updates > 0 and num_updates % args.save_interval_updates == 0", "new root metrics aggregator so validation metrics # don't pollute", "( args.save_interval_updates > 0 and num_updates > 0 and num_updates", "args.maximize_best_checkpoint_metric else min self.best = best_function(val_loss, prev_best) if args.no_save: return", "a <= b write_timer = meters.StopwatchMeter() write_timer.start() epoch = epoch_itr.epoch", "# remove old checkpoints; checkpoints are sorted in descending order", "logger.info(args) # Setup task, e.g., translation, language modeling, etc. task", "= [None] valid_subsets = args.valid_subset.split(\",\") should_stop = False num_updates =", "should_stop: logger.info(\"begin save checkpoint\") saver.save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) return valid_losses,", "seconds\".format(train_meter.sum)) def should_stop_early(args, valid_loss): # skip check if no validation", "sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) # Train until the learning rate", "a new model on one or across multiple GPUs. \"\"\"", "({})\".format(args.task, task.__class__.__name__)) logger.info(\"model: {} ({})\".format(args.arch, model.__class__.__name__)) logger.info( \"criterion: {} ({})\".format(args.criterion,", "is_better(self.keep_best[-1][0], val_loss))): ckpt_name = \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix, val_loss) if save_epoch_checkpoint \\", "trainer, # don't cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"),", "stats[\"num_updates\"] = trainer.get_num_updates() if hasattr(saver.save_checkpoint, \"best\"): key = \"best_{0}\".format(args.best_checkpoint_metric) best_function", "Inc. and its affiliates. # # This source code is", "%(levelname)s | %(name)s | %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(), stream=sys.stdout,", "checkpoint_conds.items() if cond ] if len(checkpoints) > 0: trainer.save_checkpoint(checkpoints[0], extra_state)", "self.best}) if args.keep_best_checkpoints > 0 and (len(self.keep_best) < args.keep_best_checkpoints or", "if args.maximize_best_checkpoint_metric else min self.best = best_function(val_loss, prev_best) if args.no_save:", "0 and num_updates >= args.validate_after_updates ) ) do_validate = (", "samples in enumerate(progress): with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function( \"train_step-%d\" % i ):", "num_updates = trainer.get_num_updates() max_update = args.max_update or math.inf do_save =", "val_loss) checkpoint_conds[ckpt_name] = True self.keep_best.append((val_loss, ckpt_name)) self.keep_best = sorted(self.keep_best) checkpoints", "os.path.lexists(old_chk): os.remove(old_chk) if len(self.keep_best) > args.keep_best_checkpoints: for _, x in", "{} (num. trained: {})\".format( sum(p.numel() for p in model.parameters()), sum(p.numel()", "for i, samples in enumerate(progress): with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function( \"train_step-%d\" %", "epoch_itr, valid_subsets, end_of_epoch, saver ) if should_stop: break # log", "checkpoint\") saver.save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) return valid_losses, should_stop def get_training_stats(stats):", "in progress: trainer.valid_step(sample) # log validation stats stats = get_valid_stats(args,", "trainer.get_train_iterator( epoch_itr.next_epoch_idx, # sharded data: get train iterator for next", "args.save_interval_updates == 0 and num_updates >= args.validate_after_updates ) ) do_validate", "max_epoch: # train for one epoch valid_losses, should_stop = train(args,", "p.requires_grad), ) ) # (optionally) Configure quantization if args.quantization_config_path is", "end_of_epoch and do_save) # validate during mid-epoch saves or (end_of_epoch", "if epoch_itr.epoch <= len(args.update_freq) else args.update_freq[-1] ) itr = iterators.GroupedIterator(itr,", "for valid_sub_split in args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split, combine=False, epoch=1) # Build model", "end_of_epoch = epoch_itr.end_of_epoch() updates = trainer.get_num_updates() suffix = getattr(args, \"checkpoint_suffix\",", "args.disable_validation # Validate valid_losses = [None] if do_validate: valid_losses =", "trainer, epoch_itr, val_loss): # only one worker should attempt to", "... # log mid-epoch stats num_updates = trainer.get_num_updates() if num_updates", "%(name)s | %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(), stream=sys.stdout, ) logger", "metrics.reset_meters(\"train_inner\") end_of_epoch = not itr.has_next() valid_losses, should_stop = validate_and_save( args,", "= [] for subset in subsets: logger.info('begin validation on \"{}\"", "valid_losses = [] for subset in subsets: logger.info('begin validation on", "# Save checkpoint if do_save or should_stop: logger.info(\"begin save checkpoint\")", "\"val_loss\": val_loss} if self.best is not None: extra_state.update({\"best\": self.best}) if", "epoch_itr.epoch % args.validate_interval == 0) or num_updates >= max_update or", "iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx > args.curriculum), ) update_freq", "validate during mid-epoch saves or (end_of_epoch and epoch_itr.epoch % args.validate_interval", "else min stats[key] = best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric] ) return stats", "updates, score {}) (writing took {} seconds)\".format( checkpoints[0], epoch, updates,", "the latest checkpoint) for valid_sub_split in args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split, combine=False, epoch=1)", "not args.no_progress_bar else \"simple\"), ) trainer.begin_epoch(epoch_itr.epoch) valid_losses = [None] valid_subsets", "or num_updates >= max_update or ( args.validate_interval_updates > 0 and", "def cli_main(modify_parser=None): parser = options.get_training_parser() args = options.parse_args_and_arch(parser, modify_parser=modify_parser) if", "don't cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) train_meter.stop()", "trainer, task, epoch_itr, saver) if should_stop: break # only use", "fn) for fn, cond in checkpoint_conds.items() if cond ] if", "remove old checkpoints; checkpoints are sorted in descending order checkpoints", "dir if args.distributed_rank == 0: os.makedirs(args.save_dir, exist_ok=True) prev_best = val_loss", "or num_updates >= max_update or ( args.save_interval_updates > 0 and", "are sorted in descending order checkpoints = checkpoint_paths( args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\"", "= ( end_of_epoch and not args.no_epoch_checkpoints and epoch % args.save_interval", "quantizer = quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update, ) else: quantizer =", "source tree. \"\"\" Train a new model on one or", "best_function = max if args.maximize_best_checkpoint_metric else min stats[key] = best_function(", "model, criterion) logger.info( \"training on {} devices (GPUs/TPUs)\".format(args.distributed_world_size) ) logger.info(", "fairseq.model_parallel.megatron_trainer import MegatronTrainer from fairseq.trainer import Trainer logging.basicConfig( format=\"%(asctime)s |", "0: # remove old epoch checkpoints; checkpoints are sorted in", "train_meter = meters.StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch_itr.next_epoch_idx", "* 60) > args.stop_time_hours ) ) # Save checkpoint if", "data below, based on the latest checkpoint) for valid_sub_split in", "iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) # Train until the", "Saver: def __init__(self): self.best = None self.keep_best = [] def", "distributed_utils.call_main(args, main) else: distributed_utils.call_main(args, main) if __name__ == \"__main__\": cli_main()", "trainer.valid_step(sample) # log validation stats stats = get_valid_stats(args, trainer, agg.get_smoothed_values(),", "or --batch-size\" metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print", "None: # not OOM, overflow, ... # log mid-epoch stats", "( (end_of_epoch and epoch_itr.epoch % args.save_interval == 0) or num_updates", "cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) # Train", "% i ): log_output = trainer.train_step(samples) if log_output is not", "cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) train_meter.stop() logger.info(\"done", "Stopping conditions should_stop = ( should_stop_early(args, valid_losses[0]) or num_updates >=", "of epoch {} (average epoch stats below)\".format(epoch_itr.epoch)) stats = get_training_stats(metrics.get_smoothed_values(\"train\"))", "b if args.maximize_best_checkpoint_metric else a <= b write_timer = meters.StopwatchMeter()", ") # Train until the learning rate gets too small", "args.maximize_best_checkpoint_metric else a <= b write_timer = meters.StopwatchMeter() write_timer.start() epoch", "1] if epoch_itr.epoch <= len(args.update_freq) else args.update_freq[-1] ) itr =", "0 and num_updates > 0 and num_updates % args.save_interval_updates ==", "model = task.build_model(args) criterion = task.build_criterion(args) logger.info(model) logger.info(\"task: {} ({})\".format(args.task,", "if args.keep_best_checkpoints > 0 and (len(self.keep_best) < args.keep_best_checkpoints or (", "), default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"), ) # create", "cli_main(modify_parser=None): parser = options.get_training_parser() args = options.parse_args_and_arch(parser, modify_parser=modify_parser) if args.profile:", "min stats[key] = best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric] ) return stats def", "not None or args.batch_size is not None ), \"Must specify", "affiliates. # # This source code is licensed under the", "should attempt to create the required dir if args.distributed_rank ==", "subset\", tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ), default_log_format=(\"tqdm\" if", "should_stop_early(args, valid_loss): # skip check if no validation was done", "agg.get_smoothed_values(), saver) progress.print(stats, tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses def get_valid_stats(args,", "should_stop def validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver): num_updates", "self.best is not None: extra_state.update({\"best\": self.best}) if args.keep_best_checkpoints > 0", "( not save_epoch_checkpoint and args.save_interval_updates > 0 and updates %", "> 0 and updates % args.save_interval_updates == 0 ) checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)]", "step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses def get_valid_stats(args, trainer, stats, saver): stats[\"num_updates\"]", "if one is available and restore the # corresponding train", "b): return a >= b if args.maximize_best_checkpoint_metric else a <=", "sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) train_meter.stop() logger.info(\"done training in {:.1f} seconds\".format(train_meter.sum))", "stats def validate(args, trainer, task, epoch_itr, subsets, saver): \"\"\"Evaluate the", "epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx > args.curriculum), ) update_freq = ( args.update_freq[epoch_itr.epoch", "[] for subset in subsets: logger.info('begin validation on \"{}\" subset'.format(subset))", "default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"), ) # create a", "= args.max_update or math.inf do_save = ( (end_of_epoch and epoch_itr.epoch", "args.min_lr and epoch_itr.next_epoch_idx <= max_epoch: # train for one epoch", "epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) # Train until", "progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f\"valid on '{subset}'", "] if len(checkpoints) > 0: trainer.save_checkpoint(checkpoints[0], extra_state) for cp in", "and ( self.best is None or is_better(val_loss, self.best) ) checkpoint_conds[", "import PathManager from fairseq.logging import metrics, progress_bar from fairseq.model_parallel.megatron_trainer import", "and (len(self.keep_best) < args.keep_best_checkpoints or ( val_loss is not None", "checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] = val_loss is not None and ( self.best is", "aggregators (e.g., train meters) with metrics.aggregate(new_root=True) as agg: for sample", "= quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update, ) else: quantizer = None", "False else: should_stop_early.num_runs += 1 if should_stop_early.num_runs >= args.patience: logger.info(", "suffix, val_loss) checkpoint_conds[ckpt_name] = True self.keep_best.append((val_loss, ckpt_name)) self.keep_best = sorted(self.keep_best)", "get train iterator for next epoch load_dataset=task.has_sharded_data(\"train\"), # don't cache", "= train(args, trainer, task, epoch_itr, saver) if should_stop: break #", "= ( (end_of_epoch and epoch_itr.epoch % args.save_interval == 0) or", ">= max_update or ( args.validate_interval_updates > 0 and num_updates >", "# (optionally) Configure quantization if args.quantization_config_path is not None: quantizer", "data: get train iterator for next epoch load_dataset=task.has_sharded_data(\"train\"), # don't", "new model on one or across multiple GPUs. \"\"\" import", "trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver ) if should_stop: break", "not None ), \"Must specify batch size either with --max-tokens", "should_stop = train(args, trainer, task, epoch_itr, saver) if should_stop: break", "\"best_{0}\".format(args.best_checkpoint_metric) best_function = max if args.maximize_best_checkpoint_metric else min stats[key] =", "metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function( \"train_step-%d\" % i ): log_output = trainer.train_step(samples) if", "multiple GPUs. \"\"\" import collections import logging import math import", "GPU = {} and max sentences per GPU = {}\".format(", "= round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0) return stats def validate(args, trainer, task,", "and epoch_itr.next_epoch_idx <= max_epoch: # train for one epoch valid_losses,", "num_updates >= max_update or ( args.save_interval_updates > 0 and num_updates", "= trainer.get_num_updates() if hasattr(saver.save_checkpoint, \"best\"): key = \"best_{0}\".format(args.best_checkpoint_metric) best_function =", "% args.save_interval_updates == 0 and num_updates >= args.validate_after_updates ) )", "tree. \"\"\" Train a new model on one or across", ") # Save checkpoint if do_save or should_stop: logger.info(\"begin save", "[ os.path.join(args.save_dir, fn) for fn, cond in checkpoint_conds.items() if cond", "get_valid_stats(args, trainer, agg.get_smoothed_values(), saver) progress.print(stats, tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses", "Configure quantization if args.quantization_config_path is not None: quantizer = quantization_utils.Quantizer(", "default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"), ) trainer.begin_epoch(epoch_itr.epoch) valid_losses =", "valid_subsets, saver) # Stopping conditions should_stop = ( should_stop_early(args, valid_losses[0])", "self.keep_best.append((val_loss, ckpt_name)) self.keep_best = sorted(self.keep_best) checkpoints = [ os.path.join(args.save_dir, fn)", "= os.path.join(args.save_dir, x) if os.path.lexists(x): os.remove(x) self.keep_best = self.keep_best[:args.keep_best_checkpoints] def", "args.fixed_validation_seed is not None: # set fixed seed for every", "sharded data: get train iterator for next epoch load_dataset=task.has_sharded_data(\"train\"), #", "Setup task, e.g., translation, language modeling, etc. task = tasks.setup_task(args)", "skip check if no validation was done in the current", "(c) Facebook, Inc. and its affiliates. # # This source", "do_save or should_stop: logger.info(\"begin save checkpoint\") saver.save_checkpoint(args, trainer, epoch_itr, valid_losses[0])", "= val_loss is not None and ( self.best is None", "getattr(args, \"checkpoint_suffix\", \"\") checkpoint_conds = collections.OrderedDict() save_epoch_checkpoint = ( end_of_epoch", "epoch_itr.epoch <= len(args.update_freq) else args.update_freq[-1] ) itr = iterators.GroupedIterator(itr, update_freq)", "restore the # corresponding train iterator extra_state, epoch_itr = checkpoint_utils.load_checkpoint(", "valid_loss is None: return False if args.patience <= 0: return", "| %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(), stream=sys.stdout, ) logger =", "= max if args.maximize_best_checkpoint_metric else min self.best = best_function(val_loss, prev_best)", "= trainer.get_num_updates() for i, samples in enumerate(progress): with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function(", "metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print args logger.info(args)", "> 0 and num_updates > 0 and num_updates % args.save_interval_updates", "None: # set fixed seed for every validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch)", "# Initialize data iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx >", "args.keep_best_checkpoints > 0 and (len(self.keep_best) < args.keep_best_checkpoints or ( val_loss", "valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets, saver) # Stopping", "return validation losses.\"\"\" # Initialize data iterator itr = epoch_itr.next_epoch_itr(", "or is_better(val_loss, self.best) ) checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix) ] = not args.no_last_checkpoints", "{:.1f} seconds\".format(train_meter.sum)) def should_stop_early(args, valid_loss): # skip check if no", "the model for one epoch and return validation losses.\"\"\" #", "is_better(a, b): return a > b if args.maximize_best_checkpoint_metric else a", "# Initialize data iterator itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args, \"tpu\",", "criterion, quantizer) else: trainer = MegatronTrainer(args, task, model, criterion) logger.info(", "small max_epoch = args.max_epoch or math.inf lr = trainer.get_lr() train_meter", "= utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=(", "until the learning rate gets too small max_epoch = args.max_epoch", ") ) return True else: return False @metrics.aggregate(\"train\") def train(args,", "val_loss is not None and not is_better(self.keep_best[-1][0], val_loss))): ckpt_name =", "below, based on the latest checkpoint) for valid_sub_split in args.valid_subset.split(\",\"):", "the losses.\"\"\" if args.fixed_validation_seed is not None: # set fixed", "and args.save_interval_updates > 0 and updates % args.save_interval_updates == 0", "don't pollute other aggregators (e.g., train meters) with metrics.aggregate(new_root=True) as", "in args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split, combine=False, epoch=1) # Build model and criterion", "in self.keep_best[args.keep_best_checkpoints:]: x = os.path.join(args.save_dir, x) if os.path.lexists(x): os.remove(x) self.keep_best", "args.update_freq[epoch_itr.epoch - 1] if epoch_itr.epoch <= len(args.update_freq) else args.update_freq[-1] )", "should_stop_early.num_runs >= args.patience: logger.info( \"early stop since valid performance hasn't", "the end-of-epoch stats will still be preserved metrics.reset_meters(\"train_inner\") end_of_epoch =", "% args.log_interval == 0: stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats, tag=\"train_inner\", step=num_updates)", "\"\"\" import collections import logging import math import os import", "args.profile: with torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main) else: distributed_utils.call_main(args, main)", "batch size either with --max-tokens or --batch-size\" metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed)", "train iterator for next epoch load_dataset=task.has_sharded_data(\"train\"), # don't cache epoch", "should_stop_early.num_runs = 0 return False else: should_stop_early.num_runs += 1 if", "is None or is_better(val_loss, self.best) ) checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix) ] =", "logging.basicConfig( format=\"%(asctime)s | %(levelname)s | %(name)s | %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\",", "directory of this source tree. \"\"\" Train a new model", "task, epoch_itr, saver): \"\"\"Train the model for one epoch and", "epoch_itr, saver) if should_stop: break # only use first validation", "in the # LICENSE file in the root directory of", "agg: for sample in progress: trainer.valid_step(sample) # log validation stats", "get_training_stats(stats): stats[\"wall\"] = round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0) return stats def validate(args,", "not None: # set fixed seed for every validation utils.set_torch_seed(args.fixed_validation_seed)", "args.curriculum), ) update_freq = ( args.update_freq[epoch_itr.epoch - 1] if epoch_itr.epoch", "trainer, task, epoch_itr, saver): \"\"\"Train the model for one epoch", "# log mid-epoch stats num_updates = trainer.get_num_updates() if num_updates %", "return stats def validate(args, trainer, task, epoch_itr, subsets, saver): \"\"\"Evaluate", "0 and num_updates % args.validate_interval_updates == 0 ) ) and", "task.build_model(args) criterion = task.build_criterion(args) logger.info(model) logger.info(\"task: {} ({})\".format(args.task, task.__class__.__name__)) logger.info(\"model:", "# validate during mid-epoch saves or (end_of_epoch and epoch_itr.epoch %", "saver ) if should_stop: break # log end-of-epoch stats logger.info(\"end", "min self.best = best_function(val_loss, prev_best) if args.no_save: return trainer.consolidate_optimizer() if", "itr = iterators.GroupedIterator(itr, update_freq) if getattr(args, \"tpu\", False): itr =", "model.parameters() if p.requires_grad), ) ) # (optionally) Configure quantization if", "saver): stats[\"num_updates\"] = trainer.get_num_updates() if hasattr(saver.save_checkpoint, \"best\"): key = \"best_{0}\".format(args.best_checkpoint_metric)", "[] def save_checkpoint(self, args, trainer, epoch_itr, val_loss): # only one", "\"best\"): key = \"best_{0}\".format(args.best_checkpoint_metric) best_function = max if args.maximize_best_checkpoint_metric else", "if args.patience <= 0: return False def is_better(a, b): return", "config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update, ) else: quantizer = None # Build", "the latest checkpoint if one is available and restore the", "for one epoch valid_losses, should_stop = train(args, trainer, task, epoch_itr,", "stop since valid performance hasn't improved for last {} runs\".format(", "> args.keep_best_checkpoints: for _, x in self.keep_best[args.keep_best_checkpoints:]: x = os.path.join(args.save_dir,", "), \"Must specify batch size either with --max-tokens or --batch-size\"", "args.no_progress_bar else \"simple\"), ) # create a new root metrics", "format=\"%(asctime)s | %(levelname)s | %(name)s | %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", level=os.environ.get(\"LOGLEVEL\",", "@ {} updates, score {}) (writing took {} seconds)\".format( checkpoints[0],", "progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir if", "if os.path.lexists(x): os.remove(x) self.keep_best = self.keep_best[:args.keep_best_checkpoints] def main(args): saver =", "= trainer.get_num_updates() if num_updates % args.log_interval == 0: stats =", "log interval # the end-of-epoch stats will still be preserved", ") return stats def cli_main(modify_parser=None): parser = options.get_training_parser() args =", "dataset (we load training data below, based on the latest", "max_update or ( args.stop_time_hours > 0 and trainer.cumulative_training_time() / (60", "and num_updates > 0 and num_updates % args.validate_interval_updates == 0", "the learning rate gets too small max_epoch = args.max_epoch or", "performance hasn't improved for last {} runs\".format( args.patience ) )", "val_loss): # only one worker should attempt to create the", "0 ) checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)] = save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates, suffix)] =", "Load valid dataset (we load training data below, based on", "or args.batch_size is not None ), \"Must specify batch size", "== 1: trainer = Trainer(args, task, model, criterion, quantizer) else:", "epoch_itr.next_epoch_idx <= max_epoch: # train for one epoch valid_losses, should_stop", "# Stopping conditions should_stop = ( should_stop_early(args, valid_losses[0]) or num_updates", "validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver): num_updates = trainer.get_num_updates()", ") logger = logging.getLogger(\"fairseq_cli.train\") class Saver: def __init__(self): self.best =", "Train a new model on one or across multiple GPUs.", ") for old_chk in checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk): os.remove(old_chk) if args.keep_last_epochs", "None # Build trainer if args.model_parallel_size == 1: trainer =", "validation on \"{}\" subset'.format(subset)) # Initialize data iterator itr =", "valid_losses[0]) or num_updates >= max_update or ( args.stop_time_hours > 0", "checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix) ] = not args.no_last_checkpoints extra_state = {\"train_iterator\": epoch_itr.state_dict(),", "task, epoch_itr, saver) if should_stop: break # only use first", "_, x in self.keep_best[args.keep_best_checkpoints:]: x = os.path.join(args.save_dir, x) if os.path.lexists(x):", "\"Must specify batch size either with --max-tokens or --batch-size\" metrics.reset()", "(end_of_epoch and epoch_itr.epoch % args.validate_interval == 0) or num_updates >=", "torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main) else: distributed_utils.call_main(args, main) if __name__", "logger.info( \"early stop since valid performance hasn't improved for last", "trainer.cumulative_training_time() / (60 * 60) > args.stop_time_hours ) ) #", "import numpy as np import torch from fairseq import (", "and num_updates >= args.validate_after_updates ) ) do_validate = ( (not", "num_updates >= max_update or ( args.validate_interval_updates > 0 and num_updates", "params: {} (num. trained: {})\".format( sum(p.numel() for p in model.parameters()),", "loss to update the learning rate lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0])", "update the learning rate lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr =", "<= len(args.update_freq) else args.update_freq[-1] ) itr = iterators.GroupedIterator(itr, update_freq) if", "stats[\"wall\"] = round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0) return stats def validate(args, trainer,", "write_timer.sum ) ) if not end_of_epoch and args.keep_interval_updates > 0:", "in model.parameters() if p.requires_grad), ) ) # (optionally) Configure quantization", "{} and max sentences per GPU = {}\".format( args.max_tokens, args.batch_size", "if not end_of_epoch and args.keep_interval_updates > 0: # remove old", "= getattr(should_stop_early, \"best\", None) if prev_best is None or is_better(valid_loss,", "None: extra_state.update({\"best\": self.best}) if args.keep_best_checkpoints > 0 and (len(self.keep_best) <", "updates = trainer.get_num_updates() suffix = getattr(args, \"checkpoint_suffix\", \"\") checkpoint_conds =", "the # corresponding train iterator extra_state, epoch_itr = checkpoint_utils.load_checkpoint( args,", "so validation metrics # don't pollute other aggregators (e.g., train", "= args.valid_subset.split(\",\") should_stop = False num_updates = trainer.get_num_updates() for i,", "def is_better(a, b): return a > b if args.maximize_best_checkpoint_metric else", "# Print args logger.info(args) # Setup task, e.g., translation, language", "== 0: os.makedirs(args.save_dir, exist_ok=True) prev_best = val_loss if self.best is", "0) or num_updates >= max_update or ( args.validate_interval_updates > 0", "Build model and criterion model = task.build_model(args) criterion = task.build_criterion(args)", "max_update or ( args.validate_interval_updates > 0 and num_updates > 0", "# don't pollute other aggregators (e.g., train meters) with metrics.aggregate(new_root=True)", "trainer.consolidate_optimizer() if not trainer.is_data_parallel_master: return def is_better(a, b): return a", "= trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args, \"tpu\", False): itr = utils.tpu_data_loader(itr) progress", "for old_chk in checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk): os.remove(old_chk) if len(self.keep_best) >", "b write_timer = meters.StopwatchMeter() write_timer.start() epoch = epoch_itr.epoch end_of_epoch =", "\"simple\"), ) trainer.begin_epoch(epoch_itr.epoch) valid_losses = [None] valid_subsets = args.valid_subset.split(\",\") should_stop", "trainer, task, epoch_itr, valid_subsets, saver) # Stopping conditions should_stop =", "self.best is None else self.best if val_loss is not None:", "file in the root directory of this source tree. \"\"\"", "model params: {} (num. trained: {})\".format( sum(p.numel() for p in", "task, model, criterion) logger.info( \"training on {} devices (GPUs/TPUs)\".format(args.distributed_world_size) )", "save_checkpoint(self, args, trainer, epoch_itr, val_loss): # only one worker should", "Validate valid_losses = [None] if do_validate: valid_losses = validate(args, trainer,", "checkpoints[1:]: PathManager.copy(checkpoints[0], cp, overwrite=True) write_timer.stop() logger.info( \"saved checkpoint {} (epoch", "if len(checkpoints) > 0: trainer.save_checkpoint(checkpoints[0], extra_state) for cp in checkpoints[1:]:", "itr = utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch,", "validation was done in the current epoch if valid_loss is", "metrics # don't pollute other aggregators (e.g., train meters) with", "or num_updates >= max_update or ( args.stop_time_hours > 0 and", "0) or num_updates >= max_update or ( args.save_interval_updates > 0", ") ) and not args.disable_validation # Validate valid_losses = [None]", "> b if args.maximize_best_checkpoint_metric else a < b prev_best =", "and not args.disable_validation # Validate valid_losses = [None] if do_validate:", "= None # Build trainer if args.model_parallel_size == 1: trainer", "is licensed under the MIT license found in the #", "Saver() utils.import_user_module(args) assert ( args.max_tokens is not None or args.batch_size", "distributed_utils, options, quantization_utils, tasks, utils, ) from fairseq import meters", "prev_best = getattr(should_stop_early, \"best\", None) if prev_best is None or", "for fn, cond in checkpoint_conds.items() if cond ] if len(checkpoints)", "valid performance hasn't improved for last {} runs\".format( args.patience )", "with metrics.aggregate(new_root=True) as agg: for sample in progress: trainer.valid_step(sample) #", ") checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix) ] = not args.no_last_checkpoints extra_state = {\"train_iterator\":", "# Validate valid_losses = [None] if do_validate: valid_losses = validate(args,", "one epoch valid_losses, should_stop = train(args, trainer, task, epoch_itr, saver)", "max if args.maximize_best_checkpoint_metric else min stats[key] = best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric]", "and epoch_itr.epoch % args.save_interval == 0) or num_updates >= max_update", ">= max_update or ( args.stop_time_hours > 0 and trainer.cumulative_training_time() /", "fairseq import meters from fairseq.checkpoint_utils import checkpoint_paths from fairseq.data import", "stats, saver): stats[\"num_updates\"] = trainer.get_num_updates() if hasattr(saver.save_checkpoint, \"best\"): key =", "trainer, epoch_itr, valid_losses[0]) return valid_losses, should_stop def get_training_stats(stats): stats[\"wall\"] =", "Initialize data iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx > args.curriculum),", "log validation stats stats = get_valid_stats(args, trainer, agg.get_smoothed_values(), saver) progress.print(stats,", "from fairseq import ( checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils,", "checkpoints = [ os.path.join(args.save_dir, fn) for fn, cond in checkpoint_conds.items()", "if distributed_utils.is_master(args) else None ), default_log_format=(\"tqdm\" if not args.no_progress_bar else", "should_stop = False num_updates = trainer.get_num_updates() for i, samples in", "args.save_interval_updates > 0 and num_updates > 0 and num_updates %", "log_output is not None: # not OOM, overflow, ... #", "from fairseq.model_parallel.megatron_trainer import MegatronTrainer from fairseq.trainer import Trainer logging.basicConfig( format=\"%(asctime)s", "not args.no_epoch_checkpoints and epoch % args.save_interval == 0 ) checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch,", ") # (optionally) Configure quantization if args.quantization_config_path is not None:", "# not OOM, overflow, ... # log mid-epoch stats num_updates", "trainer.save_checkpoint(checkpoints[0], extra_state) for cp in checkpoints[1:]: PathManager.copy(checkpoints[0], cp, overwrite=True) write_timer.stop()", "model for one epoch and return validation losses.\"\"\" # Initialize", "= 0 return False else: should_stop_early.num_runs += 1 if should_stop_early.num_runs", "in enumerate(progress): with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function( \"train_step-%d\" % i ): log_output", "0 and num_updates % args.save_interval_updates == 0 and num_updates >=", "or should_stop: logger.info(\"begin save checkpoint\") saver.save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) return", "= ( args.update_freq[epoch_itr.epoch - 1] if epoch_itr.epoch <= len(args.update_freq) else", ") return True else: return False @metrics.aggregate(\"train\") def train(args, trainer,", "either with --max-tokens or --batch-size\" metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_utils.is_master(args):", "in the root directory of this source tree. \"\"\" Train", "current epoch if valid_loss is None: return False if args.patience", "prev_best): should_stop_early.best = valid_loss should_stop_early.num_runs = 0 return False else:", "= trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr = trainer.get_train_iterator( epoch_itr.next_epoch_idx, # sharded data:", "logger.info(\"begin save checkpoint\") saver.save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) return valid_losses, should_stop", "None: return False if args.patience <= 0: return False def", "prefix=f\"valid on '{subset}' subset\", tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None", "p in model.parameters() if p.requires_grad), ) ) # (optionally) Configure", "stats def cli_main(modify_parser=None): parser = options.get_training_parser() args = options.parse_args_and_arch(parser, modify_parser=modify_parser)", "num_updates % args.save_interval_updates == 0 and num_updates >= args.validate_after_updates )", "best_function = max if args.maximize_best_checkpoint_metric else min self.best = best_function(val_loss,", "under the MIT license found in the # LICENSE file", "fairseq.logging import metrics, progress_bar from fairseq.model_parallel.megatron_trainer import MegatronTrainer from fairseq.trainer", "max_epoch=args.max_epoch, max_update=args.max_update, ) else: quantizer = None # Build trainer", "{})\".format( sum(p.numel() for p in model.parameters()), sum(p.numel() for p in", "logger.info( \"criterion: {} ({})\".format(args.criterion, criterion.__class__.__name__) ) logger.info( \"num. model params:", "return the losses.\"\"\" if args.fixed_validation_seed is not None: # set", "val_loss} if self.best is not None: extra_state.update({\"best\": self.best}) if args.keep_best_checkpoints", "root directory of this source tree. \"\"\" Train a new", "trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver): num_updates = trainer.get_num_updates() max_update", "or ( args.validate_interval_updates > 0 and num_updates > 0 and", "valid_losses[0]) return valid_losses, should_stop def get_training_stats(stats): stats[\"wall\"] = round(metrics.get_meter(\"default\", \"wall\").elapsed_time,", "i ): log_output = trainer.train_step(samples) if log_output is not None:", "sys import numpy as np import torch from fairseq import", "= trainer.get_num_updates() suffix = getattr(args, \"checkpoint_suffix\", \"\") checkpoint_conds = collections.OrderedDict()", "epoch-level meters metrics.reset_meters(\"train\") return valid_losses, should_stop def validate_and_save(args, trainer, task,", "should_stop: break # log end-of-epoch stats logger.info(\"end of epoch {}", "def is_better(a, b): return a >= b if args.maximize_best_checkpoint_metric else", "losses.\"\"\" # Initialize data iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx", "should_stop_early.num_runs += 1 if should_stop_early.num_runs >= args.patience: logger.info( \"early stop", "the MIT license found in the # LICENSE file in", "= args.max_epoch or math.inf lr = trainer.get_lr() train_meter = meters.StopwatchMeter()", "took {} seconds)\".format( checkpoints[0], epoch, updates, val_loss, write_timer.sum ) )", "if args.maximize_best_checkpoint_metric else min stats[key] = best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric] )", "combine=False, epoch=1) # Build model and criterion model = task.build_model(args)", "fairseq.file_io import PathManager from fairseq.logging import metrics, progress_bar from fairseq.model_parallel.megatron_trainer", "not None: extra_state.update({\"best\": self.best}) if args.keep_best_checkpoints > 0 and (len(self.keep_best)", "# set fixed seed for every validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses", "epoch if valid_loss is None: return False if args.patience <=", "per GPU = {} and max sentences per GPU =", "not None and ( self.best is None or is_better(val_loss, self.best)", "meters.StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch_itr.next_epoch_idx <= max_epoch:", "subset'.format(subset)) # Initialize data iterator itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args,", "other aggregators (e.g., train meters) with metrics.aggregate(new_root=True) as agg: for", "only use first validation loss to update the learning rate", "update_freq) if getattr(args, \"tpu\", False): itr = utils.tpu_data_loader(itr) progress =", "( args.stop_time_hours > 0 and trainer.cumulative_training_time() / (60 * 60)", "task = tasks.setup_task(args) # Load valid dataset (we load training", "<= b write_timer = meters.StopwatchMeter() write_timer.start() epoch = epoch_itr.epoch end_of_epoch", "and num_updates % args.save_interval_updates == 0 and num_updates >= args.validate_after_updates", "= ( not save_epoch_checkpoint and args.save_interval_updates > 0 and updates", "modeling, etc. task = tasks.setup_task(args) # Load valid dataset (we", "if args.keep_last_epochs > 0: # remove old epoch checkpoints; checkpoints", "= iterators.GroupedIterator(itr, update_freq) if getattr(args, \"tpu\", False): itr = utils.tpu_data_loader(itr)", "= best_function(val_loss, prev_best) if args.no_save: return trainer.consolidate_optimizer() if not trainer.is_data_parallel_master:", "# Train until the learning rate gets too small max_epoch", "not is_better(self.keep_best[-1][0], val_loss))): ckpt_name = \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix, val_loss) if save_epoch_checkpoint", "trainer.begin_epoch(epoch_itr.epoch) valid_losses = [None] valid_subsets = args.valid_subset.split(\",\") should_stop = False", "logger.info( \"max tokens per GPU = {} and max sentences", "losses.\"\"\" if args.fixed_validation_seed is not None: # set fixed seed", "#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its", "prev_best) if args.no_save: return trainer.consolidate_optimizer() if not trainer.is_data_parallel_master: return def", "itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f\"valid on '{subset}' subset\", tensorboard_logdir=( args.tensorboard_logdir", "and return the losses.\"\"\" if args.fixed_validation_seed is not None: #", "= validate_and_save( args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver )", "get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats, tag=\"train_inner\", step=num_updates) # reset mid-epoch stats after each", "< b prev_best = getattr(should_stop_early, \"best\", None) if prev_best is", "None else self.best if val_loss is not None: best_function =", "metrics, progress_bar from fairseq.model_parallel.megatron_trainer import MegatronTrainer from fairseq.trainer import Trainer", "args.distributed_rank == 0: os.makedirs(args.save_dir, exist_ok=True) prev_best = val_loss if self.best", "validate(args, trainer, task, epoch_itr, subsets, saver): \"\"\"Evaluate the model on", "valid_losses = [None] valid_subsets = args.valid_subset.split(\",\") should_stop = False num_updates", "do_save = ( (end_of_epoch and epoch_itr.epoch % args.save_interval == 0)", "0 return False else: should_stop_early.num_runs += 1 if should_stop_early.num_runs >=", "= progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f\"valid on '{subset}' subset\",", "use first validation loss to update the learning rate lr", "fn, cond in checkpoint_conds.items() if cond ] if len(checkpoints) >", "updates % args.save_interval_updates == 0 ) checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] = val_loss is", "sum(p.numel() for p in model.parameters()), sum(p.numel() for p in model.parameters()", "MegatronTrainer(args, task, model, criterion) logger.info( \"training on {} devices (GPUs/TPUs)\".format(args.distributed_world_size)", "( should_stop_early(args, valid_losses[0]) or num_updates >= max_update or ( args.stop_time_hours", "None: quantizer = quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update, ) else: quantizer", "valid_subsets = args.valid_subset.split(\",\") should_stop = False num_updates = trainer.get_num_updates() for", "if prev_best is None or is_better(valid_loss, prev_best): should_stop_early.best = valid_loss", "fixed seed for every validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses = []", "options.get_training_parser() args = options.parse_args_and_arch(parser, modify_parser=modify_parser) if args.profile: with torch.cuda.profiler.profile(): with", "self.best) ) checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix) ] = not args.no_last_checkpoints extra_state =", "extra_state = {\"train_iterator\": epoch_itr.state_dict(), \"val_loss\": val_loss} if self.best is not", "def train(args, trainer, task, epoch_itr, saver): \"\"\"Train the model for", "log mid-epoch stats num_updates = trainer.get_num_updates() if num_updates % args.log_interval", "save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates, suffix)] = ( not save_epoch_checkpoint and args.save_interval_updates", ") if should_stop: break # log end-of-epoch stats logger.info(\"end of", "checkpoints; checkpoints are sorted in descending order checkpoints = checkpoint_paths(", "parser = options.get_training_parser() args = options.parse_args_and_arch(parser, modify_parser=modify_parser) if args.profile: with", "x = os.path.join(args.save_dir, x) if os.path.lexists(x): os.remove(x) self.keep_best = self.keep_best[:args.keep_best_checkpoints]", "logging import math import os import sys import numpy as", "trainer.get_num_updates() if num_updates % args.log_interval == 0: stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\"))", "or math.inf do_save = ( (end_of_epoch and epoch_itr.epoch % args.save_interval", "cp, overwrite=True) write_timer.stop() logger.info( \"saved checkpoint {} (epoch {} @", "args.maximize_best_checkpoint_metric else a < b prev_best = getattr(should_stop_early, \"best\", None)", "train meters) with metrics.aggregate(new_root=True) as agg: for sample in progress:", "or ( args.stop_time_hours > 0 and trainer.cumulative_training_time() / (60 *", "stats will still be preserved metrics.reset_meters(\"train_inner\") end_of_epoch = not itr.has_next()", "os.makedirs(args.save_dir, exist_ok=True) prev_best = val_loss if self.best is None else", "translation, language modeling, etc. task = tasks.setup_task(args) # Load valid", "on one or across multiple GPUs. \"\"\" import collections import", "== 0) or num_updates >= max_update or ( args.validate_interval_updates >", "Copyright (c) Facebook, Inc. and its affiliates. # # This", "checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils, ) from fairseq import", "= checkpoint_paths( args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" ) for old_chk in checkpoints[args.keep_interval_updates:]: if", "the validation set(s) and return the losses.\"\"\" if args.fixed_validation_seed is", "epoch_itr = trainer.get_train_iterator( epoch_itr.next_epoch_idx, # sharded data: get train iterator", "save_epoch_checkpoint \\ else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates, suffix, val_loss) checkpoint_conds[ckpt_name] = True", "= trainer.get_num_updates() max_update = args.max_update or math.inf do_save = (", "a >= b if args.maximize_best_checkpoint_metric else a <= b write_timer", "prev_best is None or is_better(valid_loss, prev_best): should_stop_early.best = valid_loss should_stop_early.num_runs", "= valid_loss should_stop_early.num_runs = 0 return False else: should_stop_early.num_runs +=", "step=num_updates) # reset mid-epoch stats after each log interval #", "| %(name)s | %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(), stream=sys.stdout, )", "= {}\".format( args.max_tokens, args.batch_size ) ) # Load the latest", "(end_of_epoch and epoch_itr.epoch % args.save_interval == 0) or num_updates >=", "# LICENSE file in the root directory of this source", "{} ({})\".format(args.arch, model.__class__.__name__)) logger.info( \"criterion: {} ({})\".format(args.criterion, criterion.__class__.__name__) ) logger.info(", "> 0 and num_updates > 0 and num_updates % args.validate_interval_updates", "Trainer(args, task, model, criterion, quantizer) else: trainer = MegatronTrainer(args, task,", "args.stop_time_hours ) ) # Save checkpoint if do_save or should_stop:", "be preserved metrics.reset_meters(\"train_inner\") end_of_epoch = not itr.has_next() valid_losses, should_stop =", "found in the # LICENSE file in the root directory", "should_stop def get_training_stats(stats): stats[\"wall\"] = round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0) return stats", "during mid-epoch saves or (end_of_epoch and epoch_itr.epoch % args.validate_interval ==", "= [ os.path.join(args.save_dir, fn) for fn, cond in checkpoint_conds.items() if", "log_output = trainer.train_step(samples) if log_output is not None: # not", "max sentences per GPU = {}\".format( args.max_tokens, args.batch_size ) )", "True else: return False @metrics.aggregate(\"train\") def train(args, trainer, task, epoch_itr,", "not itr.has_next() valid_losses, should_stop = validate_and_save( args, trainer, task, epoch_itr,", "args, trainer, epoch_itr, val_loss): # only one worker should attempt", "preserved metrics.reset_meters(\"train_inner\") end_of_epoch = not itr.has_next() valid_losses, should_stop = validate_and_save(", "== 0 ) ) and not args.disable_validation # Validate valid_losses", "should_stop: break # only use first validation loss to update", "epoch load_dataset=task.has_sharded_data(\"train\"), # don't cache epoch iterators for sharded datasets", "task, model, criterion, quantizer) else: trainer = MegatronTrainer(args, task, model,", "torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main) else: distributed_utils.call_main(args, main) if __name__ == \"__main__\":", "if do_save or should_stop: logger.info(\"begin save checkpoint\") saver.save_checkpoint(args, trainer, epoch_itr,", "import torch from fairseq import ( checkpoint_utils, distributed_utils, options, quantization_utils,", "<= 0: return False def is_better(a, b): return a >", "valid_subsets, end_of_epoch, saver): num_updates = trainer.get_num_updates() max_update = args.max_update or", "torch from fairseq import ( checkpoint_utils, distributed_utils, options, quantization_utils, tasks,", "os.remove(x) self.keep_best = self.keep_best[:args.keep_best_checkpoints] def main(args): saver = Saver() utils.import_user_module(args)", "valid_losses[0]) epoch_itr = trainer.get_train_iterator( epoch_itr.next_epoch_idx, # sharded data: get train", "in descending order checkpoints = checkpoint_paths( args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" ) for", "datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) # Train until the learning rate gets", "epoch_itr.epoch % args.save_interval == 0) or num_updates >= max_update or", "saver.save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) return valid_losses, should_stop def get_training_stats(stats): stats[\"wall\"]", "load training data below, based on the latest checkpoint) for", "and do_save) # validate during mid-epoch saves or (end_of_epoch and", "= Trainer(args, task, model, criterion, quantizer) else: trainer = MegatronTrainer(args,", "This source code is licensed under the MIT license found", "= get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats, tag=\"train_inner\", step=num_updates) # reset mid-epoch stats after", "== 0 ) checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] = val_loss is not None and", "sorted in descending order checkpoints = checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\") for old_chk", "args.patience ) ) return True else: return False @metrics.aggregate(\"train\") def", ") from fairseq import meters from fairseq.checkpoint_utils import checkpoint_paths from", "args.no_last_checkpoints extra_state = {\"train_iterator\": epoch_itr.state_dict(), \"val_loss\": val_loss} if self.best is", "one or across multiple GPUs. \"\"\" import collections import logging", "sentences per GPU = {}\".format( args.max_tokens, args.batch_size ) ) #", "else: should_stop_early.num_runs += 1 if should_stop_early.num_runs >= args.patience: logger.info( \"early", "> 0 and num_updates % args.save_interval_updates == 0 and num_updates", "args.stop_time_hours > 0 and trainer.cumulative_training_time() / (60 * 60) >", "os.path.join(args.save_dir, fn) for fn, cond in checkpoint_conds.items() if cond ]", "trainer.get_lr() train_meter = meters.StopwatchMeter() train_meter.start() while lr > args.min_lr and", "= getattr(args, \"checkpoint_suffix\", \"\") checkpoint_conds = collections.OrderedDict() save_epoch_checkpoint = (", "iterator extra_state, epoch_itr = checkpoint_utils.load_checkpoint( args, trainer, # don't cache", "is None or is_better(valid_loss, prev_best): should_stop_early.best = valid_loss should_stop_early.num_runs =", "= trainer.train_step(samples) if log_output is not None: # not OOM,", "log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ), default_log_format=(\"tqdm\"", "logging.getLogger(\"fairseq_cli.train\") class Saver: def __init__(self): self.best = None self.keep_best =", "is_better(a, b): return a >= b if args.maximize_best_checkpoint_metric else a", "validate_and_save( args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver ) if", "to update the learning rate lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr", "trained: {})\".format( sum(p.numel() for p in model.parameters()), sum(p.numel() for p", "end_of_epoch = not itr.has_next() valid_losses, should_stop = validate_and_save( args, trainer,", "attempt to create the required dir if args.distributed_rank == 0:", "# the end-of-epoch stats will still be preserved metrics.reset_meters(\"train_inner\") end_of_epoch", "validate(args, trainer, task, epoch_itr, valid_subsets, saver) # Stopping conditions should_stop", "break # log end-of-epoch stats logger.info(\"end of epoch {} (average", "\"best\", None) if prev_best is None or is_better(valid_loss, prev_best): should_stop_early.best", "\"{}\" subset'.format(subset)) # Initialize data iterator itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if", "shuffle=(epoch_itr.next_epoch_idx > args.curriculum), ) update_freq = ( args.update_freq[epoch_itr.epoch - 1]", "with torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main) else: distributed_utils.call_main(args, main) if", "check if no validation was done in the current epoch", "args.batch_size is not None ), \"Must specify batch size either", "validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses = [] for subset in subsets:", "-u # Copyright (c) Facebook, Inc. and its affiliates. #", ") trainer.begin_epoch(epoch_itr.epoch) valid_losses = [None] valid_subsets = args.valid_subset.split(\",\") should_stop =", "checkpoint if do_save or should_stop: logger.info(\"begin save checkpoint\") saver.save_checkpoint(args, trainer,", "x in self.keep_best[args.keep_best_checkpoints:]: x = os.path.join(args.save_dir, x) if os.path.lexists(x): os.remove(x)", "no validation was done in the current epoch if valid_loss", "tag=\"train_inner\", step=num_updates) # reset mid-epoch stats after each log interval", "validation loss to update the learning rate lr = trainer.lr_step(epoch_itr.epoch,", "return valid_losses, should_stop def get_training_stats(stats): stats[\"wall\"] = round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0)", "args.no_progress_bar else \"simple\"), ) trainer.begin_epoch(epoch_itr.epoch) valid_losses = [None] valid_subsets =", "else: trainer = MegatronTrainer(args, task, model, criterion) logger.info( \"training on", "args.validate_interval_updates == 0 ) ) and not args.disable_validation # Validate", "\"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix, val_loss) if save_epoch_checkpoint \\ else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates, suffix,", "class Saver: def __init__(self): self.best = None self.keep_best = []", "{\"train_iterator\": epoch_itr.state_dict(), \"val_loss\": val_loss} if self.best is not None: extra_state.update({\"best\":", "def __init__(self): self.best = None self.keep_best = [] def save_checkpoint(self,", "suffix)] = ( not save_epoch_checkpoint and args.save_interval_updates > 0 and", "if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print args logger.info(args) # Setup task,", "args.keep_last_epochs > 0: # remove old epoch checkpoints; checkpoints are", "lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr = trainer.get_train_iterator( epoch_itr.next_epoch_idx, # sharded", "= ( (not end_of_epoch and do_save) # validate during mid-epoch", "metrics aggregator so validation metrics # don't pollute other aggregators", ") checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)] = save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates, suffix)] = (", "% args.save_interval == 0) or num_updates >= max_update or (", "if should_stop: break # log end-of-epoch stats logger.info(\"end of epoch", "= [None] if do_validate: valid_losses = validate(args, trainer, task, epoch_itr,", "and criterion model = task.build_model(args) criterion = task.build_criterion(args) logger.info(model) logger.info(\"task:", "based on the latest checkpoint) for valid_sub_split in args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split,", "not None: # not OOM, overflow, ... # log mid-epoch", "( checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils, ) from fairseq", "is None else self.best if val_loss is not None: best_function", "iterator for next epoch load_dataset=task.has_sharded_data(\"train\"), # don't cache epoch iterators", "if should_stop_early.num_runs >= args.patience: logger.info( \"early stop since valid performance", "overflow, ... # log mid-epoch stats num_updates = trainer.get_num_updates() if", "%H:%M:%S\", level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(), stream=sys.stdout, ) logger = logging.getLogger(\"fairseq_cli.train\") class Saver:", "0: return False def is_better(a, b): return a > b", "specify batch size either with --max-tokens or --batch-size\" metrics.reset() np.random.seed(args.seed)", "stats below)\".format(epoch_itr.epoch)) stats = get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats, tag=\"train\", step=num_updates) # reset", "\"INFO\").upper(), stream=sys.stdout, ) logger = logging.getLogger(\"fairseq_cli.train\") class Saver: def __init__(self):", "PathManager.copy(checkpoints[0], cp, overwrite=True) write_timer.stop() logger.info( \"saved checkpoint {} (epoch {}", "tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ), default_log_format=(\"tqdm\" if not", "suffix)] = save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates, suffix)] = ( not save_epoch_checkpoint", "self.keep_best[args.keep_best_checkpoints:]: x = os.path.join(args.save_dir, x) if os.path.lexists(x): os.remove(x) self.keep_best =", "%(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\", level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(), stream=sys.stdout, ) logger = logging.getLogger(\"fairseq_cli.train\")", "log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ),", "({})\".format(args.arch, model.__class__.__name__)) logger.info( \"criterion: {} ({})\".format(args.criterion, criterion.__class__.__name__) ) logger.info( \"num.", "collections.OrderedDict() save_epoch_checkpoint = ( end_of_epoch and not args.no_epoch_checkpoints and epoch", "or (end_of_epoch and epoch_itr.epoch % args.validate_interval == 0) or num_updates", "corresponding train iterator extra_state, epoch_itr = checkpoint_utils.load_checkpoint( args, trainer, #", "create the required dir if args.distributed_rank == 0: os.makedirs(args.save_dir, exist_ok=True)", ") train_meter.stop() logger.info(\"done training in {:.1f} seconds\".format(train_meter.sum)) def should_stop_early(args, valid_loss):", "progress.print(stats, tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses def get_valid_stats(args, trainer, stats,", "return False if args.patience <= 0: return False def is_better(a,", "= task.build_criterion(args) logger.info(model) logger.info(\"task: {} ({})\".format(args.task, task.__class__.__name__)) logger.info(\"model: {} ({})\".format(args.arch,", "lr > args.min_lr and epoch_itr.next_epoch_idx <= max_epoch: # train for", "None ), default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"), ) trainer.begin_epoch(epoch_itr.epoch)", ") checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] = val_loss is not None and ( self.best", "code is licensed under the MIT license found in the", "trainer, task, epoch_itr, subsets, saver): \"\"\"Evaluate the model on the", "if p.requires_grad), ) ) # (optionally) Configure quantization if args.quantization_config_path", "# reset mid-epoch stats after each log interval # the", "the current epoch if valid_loss is None: return False if", "logger.info(\"done training in {:.1f} seconds\".format(train_meter.sum)) def should_stop_early(args, valid_loss): # skip", "Facebook, Inc. and its affiliates. # # This source code", "should_stop = ( should_stop_early(args, valid_losses[0]) or num_updates >= max_update or", "task, epoch_itr, valid_subsets, saver) # Stopping conditions should_stop = (", "valid_losses, should_stop def get_training_stats(stats): stats[\"wall\"] = round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0) return", "max if args.maximize_best_checkpoint_metric else min self.best = best_function(val_loss, prev_best) if", "PathManager from fairseq.logging import metrics, progress_bar from fairseq.model_parallel.megatron_trainer import MegatronTrainer", "args logger.info(args) # Setup task, e.g., translation, language modeling, etc.", "import iterators from fairseq.file_io import PathManager from fairseq.logging import metrics,", "and epoch_itr.epoch % args.validate_interval == 0) or num_updates >= max_update", "# # This source code is licensed under the MIT", "num_updates >= max_update or ( args.stop_time_hours > 0 and trainer.cumulative_training_time()", "worker should attempt to create the required dir if args.distributed_rank", "do_save) # validate during mid-epoch saves or (end_of_epoch and epoch_itr.epoch", "disable_iterator_cache=task.has_sharded_data(\"train\"), ) # Train until the learning rate gets too", "is_better(valid_loss, prev_best): should_stop_early.best = valid_loss should_stop_early.num_runs = 0 return False", ") ) # (optionally) Configure quantization if args.quantization_config_path is not", "get_valid_stats(args, trainer, stats, saver): stats[\"num_updates\"] = trainer.get_num_updates() if hasattr(saver.save_checkpoint, \"best\"):", "save_epoch_checkpoint = ( end_of_epoch and not args.no_epoch_checkpoints and epoch %", "GPU = {}\".format( args.max_tokens, args.batch_size ) ) # Load the", "epoch_itr.end_of_epoch() updates = trainer.get_num_updates() suffix = getattr(args, \"checkpoint_suffix\", \"\") checkpoint_conds", "end_of_epoch, saver): num_updates = trainer.get_num_updates() max_update = args.max_update or math.inf", "<= max_epoch: # train for one epoch valid_losses, should_stop =", "prev_best = val_loss if self.best is None else self.best if", "progress_bar from fairseq.model_parallel.megatron_trainer import MegatronTrainer from fairseq.trainer import Trainer logging.basicConfig(", "datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) train_meter.stop() logger.info(\"done training in {:.1f} seconds\".format(train_meter.sum)) def", "if self.best is not None: extra_state.update({\"best\": self.best}) if args.keep_best_checkpoints >", "quantization if args.quantization_config_path is not None: quantizer = quantization_utils.Quantizer( config_path=args.quantization_config_path,", "False): itr = utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval,", "model on the validation set(s) and return the losses.\"\"\" if", "root metrics aggregator so validation metrics # don't pollute other", "iterators from fairseq.file_io import PathManager from fairseq.logging import metrics, progress_bar", "checkpoints are sorted in descending order checkpoints = checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\")", "if valid_loss is None: return False if args.patience <= 0:", "(len(self.keep_best) < args.keep_best_checkpoints or ( val_loss is not None and", "{} ({})\".format(args.task, task.__class__.__name__)) logger.info(\"model: {} ({})\".format(args.arch, model.__class__.__name__)) logger.info( \"criterion: {}", "% args.save_interval_updates == 0 ) checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] = val_loss is not", "distributed_utils.is_master(args) else None ), default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"),", "= checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\") for old_chk in checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk): os.remove(old_chk)", "getattr(should_stop_early, \"best\", None) if prev_best is None or is_better(valid_loss, prev_best):", "1 if should_stop_early.num_runs >= args.patience: logger.info( \"early stop since valid", "\"\"\"Evaluate the model on the validation set(s) and return the", "saves or (end_of_epoch and epoch_itr.epoch % args.validate_interval == 0) or", "args.model_parallel_size == 1: trainer = Trainer(args, task, model, criterion, quantizer)", "is not None: extra_state.update({\"best\": self.best}) if args.keep_best_checkpoints > 0 and", "% args.save_interval == 0 ) checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)] = save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch,", "args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split, combine=False, epoch=1) # Build model and criterion model", "# skip check if no validation was done in the", "--max-tokens or --batch-size\" metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) #", "(not end_of_epoch and do_save) # validate during mid-epoch saves or", "(60 * 60) > args.stop_time_hours ) ) # Save checkpoint", "end-of-epoch stats logger.info(\"end of epoch {} (average epoch stats below)\".format(epoch_itr.epoch))", "size either with --max-tokens or --batch-size\" metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if", "if self.best is None else self.best if val_loss is not", "if len(self.keep_best) > args.keep_best_checkpoints: for _, x in self.keep_best[args.keep_best_checkpoints:]: x", "None) if prev_best is None or is_better(valid_loss, prev_best): should_stop_early.best =", "set fixed seed for every validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses =", "import math import os import sys import numpy as np", "checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk): os.remove(old_chk) if args.keep_last_epochs > 0: # remove", "= meters.StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch_itr.next_epoch_idx <=", "available and restore the # corresponding train iterator extra_state, epoch_itr", "/ (60 * 60) > args.stop_time_hours ) ) # Save", "itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx > args.curriculum), ) update_freq =", "enumerate(progress): with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function( \"train_step-%d\" % i ): log_output =", "suffix = getattr(args, \"checkpoint_suffix\", \"\") checkpoint_conds = collections.OrderedDict() save_epoch_checkpoint =", "valid_loss): # skip check if no validation was done in", "\"saved checkpoint {} (epoch {} @ {} updates, score {})", "or ( args.save_interval_updates > 0 and num_updates > 0 and", "args.validate_after_updates ) ) do_validate = ( (not end_of_epoch and do_save)", "valid_losses, should_stop def validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver):", ") if not end_of_epoch and args.keep_interval_updates > 0: # remove", "mid-epoch saves or (end_of_epoch and epoch_itr.epoch % args.validate_interval == 0)", "# only use first validation loss to update the learning", "epoch_itr, valid_subsets, end_of_epoch, saver): num_updates = trainer.get_num_updates() max_update = args.max_update", "if args.fixed_validation_seed is not None: # set fixed seed for", "else a < b prev_best = getattr(should_stop_early, \"best\", None) if", "was done in the current epoch if valid_loss is None:", "val_loss))): ckpt_name = \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix, val_loss) if save_epoch_checkpoint \\ else", "metrics.aggregate(new_root=True) as agg: for sample in progress: trainer.valid_step(sample) # log", "runs\".format( args.patience ) ) return True else: return False @metrics.aggregate(\"train\")", "# Copyright (c) Facebook, Inc. and its affiliates. # #", "epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch() updates = trainer.get_num_updates() suffix = getattr(args,", "Print args logger.info(args) # Setup task, e.g., translation, language modeling,", "datefmt=\"%Y-%m-%d %H:%M:%S\", level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(), stream=sys.stdout, ) logger = logging.getLogger(\"fairseq_cli.train\") class", "val_loss is not None and ( self.best is None or", "= epoch_itr.end_of_epoch() updates = trainer.get_num_updates() suffix = getattr(args, \"checkpoint_suffix\", \"\")", "): log_output = trainer.train_step(samples) if log_output is not None: #", "as agg: for sample in progress: trainer.valid_step(sample) # log validation", "model on one or across multiple GPUs. \"\"\" import collections", "> 0 and num_updates % args.validate_interval_updates == 0 ) )", "for subset in subsets: logger.info('begin validation on \"{}\" subset'.format(subset)) #", ">= max_update or ( args.save_interval_updates > 0 and num_updates >", "import meters from fairseq.checkpoint_utils import checkpoint_paths from fairseq.data import iterators", "False num_updates = trainer.get_num_updates() for i, samples in enumerate(progress): with", "{} (epoch {} @ {} updates, score {}) (writing took", "iterators.GroupedIterator(itr, update_freq) if getattr(args, \"tpu\", False): itr = utils.tpu_data_loader(itr) progress", "args.max_tokens, args.batch_size ) ) # Load the latest checkpoint if", "every validation utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses = [] for subset in", "trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr = trainer.get_train_iterator( epoch_itr.next_epoch_idx, # sharded data: get", "import logging import math import os import sys import numpy", "Train until the learning rate gets too small max_epoch =", "aggregator so validation metrics # don't pollute other aggregators (e.g.,", "the root directory of this source tree. \"\"\" Train a", "# remove old epoch checkpoints; checkpoints are sorted in descending", "utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, prefix=f\"valid on", "seconds)\".format( checkpoints[0], epoch, updates, val_loss, write_timer.sum ) ) if not", "\"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates, suffix, val_loss) checkpoint_conds[ckpt_name] = True self.keep_best.append((val_loss, ckpt_name)) self.keep_best", "args.patience <= 0: return False def is_better(a, b): return a", "len(self.keep_best) > args.keep_best_checkpoints: for _, x in self.keep_best[args.keep_best_checkpoints:]: x =", "utils.set_torch_seed(args.fixed_validation_seed) trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses = [] for subset in subsets: logger.info('begin", "write_timer = meters.StopwatchMeter() write_timer.start() epoch = epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch()", "> args.curriculum), ) update_freq = ( args.update_freq[epoch_itr.epoch - 1] if", "model, criterion, quantizer) else: trainer = MegatronTrainer(args, task, model, criterion)", "math import os import sys import numpy as np import", "trainer, agg.get_smoothed_values(), saver) progress.print(stats, tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses def", "progress.log(stats, tag=\"train_inner\", step=num_updates) # reset mid-epoch stats after each log", "b): return a > b if args.maximize_best_checkpoint_metric else a <", "args.max_tokens is not None or args.batch_size is not None ),", "{}\".format( args.max_tokens, args.batch_size ) ) # Load the latest checkpoint", "train(args, trainer, task, epoch_itr, saver) if should_stop: break # only", "valid_losses, should_stop = train(args, trainer, task, epoch_itr, saver) if should_stop:", "LICENSE file in the root directory of this source tree.", "else None ), default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"), )", "not None: best_function = max if args.maximize_best_checkpoint_metric else min self.best", "meters.StopwatchMeter() write_timer.start() epoch = epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch() updates =", "task.load_dataset(valid_sub_split, combine=False, epoch=1) # Build model and criterion model =", "= trainer.get_lr() train_meter = meters.StopwatchMeter() train_meter.start() while lr > args.min_lr", "itr.has_next() valid_losses, should_stop = validate_and_save( args, trainer, task, epoch_itr, valid_subsets,", "args.keep_best_checkpoints or ( val_loss is not None and not is_better(self.keep_best[-1][0],", ">= args.validate_after_updates ) ) do_validate = ( (not end_of_epoch and", "self.best if val_loss is not None: best_function = max if", "import Trainer logging.basicConfig( format=\"%(asctime)s | %(levelname)s | %(name)s | %(message)s\",", "will still be preserved metrics.reset_meters(\"train_inner\") end_of_epoch = not itr.has_next() valid_losses,", "set(s) and return the losses.\"\"\" if args.fixed_validation_seed is not None:", "fairseq import ( checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils, )", "None ), \"Must specify batch size either with --max-tokens or", "latest checkpoint if one is available and restore the #", "checkpoint_paths( args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" ) for old_chk in checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk):", "from fairseq.trainer import Trainer logging.basicConfig( format=\"%(asctime)s | %(levelname)s | %(name)s", "collections import logging import math import os import sys import", "valid_subsets, end_of_epoch, saver ) if should_stop: break # log end-of-epoch", "remove old epoch checkpoints; checkpoints are sorted in descending order", "to create the required dir if args.distributed_rank == 0: os.makedirs(args.save_dir,", "# Build trainer if args.model_parallel_size == 1: trainer = Trainer(args,", "a > b if args.maximize_best_checkpoint_metric else a < b prev_best", "on the latest checkpoint) for valid_sub_split in args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split, combine=False,", "quantizer) else: trainer = MegatronTrainer(args, task, model, criterion) logger.info( \"training", "is not None: # not OOM, overflow, ... # log", "@metrics.aggregate(\"train\") def train(args, trainer, task, epoch_itr, saver): \"\"\"Train the model", "python3 -u # Copyright (c) Facebook, Inc. and its affiliates.", "None or args.batch_size is not None ), \"Must specify batch", "first validation loss to update the learning rate lr =", "log end-of-epoch stats logger.info(\"end of epoch {} (average epoch stats", "\"train_step-%d\" % i ): log_output = trainer.train_step(samples) if log_output is", "key = \"best_{0}\".format(args.best_checkpoint_metric) best_function = max if args.maximize_best_checkpoint_metric else min", "saver = Saver() utils.import_user_module(args) assert ( args.max_tokens is not None", "round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0) return stats def validate(args, trainer, task, epoch_itr,", "val_loss) if save_epoch_checkpoint \\ else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates, suffix, val_loss) checkpoint_conds[ckpt_name]", "args.save_interval_updates == 0 ) checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] = val_loss is not None", "# log validation stats stats = get_valid_stats(args, trainer, agg.get_smoothed_values(), saver)", "or across multiple GPUs. \"\"\" import collections import logging import", "num_updates = trainer.get_num_updates() for i, samples in enumerate(progress): with metrics.aggregate(\"train_inner\"),", "improved for last {} runs\".format( args.patience ) ) return True", "return True else: return False @metrics.aggregate(\"train\") def train(args, trainer, task,", "latest checkpoint) for valid_sub_split in args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split, combine=False, epoch=1) #", "train_meter.start() while lr > args.min_lr and epoch_itr.next_epoch_idx <= max_epoch: #", "hasattr(saver.save_checkpoint, \"best\"): key = \"best_{0}\".format(args.best_checkpoint_metric) best_function = max if args.maximize_best_checkpoint_metric", "Save checkpoint if do_save or should_stop: logger.info(\"begin save checkpoint\") saver.save_checkpoint(args,", "order checkpoints = checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\") for old_chk in checkpoints[args.keep_last_epochs:]: if", "utils.set_torch_seed(args.seed) if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print args logger.info(args) # Setup", "[None] if do_validate: valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets,", "updates, suffix, val_loss) checkpoint_conds[ckpt_name] = True self.keep_best.append((val_loss, ckpt_name)) self.keep_best =", "False if args.patience <= 0: return False def is_better(a, b):", "max_epoch = args.max_epoch or math.inf lr = trainer.get_lr() train_meter =", "( self.best is None or is_better(val_loss, self.best) ) checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix)", "not None and not is_better(self.keep_best[-1][0], val_loss))): ckpt_name = \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch, suffix,", "saver) if should_stop: break # only use first validation loss", "def get_valid_stats(args, trainer, stats, saver): stats[\"num_updates\"] = trainer.get_num_updates() if hasattr(saver.save_checkpoint,", "if args.maximize_best_checkpoint_metric else a < b prev_best = getattr(should_stop_early, \"best\",", "0 ) checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] = val_loss is not None and (", "progress: trainer.valid_step(sample) # log validation stats stats = get_valid_stats(args, trainer,", "mid-epoch stats num_updates = trainer.get_num_updates() if num_updates % args.log_interval ==", "epoch_itr, valid_losses[0]) return valid_losses, should_stop def get_training_stats(stats): stats[\"wall\"] = round(metrics.get_meter(\"default\",", "one is available and restore the # corresponding train iterator", "sorted(self.keep_best) checkpoints = [ os.path.join(args.save_dir, fn) for fn, cond in", "if hasattr(saver.save_checkpoint, \"best\"): key = \"best_{0}\".format(args.best_checkpoint_metric) best_function = max if", "checkpoint {} (epoch {} @ {} updates, score {}) (writing", "return False @metrics.aggregate(\"train\") def train(args, trainer, task, epoch_itr, saver): \"\"\"Train", "pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" ) for old_chk in checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk): os.remove(old_chk) if", "tasks.setup_task(args) # Load valid dataset (we load training data below,", "task.build_criterion(args) logger.info(model) logger.info(\"task: {} ({})\".format(args.task, task.__class__.__name__)) logger.info(\"model: {} ({})\".format(args.arch, model.__class__.__name__))", "= task.build_model(args) criterion = task.build_criterion(args) logger.info(model) logger.info(\"task: {} ({})\".format(args.task, task.__class__.__name__))", "(num. trained: {})\".format( sum(p.numel() for p in model.parameters()), sum(p.numel() for", "0 and updates % args.save_interval_updates == 0 ) checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] =", "trainer.get_num_updates() for i, samples in enumerate(progress): with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function( \"train_step-%d\"", "checkpoint_utils.load_checkpoint( args, trainer, # don't cache epoch iterators for sharded", "0: # remove old checkpoints; checkpoints are sorted in descending", "({})\".format(args.criterion, criterion.__class__.__name__) ) logger.info( \"num. model params: {} (num. trained:", "saver): \"\"\"Evaluate the model on the validation set(s) and return", "else: return False @metrics.aggregate(\"train\") def train(args, trainer, task, epoch_itr, saver):", "is not None and ( self.best is None or is_better(val_loss,", "sorted in descending order checkpoints = checkpoint_paths( args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" )", "0) return stats def validate(args, trainer, task, epoch_itr, subsets, saver):", "= MegatronTrainer(args, task, model, criterion) logger.info( \"training on {} devices", "options, quantization_utils, tasks, utils, ) from fairseq import meters from", "def should_stop_early(args, valid_loss): # skip check if no validation was", "saver) progress.print(stats, tag=subset, step=trainer.get_num_updates()) valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses def get_valid_stats(args, trainer,", "stats[args.best_checkpoint_metric] ) return stats def cli_main(modify_parser=None): parser = options.get_training_parser() args", "{} @ {} updates, score {}) (writing took {} seconds)\".format(", "= options.parse_args_and_arch(parser, modify_parser=modify_parser) if args.profile: with torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args,", "trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args, \"tpu\", False): itr = utils.tpu_data_loader(itr) progress =", "None self.keep_best = [] def save_checkpoint(self, args, trainer, epoch_itr, val_loss):", "for _, x in self.keep_best[args.keep_best_checkpoints:]: x = os.path.join(args.save_dir, x) if", "epoch_itr, saver): \"\"\"Train the model for one epoch and return", "None or is_better(val_loss, self.best) ) checkpoint_conds[ \"checkpoint_last{}.pt\".format(suffix) ] = not", "self.best = best_function(val_loss, prev_best) if args.no_save: return trainer.consolidate_optimizer() if not", "not args.no_last_checkpoints extra_state = {\"train_iterator\": epoch_itr.state_dict(), \"val_loss\": val_loss} if self.best", "last {} runs\".format( args.patience ) ) return True else: return", "return trainer.consolidate_optimizer() if not trainer.is_data_parallel_master: return def is_better(a, b): return", "> args.min_lr and epoch_itr.next_epoch_idx <= max_epoch: # train for one", "logger.info( \"num. model params: {} (num. trained: {})\".format( sum(p.numel() for", "for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) # Train until the learning", "\"\") checkpoint_conds = collections.OrderedDict() save_epoch_checkpoint = ( end_of_epoch and not", "else a <= b write_timer = meters.StopwatchMeter() write_timer.start() epoch =", "torch.autograd.profiler.record_function( \"train_step-%d\" % i ): log_output = trainer.train_step(samples) if log_output", "0 and num_updates > 0 and num_updates % args.validate_interval_updates ==", "and not args.no_epoch_checkpoints and epoch % args.save_interval == 0 )", "task, epoch_itr, valid_subsets, end_of_epoch, saver ) if should_stop: break #", "num_updates % args.validate_interval_updates == 0 ) ) and not args.disable_validation", "trainer = MegatronTrainer(args, task, model, criterion) logger.info( \"training on {}", "else self.best if val_loss is not None: best_function = max", "write_timer.stop() logger.info( \"saved checkpoint {} (epoch {} @ {} updates,", "trainer.train_step(samples) if log_output is not None: # not OOM, overflow,", "\"checkpoint_suffix\", \"\") checkpoint_conds = collections.OrderedDict() save_epoch_checkpoint = ( end_of_epoch and", "options.parse_args_and_arch(parser, modify_parser=modify_parser) if args.profile: with torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main)", "assert ( args.max_tokens is not None or args.batch_size is not", "None ), default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"), ) #", "is not None and not is_better(self.keep_best[-1][0], val_loss))): ckpt_name = \"checkpoint{}{}.best_{:.4f}.pt\".format(epoch,", "checkpoint_paths from fairseq.data import iterators from fairseq.file_io import PathManager from", "should_stop_early(args, valid_losses[0]) or num_updates >= max_update or ( args.stop_time_hours >", "descending order checkpoints = checkpoint_paths( args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" ) for old_chk", "# Build model and criterion model = task.build_model(args) criterion =", "should_stop = validate_and_save( args, trainer, task, epoch_itr, valid_subsets, end_of_epoch, saver", "logger.info( \"training on {} devices (GPUs/TPUs)\".format(args.distributed_world_size) ) logger.info( \"max tokens", "if args.profile: with torch.cuda.profiler.profile(): with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main) else: distributed_utils.call_main(args,", "getattr(args, \"tpu\", False): itr = utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr,", "main(args): saver = Saver() utils.import_user_module(args) assert ( args.max_tokens is not", "extra_state, epoch_itr = checkpoint_utils.load_checkpoint( args, trainer, # don't cache epoch", "model and criterion model = task.build_model(args) criterion = task.build_criterion(args) logger.info(model)", "one worker should attempt to create the required dir if", ") do_validate = ( (not end_of_epoch and do_save) # validate", ") ) # Load the latest checkpoint if one is", "meters metrics.reset_meters(\"train\") return valid_losses, should_stop def validate_and_save(args, trainer, task, epoch_itr,", "train_meter.stop() logger.info(\"done training in {:.1f} seconds\".format(train_meter.sum)) def should_stop_early(args, valid_loss): #", "if getattr(args, \"tpu\", False): itr = utils.tpu_data_loader(itr) progress = progress_bar.progress_bar(", "args, trainer, # don't cache epoch iterators for sharded datasets", "or math.inf lr = trainer.get_lr() train_meter = meters.StopwatchMeter() train_meter.start() while", "\"training on {} devices (GPUs/TPUs)\".format(args.distributed_world_size) ) logger.info( \"max tokens per", "not args.disable_validation # Validate valid_losses = [None] if do_validate: valid_losses", "import ( checkpoint_utils, distributed_utils, options, quantization_utils, tasks, utils, ) from", "licensed under the MIT license found in the # LICENSE", "iterator itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args, \"tpu\", False): itr =", "itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None", "None and ( self.best is None or is_better(val_loss, self.best) )", "args.validate_interval == 0) or num_updates >= max_update or ( args.validate_interval_updates", "MIT license found in the # LICENSE file in the", "each log interval # the end-of-epoch stats will still be", ") and not args.disable_validation # Validate valid_losses = [None] if", "max_update = args.max_update or math.inf do_save = ( (end_of_epoch and", "{} runs\".format( args.patience ) ) return True else: return False", "num_updates % args.log_interval == 0: stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats, tag=\"train_inner\",", "in subsets: logger.info('begin validation on \"{}\" subset'.format(subset)) # Initialize data", "updates, val_loss, write_timer.sum ) ) if not end_of_epoch and args.keep_interval_updates", "stats num_updates = trainer.get_num_updates() if num_updates % args.log_interval == 0:", "checkpoint) for valid_sub_split in args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split, combine=False, epoch=1) # Build", "\"num. model params: {} (num. trained: {})\".format( sum(p.numel() for p", "0 ) ) and not args.disable_validation # Validate valid_losses =", "= collections.OrderedDict() save_epoch_checkpoint = ( end_of_epoch and not args.no_epoch_checkpoints and", "\"\"\"Train the model for one epoch and return validation losses.\"\"\"", "epoch=epoch_itr.epoch, prefix=f\"valid on '{subset}' subset\", tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else", "for p in model.parameters()), sum(p.numel() for p in model.parameters() if", "on the validation set(s) and return the losses.\"\"\" if args.fixed_validation_seed", "saver.save_checkpoint.best, stats[args.best_checkpoint_metric] ) return stats def cli_main(modify_parser=None): parser = options.get_training_parser()", "from fairseq.data import iterators from fairseq.file_io import PathManager from fairseq.logging", "args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" ) for old_chk in checkpoints[args.keep_interval_updates:]: if os.path.lexists(old_chk): os.remove(old_chk)", ") # Load the latest checkpoint if one is available", "args.save_interval == 0 ) checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)] = save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates,", "logger = logging.getLogger(\"fairseq_cli.train\") class Saver: def __init__(self): self.best = None", ") ) if not end_of_epoch and args.keep_interval_updates > 0: #", "self.keep_best[:args.keep_best_checkpoints] def main(args): saver = Saver() utils.import_user_module(args) assert ( args.max_tokens", "pollute other aggregators (e.g., train meters) with metrics.aggregate(new_root=True) as agg:", "e.g., translation, language modeling, etc. task = tasks.setup_task(args) # Load", "{}) (writing took {} seconds)\".format( checkpoints[0], epoch, updates, val_loss, write_timer.sum", "args.keep_interval_updates > 0: # remove old checkpoints; checkpoints are sorted", "np import torch from fairseq import ( checkpoint_utils, distributed_utils, options,", "for next epoch load_dataset=task.has_sharded_data(\"train\"), # don't cache epoch iterators for", "with torch.autograd.profiler.emit_nvtx(): distributed_utils.call_main(args, main) else: distributed_utils.call_main(args, main) if __name__ ==", "train(args, trainer, task, epoch_itr, saver): \"\"\"Train the model for one", "tokens per GPU = {} and max sentences per GPU", "and num_updates % args.validate_interval_updates == 0 ) ) and not", "len(args.update_freq) else args.update_freq[-1] ) itr = iterators.GroupedIterator(itr, update_freq) if getattr(args,", "- 1] if epoch_itr.epoch <= len(args.update_freq) else args.update_freq[-1] ) itr", "max_update=args.max_update, ) else: quantizer = None # Build trainer if", "{} seconds)\".format( checkpoints[0], epoch, updates, val_loss, write_timer.sum ) ) if", "\"checkpoint_last{}.pt\".format(suffix) ] = not args.no_last_checkpoints extra_state = {\"train_iterator\": epoch_itr.state_dict(), \"val_loss\":", "this source tree. \"\"\" Train a new model on one", "fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx > args.curriculum), ) update_freq = ( args.update_freq[epoch_itr.epoch -", "learning rate lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr = trainer.get_train_iterator( epoch_itr.next_epoch_idx,", "utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir", "checkpoints[0], epoch, updates, val_loss, write_timer.sum ) ) if not end_of_epoch", "still be preserved metrics.reset_meters(\"train_inner\") end_of_epoch = not itr.has_next() valid_losses, should_stop", "= True self.keep_best.append((val_loss, ckpt_name)) self.keep_best = sorted(self.keep_best) checkpoints = [", "num_updates >= args.validate_after_updates ) ) do_validate = ( (not end_of_epoch", "criterion) logger.info( \"training on {} devices (GPUs/TPUs)\".format(args.distributed_world_size) ) logger.info( \"max", "1: trainer = Trainer(args, task, model, criterion, quantizer) else: trainer", "= \"best_{0}\".format(args.best_checkpoint_metric) best_function = max if args.maximize_best_checkpoint_metric else min stats[key]", "for last {} runs\".format( args.patience ) ) return True else:", "def save_checkpoint(self, args, trainer, epoch_itr, val_loss): # only one worker", "= progress_bar.progress_bar( itr, log_format=args.log_format, log_interval=args.log_interval, epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args)", "the # LICENSE file in the root directory of this", "= None self.keep_best = [] def save_checkpoint(self, args, trainer, epoch_itr,", "if args.quantization_config_path is not None: quantizer = quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch,", "import checkpoint_paths from fairseq.data import iterators from fairseq.file_io import PathManager", "checkpoint_conds[\"checkpoint{}{}.pt\".format(epoch, suffix)] = save_epoch_checkpoint checkpoint_conds[\"checkpoint_{}_{}{}.pt\".format(epoch, updates, suffix)] = ( not", "the learning rate lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) epoch_itr = trainer.get_train_iterator(", "extra_state) for cp in checkpoints[1:]: PathManager.copy(checkpoints[0], cp, overwrite=True) write_timer.stop() logger.info(", "val_loss if self.best is None else self.best if val_loss is", "valid_sub_split in args.valid_subset.split(\",\"): task.load_dataset(valid_sub_split, combine=False, epoch=1) # Build model and", ") update_freq = ( args.update_freq[epoch_itr.epoch - 1] if epoch_itr.epoch <=", "False def is_better(a, b): return a > b if args.maximize_best_checkpoint_metric", "meters) with metrics.aggregate(new_root=True) as agg: for sample in progress: trainer.valid_step(sample)", "val_loss is not None: best_function = max if args.maximize_best_checkpoint_metric else", "checkpoint if one is available and restore the # corresponding", "= trainer.get_train_iterator( epoch_itr.next_epoch_idx, # sharded data: get train iterator for", "( args.max_tokens is not None or args.batch_size is not None", "hasn't improved for last {} runs\".format( args.patience ) ) return", "# Load valid dataset (we load training data below, based", "import metrics, progress_bar from fairseq.model_parallel.megatron_trainer import MegatronTrainer from fairseq.trainer import", "# reset epoch-level meters metrics.reset_meters(\"train\") return valid_losses, should_stop def validate_and_save(args,", "on \"{}\" subset'.format(subset)) # Initialize data iterator itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False)", "args.validate_interval_updates > 0 and num_updates > 0 and num_updates %", ") else: quantizer = None # Build trainer if args.model_parallel_size", "> 0: trainer.save_checkpoint(checkpoints[0], extra_state) for cp in checkpoints[1:]: PathManager.copy(checkpoints[0], cp,", "= checkpoint_utils.load_checkpoint( args, trainer, # don't cache epoch iterators for", "end_of_epoch and args.keep_interval_updates > 0: # remove old checkpoints; checkpoints", "epoch, updates, val_loss, write_timer.sum ) ) if not end_of_epoch and", "is available and restore the # corresponding train iterator extra_state,", "import collections import logging import math import os import sys", "load_dataset=task.has_sharded_data(\"train\"), # don't cache epoch iterators for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"),", "saver): num_updates = trainer.get_num_updates() max_update = args.max_update or math.inf do_save", "descending order checkpoints = checkpoint_paths(args.save_dir, pattern=r\"checkpoint(\\d+)\\.pt\") for old_chk in checkpoints[args.keep_last_epochs:]:", "model.parameters()), sum(p.numel() for p in model.parameters() if p.requires_grad), ) )", "{} ({})\".format(args.criterion, criterion.__class__.__name__) ) logger.info( \"num. model params: {} (num.", "return False else: should_stop_early.num_runs += 1 if should_stop_early.num_runs >= args.patience:", "not args.no_progress_bar else \"simple\"), ) # create a new root", "do_validate: valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets, saver) #", "0: os.makedirs(args.save_dir, exist_ok=True) prev_best = val_loss if self.best is None", "old checkpoints; checkpoints are sorted in descending order checkpoints =", "\"tpu\", False): itr = utils.tpu_data_loader(itr) progress = progress_bar.progress_bar( itr, log_format=args.log_format,", "i, samples in enumerate(progress): with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function( \"train_step-%d\" % i", "utils.import_user_module(args) assert ( args.max_tokens is not None or args.batch_size is", "== 0 and num_updates >= args.validate_after_updates ) ) do_validate =", "for sharded datasets disable_iterator_cache=task.has_sharded_data(\"train\"), ) train_meter.stop() logger.info(\"done training in {:.1f}", "None or is_better(valid_loss, prev_best): should_stop_early.best = valid_loss should_stop_early.num_runs = 0", "stats stats = get_valid_stats(args, trainer, agg.get_smoothed_values(), saver) progress.print(stats, tag=subset, step=trainer.get_num_updates())", "{} devices (GPUs/TPUs)\".format(args.distributed_world_size) ) logger.info( \"max tokens per GPU =", "trainer.begin_valid_epoch(epoch_itr.epoch) valid_losses = [] for subset in subsets: logger.info('begin validation", "args.max_update or math.inf do_save = ( (end_of_epoch and epoch_itr.epoch %", "fairseq.data import iterators from fairseq.file_io import PathManager from fairseq.logging import", "is not None ), \"Must specify batch size either with", "> args.stop_time_hours ) ) # Save checkpoint if do_save or", "saver): \"\"\"Train the model for one epoch and return validation", "and trainer.cumulative_training_time() / (60 * 60) > args.stop_time_hours ) )", "os.remove(old_chk) if args.keep_last_epochs > 0: # remove old epoch checkpoints;", "\"max tokens per GPU = {} and max sentences per", "= validate(args, trainer, task, epoch_itr, valid_subsets, saver) # Stopping conditions", ") itr = iterators.GroupedIterator(itr, update_freq) if getattr(args, \"tpu\", False): itr", "in checkpoint_conds.items() if cond ] if len(checkpoints) > 0: trainer.save_checkpoint(checkpoints[0],", "valid_losses.append(stats[args.best_checkpoint_metric]) return valid_losses def get_valid_stats(args, trainer, stats, saver): stats[\"num_updates\"] =", "best_function(val_loss, prev_best) if args.no_save: return trainer.consolidate_optimizer() if not trainer.is_data_parallel_master: return", "os.path.lexists(old_chk): os.remove(old_chk) if args.keep_last_epochs > 0: # remove old epoch", "{} updates, score {}) (writing took {} seconds)\".format( checkpoints[0], epoch,", "sample in progress: trainer.valid_step(sample) # log validation stats stats =", "< args.keep_best_checkpoints or ( val_loss is not None and not", "cond in checkpoint_conds.items() if cond ] if len(checkpoints) > 0:", "validation set(s) and return the losses.\"\"\" if args.fixed_validation_seed is not", "epoch=epoch_itr.epoch, tensorboard_logdir=( args.tensorboard_logdir if distributed_utils.is_master(args) else None ), default_log_format=(\"tqdm\" if", "training data below, based on the latest checkpoint) for valid_sub_split", "stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\")) progress.log(stats, tag=\"train_inner\", step=num_updates) # reset mid-epoch stats", "= get_training_stats(metrics.get_smoothed_values(\"train\")) progress.print(stats, tag=\"train\", step=num_updates) # reset epoch-level meters metrics.reset_meters(\"train\")", "if os.path.lexists(old_chk): os.remove(old_chk) if len(self.keep_best) > args.keep_best_checkpoints: for _, x", "pattern=r\"checkpoint(\\d+)\\.pt\") for old_chk in checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk): os.remove(old_chk) if len(self.keep_best)", "checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print args logger.info(args) # Setup task, e.g., translation,", "= not args.no_last_checkpoints extra_state = {\"train_iterator\": epoch_itr.state_dict(), \"val_loss\": val_loss} if", "learning rate gets too small max_epoch = args.max_epoch or math.inf", "disable_iterator_cache=task.has_sharded_data(\"train\"), ) train_meter.stop() logger.info(\"done training in {:.1f} seconds\".format(train_meter.sum)) def should_stop_early(args,", "self.keep_best = self.keep_best[:args.keep_best_checkpoints] def main(args): saver = Saver() utils.import_user_module(args) assert", "if cond ] if len(checkpoints) > 0: trainer.save_checkpoint(checkpoints[0], extra_state) for", "else \"checkpoint_{}_{}{}.best_{:.4f}.pt\".format(epoch, updates, suffix, val_loss) checkpoint_conds[ckpt_name] = True self.keep_best.append((val_loss, ckpt_name))", "args.keep_best_checkpoints: for _, x in self.keep_best[args.keep_best_checkpoints:]: x = os.path.join(args.save_dir, x)", "epoch=1) # Build model and criterion model = task.build_model(args) criterion", "= val_loss if self.best is None else self.best if val_loss", "Build trainer if args.model_parallel_size == 1: trainer = Trainer(args, task,", "checkpoint_conds[ckpt_name] = True self.keep_best.append((val_loss, ckpt_name)) self.keep_best = sorted(self.keep_best) checkpoints =", "and updates % args.save_interval_updates == 0 ) checkpoint_conds[\"checkpoint_best{}.pt\".format(suffix)] = val_loss", "logger.info(\"task: {} ({})\".format(args.task, task.__class__.__name__)) logger.info(\"model: {} ({})\".format(args.arch, model.__class__.__name__)) logger.info( \"criterion:", "b prev_best = getattr(should_stop_early, \"best\", None) if prev_best is None", "(we load training data below, based on the latest checkpoint)", "= logging.getLogger(\"fairseq_cli.train\") class Saver: def __init__(self): self.best = None self.keep_best", "old_chk in checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk): os.remove(old_chk) if len(self.keep_best) > args.keep_best_checkpoints:", "= False num_updates = trainer.get_num_updates() for i, samples in enumerate(progress):", "Initialize data iterator itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False) if getattr(args, \"tpu\", False):", "across multiple GPUs. \"\"\" import collections import logging import math", "the required dir if args.distributed_rank == 0: os.makedirs(args.save_dir, exist_ok=True) prev_best", "args.patience: logger.info( \"early stop since valid performance hasn't improved for", "in the current epoch if valid_loss is None: return False", "( (not end_of_epoch and do_save) # validate during mid-epoch saves", ") # create a new root metrics aggregator so validation", "not None: quantizer = quantization_utils.Quantizer( config_path=args.quantization_config_path, max_epoch=args.max_epoch, max_update=args.max_update, ) else:", "if do_validate: valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets, saver)", "( end_of_epoch and not args.no_epoch_checkpoints and epoch % args.save_interval ==", "= epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.next_epoch_idx > args.curriculum), ) update_freq = (", "# create a new root metrics aggregator so validation metrics", "reset mid-epoch stats after each log interval # the end-of-epoch", "= not itr.has_next() valid_losses, should_stop = validate_and_save( args, trainer, task,", "if not args.no_progress_bar else \"simple\"), ) trainer.begin_epoch(epoch_itr.epoch) valid_losses = [None]", "trainer.get_num_updates() suffix = getattr(args, \"checkpoint_suffix\", \"\") checkpoint_conds = collections.OrderedDict() save_epoch_checkpoint", "math.inf lr = trainer.get_lr() train_meter = meters.StopwatchMeter() train_meter.start() while lr", "if args.distributed_rank == 0: os.makedirs(args.save_dir, exist_ok=True) prev_best = val_loss if", "checkpoint_conds = collections.OrderedDict() save_epoch_checkpoint = ( end_of_epoch and not args.no_epoch_checkpoints", "epoch_itr, val_loss): # only one worker should attempt to create", "> 0: # remove old checkpoints; checkpoints are sorted in", "score {}) (writing took {} seconds)\".format( checkpoints[0], epoch, updates, val_loss,", "= Saver() utils.import_user_module(args) assert ( args.max_tokens is not None or", "checkpoints = checkpoint_paths( args.save_dir, pattern=r\"checkpoint_\\d+_(\\d+)\\.pt\" ) for old_chk in checkpoints[args.keep_interval_updates:]:", "np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_utils.is_master(args): checkpoint_utils.verify_checkpoint_directory(args.save_dir) # Print args logger.info(args) #", "if no validation was done in the current epoch if", "return False def is_better(a, b): return a > b if", "% args.validate_interval == 0) or num_updates >= max_update or (", "), default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"), ) trainer.begin_epoch(epoch_itr.epoch) valid_losses", "checkpoints[args.keep_last_epochs:]: if os.path.lexists(old_chk): os.remove(old_chk) if len(self.keep_best) > args.keep_best_checkpoints: for _,", "exist_ok=True) prev_best = val_loss if self.best is None else self.best", "stats[key] = best_function( saver.save_checkpoint.best, stats[args.best_checkpoint_metric] ) return stats def cli_main(modify_parser=None):", "logger.info(model) logger.info(\"task: {} ({})\".format(args.task, task.__class__.__name__)) logger.info(\"model: {} ({})\".format(args.arch, model.__class__.__name__)) logger.info(", "subsets, saver): \"\"\"Evaluate the model on the validation set(s) and" ]
[ "at every point in that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S,", ", dot(V,grad(S))) def shr(V): \"\"\" Shear Deformation <div class=jython> SHR", ") = average of all non-missing grid point values in", "<div class=jython> VLDF(V) = [(u(level1) - u(level2))/2, (v(level1) - v(level2))/2]", "the names are case sensitive and some are named slightly", "u (GEO(S)) (level1) - u (GEO(S)) (level2), v (GEO(S)) (level1)", "S * DIV ( V ) + DOT ( V,", "the wind shear between discrete layers <div class=jython> EI =", "(S2) - DDY (S1) * DDX (S2) </div> \"\"\" return", "<div class=jython> ATN2 (S1, S2) = ATAN ( S1 /", "quo(dv,dz) # Vector output def age(obs,geo): \"\"\" Ageostrophic wind <div", "def inad(V1,V2): \"\"\" Inertial advective wind <div class=jython> INAD (", "vecr(qvecudp,qvecvdp) def rectv(S, D=2): \"\"\" <div class=jython> Apply a rectangular", "class=jython> FRNT ( THTA, V ) = 1/2 * MAG", "S2 ) / 2 </div> \"\"\" return add(S1,S2)/2 def avor(V):", "\"temperature\", \"celsius\") HT = sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718 HU = (ddx(vwind)", "\"\"\" <div class=jython> Apply a rectangular aperature smoothing to the", "class=jython> CORL = TWO_OMEGA*sin(latr) </div> \"\"\" return DerivedGridFactory.createCoriolisGrid(S) def cress(S,", "grid point values in the subset area </div> \"\"\" return", "+ DOT ( V, GRAD ( S ) ) </div>", "Total deformation <div class=jython> DEF ( V ) = (", "unit) def ldf(S,level1,level2, unit=None): \"\"\" Layer Difference <div class=jython> LDF", "case sensitive and some are named slightly different from GEMPAK", "( V ) = DDX ( u ) - DDY", "def gwfs(S, N=6): \"\"\" <div class=jython> Horizontal smoothing using normally", "S (Y1) + S (Y2) + ... + S (KYD)", "add(S1,S2)/2 def avor(V): \"\"\" Absolute Vorticity <div class=jython> AVOR (", "+ ... + S (KXD) ) KXD = number of", "<div class=jython> CORL = TWO_OMEGA*sin(latr) </div> \"\"\" return DerivedGridFactory.createCoriolisGrid(S) def", "N * delta-x wave. Increasing N increases the smoothing. (default", "subtract the components of 2 vectors <div class=jython> VSUB (V1,", "</div> \"\"\" return vecr(ddy(ur(V)), ddy(vr(V))) def frnt(S,V): \"\"\" Frontogenesis function", "GridMath.AXIS_X) def yav(S): \"\"\" Average along a grid column <div", "\"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y) def zav(S): \"\"\" Average across", "(default D=2) </div> \"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def sm5v(V):", "(S) ) </div> \"\"\" return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def avg(S1,S2): \"\"\" Average", "( V, GRAD ( S ) ) </div> \"\"\" return", "GridMath.ddy(S); def defr(V): \"\"\" Total deformation <div class=jython> DEF (", ") = [ S1, S2 ] </div> \"\"\" return makeTrueVector(S1,S2)", "return GridUtil.smooth(S, \"CRES\", int(D)) def dvdx(V): \"\"\" Partial x derivative", "= 1/2 ATAN2 ( SHR / STR ) <br> </div>", "S (Y2) + ... + S (KYD) ) / KNT", "<br> - DDY (THTA) * SIN (PSI))/ <br> MAG (", "(V), GRAD (THTA) ) ) ] </div> \"\"\" dtdp =", "] </div> \"\"\" return mul(V1,V2) def vquo(V1,V2): \"\"\" Divide the", "</div> \"\"\" return dirr(DerivedGridFactory.createTrueFlowVector(V)) def dirr(V): \"\"\" Grid relative direction", "a level ( K / m / s ) <div", ") ) * [ ( DOT ( DVDX (V), GRAD", "<div class=jython> YAV (S) = ( S (Y1) + S", "(default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.multiply(S1,S2,WA) def quo(S1,S2,WA=0): \"\"\" Divide", "</div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def zsum(S): \"\"\" Sum across", "DVDY ( V ) = [ DDY (u), DDY (v)", "GRAD (v2) ) ] </div> \"\"\" return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def qvec(S,V):", "return DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def mixr(temp,rh): \"\"\" Mixing Ratio from Temperature, RH", "( v ) - DDY ( u ) </div> \"\"\"", "STRD (V) ** 2 + SHR (V) ** 2 )", "points <div class=jython> ZAV (S) = ( S (Z1) +", "top), \"temperature\", \"celsius\") HT = sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718 HU =", "add(noUnit(Z), add(noUnit(HU), noUnit(HT))) L = (L - 2.520)*(-0.59) P= 1.0/(1.0", "\"\"\" Relative Vorticity <div class=jython> VOR ( V ) =", "Potential Temperature from Temperature and Relative humidity (requires pressure domain)", "- u(level2), v(level1) - v(level2)] </div> \"\"\" return layerDiff(V,level1,level2, unit)", "from GEMPAK functions to avoid conflicts with Jython built-ins (e.g.", "v ) + DDY ( u ) </div> \"\"\" return", "RH (requires pressure domain) \"\"\" return DerivedGridFactory.createMixingRatio(temp,rh) def relh(temp,mixr): \"\"\"", "DerivedGridFactory.createMixingRatio(temp,rh) def relh(temp,mixr): \"\"\" Create Relative Humidity from Temperature, mixing", "u(level2), v(level1) - v(level2)] </div> \"\"\" return layerDiff(V,level1,level2, unit) def", "GridMath.FUNC_SUM, GridMath.AXIS_X) def yav(S): \"\"\" Average along a grid column", "Horizontal Advection, negative by convention <div class=jython> ADV ( S,", "jcbn(S1,S2): \"\"\" Jacobian Determinant <div class=jython> JCBN ( S1, S2", "Vorticity <div class=jython> VOR ( V ) = DDX (", "of 2 vectors <div class=jython> VMUL (V1, V2) = [", "weighting function is the product of the rectangular aperature diffraction", "def sdiv(S,V): \"\"\" Horizontal Flux Divergence <div class=jython> SDIV (", "(usually from theta and wind) \"\"\" return DerivedGridFactory.createPotentialVorticity(S,V) def rects(S,", "def sm9s(S): \"\"\" Smooth a scalar grid using a 9-point", "= (ddx(vwind) + ddy(uwind))*0.318 L = add(noUnit(Z), add(noUnit(HU), noUnit(HT))) L", "( GRAD (THTA) ) * ( DEF * COS (2", "else: return layerAverage(S,level1,level2, unit) def ldf(S,level1,level2, unit=None): \"\"\" Layer Difference", "DerivedGridFactory.GRAVITY; # Math functions def atn2(S1,S2,WA=0): \"\"\" Wrapper for atan2", "X coordinate \"\"\" return GridMath.ddx(S); def ddy(S): \"\"\" Take the", "\"\"\" Jacobian Determinant <div class=jython> JCBN ( S1, S2 )", "V<sub>n</sub>. Lowercase u and v refer to the grid relative", "DerivedGridFactory.createCoriolisGrid(S) def cress(S, D=2): \"\"\" <div class=jython> Apply a Cressman", "the doc for the Grid Diagnostics module. These functions are", "the x and y directions. D is the radius of", "radius of influence in grid increments, increasing D increases the", "( v ) </div> \"\"\" return sub(ddx(ur(V)),ddy(vr(V))) def thta(temp): \"\"\"", "(V), GRAD (S) ) ), - ( DOT ( DVDY", "+ ddy(temp)*ddy(temp))*0.718 HU = (ddx(vwind) + ddy(uwind))*0.318 L = add(noUnit(Z),", "</div> \"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def dvdx(V): \"\"\" Partial", "Z = windShear(u, v, z, top, bottom, unit)*7.268 uwind =", "grid column <div class=jython> YSUM (S) = ( S (Y1)", "* DDX (S2) </div> \"\"\" return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def latr(S): \"\"\"", "+ S (KYD) ) KYD = number of points in", "+ S (Y2) + ... + S (KYD) ) /", "S (KYD) ) KYD = number of points in row", "= u1 * v2 - u2 * v1 </div> \"\"\"", "V ) = DDX ( u ) + DDY (", "points. The weighting function is the product of the rectangular", "S ) = [ DDX ( S ), DDY (", "[ u (OBS) - u (GEO(S)), v (OBS) - v", "def gwfv(V, N=6): \"\"\" <div class=jython> Horizontal smoothing using normally", "beta = asin(a/mgradt) frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V)) return frnto def geo(z):", "constant \"\"\" return DerivedGridFactory.GRAVITY; # Math functions def atn2(S1,S2,WA=0): \"\"\"", "(S1, S2) = S1 / S2<br> WA = use WEIGHTED_AVERAGE", "smoother <div class=jython> SM9S ( S ) = .25 *", "= sqrt(DSH * DSH + DST * DST) EI =", "<div class=jython> VLDF(V) = [u(level1) - u(level2), v(level1) - v(level2)]", "GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def savs(S): \"\"\" Average over grid subset <div", "Smooth a scalar grid using a 5-point smoother (see sm5s)", "of the vertical wind shear in a layer <div class=jython>", "\"\"\" Wrapper for atan2 built-in <div class=jython> ATN2 (S1, S2)", "wind shear between discrete layers <div class=jython> LP = 7.268DUDZ", "points in column </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y) def", ") </div> \"\"\" return GridUtil.smooth(S, \"SM5S\") def sm9s(S): \"\"\" Smooth", "= [ u1-u2, v1-v2 ] </div> \"\"\" return sub(V1,V2) def", "</div> \"\"\" grads = grad(S) return div(grads) def lav(S,level1=None,level2=None, unit=None):", "of 2 vectors <div class=jython> VADD (V1, V2) = [", "components of 2 vectors <div class=jython> VMUL (V1, V2) =", ") <div class=jython> QVCL ( THTA, V ) = (", "S (KXD) ) KXD = number of points in row", "s ) <div class=jython> QVCL ( THTA, V ) =", "\"\"\" Subtract <div class=jython> SUB (S1, S2) = S1 -", "grid points. The weighting function is the product of the", "derivative of a vector <div class=jython> DVDX ( V )", "grid using a 5-point smoother <div class=jython> SM5S ( S", "<div class=jython> AVG (S1, S2) = ( S1 + S2", "</div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X) def xsum(S): \"\"\" Sum", "ddy(temp)*ddy(temp))*0.718 HU = (ddx(vwind) + ddy(uwind))*0.318 L = add(noUnit(Z), add(noUnit(HU),", "sub(obs,geo) def circv(S, D=2): \"\"\" <div class=jython> Apply a circular", "(requires pressure domain) \"\"\" return DerivedGridFactory.createRelativeHumidity(temp,mixr) def pvor(S,V): \"\"\" Potetial", "def xsum(S): \"\"\" Sum along a grid row <div class=jython>", "+ S (Y2) + ... + S (KYD) ) KYD", "class=jython> VMUL (V1, V2) = [ u1*u2, v1*v2 ] </div>", "# Scalar quantities def adv(S,V): \"\"\" Horizontal Advection, negative by", "def LPIndex(u, v, z, t, top, bottom, unit): \"\"\" calculate", "(i-1,j-1) ) </div> \"\"\" return GridUtil.smooth(S, \"SM9S\") def strd(V): \"\"\"", "sm5s(S): \"\"\" Smooth a scalar grid using a 5-point smoother", "[(u(level1) - u(level2))/2, (v(level1) - v(level2))/2] </div> \"\"\" return layerAverage(V,", "DIV ( V ) = DDX ( u ) +", "</div> \"\"\" return GridMath.add(S1,S2,WA) def mul(S1,S2,WA=0): \"\"\" Multiply <div class=jython>", "a circular aperature smoothing to the grid points. The weighting", "(S1) * DDX (S2) </div> \"\"\" return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def latr(S):", "v1/v2 ] </div> \"\"\" return quo(V1,V2) def vsub(V1,V2): \"\"\" subtract", "ddy(uwind))*0.318 L = add(noUnit(Z), add(noUnit(HU), noUnit(HT))) L = (L -", "between discrete layers <div class=jython> LP = 7.268DUDZ + 0.718DTDN", "the smoothing. (default N=6) </div> \"\"\" return gwfs(V, N) def", "getSliceAtLevel(v, top) temp = newUnit(getSliceAtLevel(t, top), \"temperature\", \"celsius\") HT =", "vmul(V1,V2): \"\"\" Multiply the components of 2 vectors <div class=jython>", "( V ) = ( STRD (V) ** 2 +", "v component \"\"\" return DerivedGridFactory.getVComponent(V) def xav(S): \"\"\" Average along", "component \"\"\" return ur(DerivedGridFactory.createTrueFlowVector(V)) def ur(V): \"\"\" Grid relative u", "makeTrueVector(S1,S2) def vecr(S1,S2): \"\"\" Make a vector from two components", "( STRD (V) ** 2 + SHR (V) ** 2", "( S ) = DIV ( GRAD (S) ) </div>", "usually THTA. </div> \"\"\" grads = grad(S) qvecu = newName(-dot(dvdx(V),grads),\"qvecu\")", "def dvdy(V): \"\"\" Partial x derivative of a vector <div", "(THTA) / DP ) ) * [ ( DOT (", "WSHR ( V ) = MAG [ VLDF (V) ]", "= [ S1, S2 ] </div> \"\"\" return makeVector(S1,S2) def", "= use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.atan2(S1,S2,WA) def", "(i+1,j) + S (i,j+1) + S (i-1,j) + S (i,j-1)", "in row XSUM for a row is stored at every", "Average across the levels of a grid at all points", "shear between discrete layers <div class=jython> EI = VWS X", "column KNT = number of non-missing points in column </div>", "return DerivedGridFactory.createGeostrophicWindVector(z) def grad(S): \"\"\" Gradient of a scalar <div", "( DVDY (V), GRAD (S) ) ) ] where S", "( V ) = [ DDY (u), DDY (v) ]", "def un(V): \"\"\" North relative u component \"\"\" return ur(DerivedGridFactory.createTrueFlowVector(V))", "( S ), DDY ( S ) ] </div> \"\"\"", "def ddx(S): \"\"\" Take the derivative with respect to the", "( S (Z1) + S (Z2) + ... + S", "\"\"\" Gradient of a scalar <div class=jython> GRAD ( S", "(THTA) * SIN (PSI))/ <br> MAG ( GRAD (THTA) )", "class=jython> VOR ( V ) = DDX ( v )", "GEO ( S ) = [ - DDY (S) *", "= 1/2 * MAG ( GRAD (THTA) ) * (", "( un(v), vn(v) ) </div> \"\"\" return dirr(DerivedGridFactory.createTrueFlowVector(V)) def dirr(V):", "+ GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP = setLevel(P ,top, unit) return LP def", "<div class=jython> DIRN ( V ) = DIRR ( un(v),", "is stored at every point in that row. </div> \"\"\"", "= DDX ( v ) - DDY ( u )", "DOT ( DVDY (V), GRAD (THTA) ) ) ] </div>", "strch = strd(V) psi = .5*atn2(shear,strch) dxt = ddx(S) dyt", "cress(S, D=2): \"\"\" <div class=jython> Apply a Cressman smoothing to", "GridMath.AXIS_Y) def zav(S): \"\"\" Average across the levels of a", "(V), GRAD (THTA) ) ), ( DOT ( DVDY (V),", "( u ) </div> \"\"\" return add(ddx(vr(V)),ddy(ur(V))) def sm5s(S): \"\"\"", "number of points in column KNT = number of non-missing", "sm9s(V) def thrm(S, level1, level2, unit=None): \"\"\" Thermal wind <div", "along a grid row <div class=jython> XAV (S) = (", "output def age(obs,geo): \"\"\" Ageostrophic wind <div class=jython> AGE (", "( V ) = [ DDX (u), DDX (v) ]", "in column KNT = number of non-missing points in column", ") </div> \"\"\" return dirr(DerivedGridFactory.createTrueFlowVector(V)) def dirr(V): \"\"\" Grid relative", "), - ( DOT ( DVDY (V), GRAD (S) )", "(THTA) ) ) ] </div> \"\"\" dtdp = GridMath.partial(THTA,2) gradt", "return DerivedGridFactory.createVectorDirection(V) def dot(V1,V2): \"\"\" Vector dot product <div class=jython>", "a scalar grid using a 5-point smoother (see sm5s) \"\"\"", "layer average <div class=jython> VLDF(V) = [(u(level1) - u(level2))/2, (v(level1)", "the smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"RECT\", int(D))", "\"\"\" Take the derivative with respect to the domain's Y", "return layerAverage(V, level1, level2, unit) def vldf(V,level1,level2, unit=None): \"\"\" calculate", "of 2 vectors <div class=jython> VQUO (V1, V2) = [", "( S ) = S (level1) - S (level2) </div>", "BETA) - DIV ) <p> Where: BETA = ASIN (", "GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE) else: return layerAverage(S,level1,level2, unit) def ldf(S,level1,level2, unit=None): \"\"\"", ".5*mgradt*(defr(V)*cos(2*beta)-div(V)) return frnto def geo(z): \"\"\" geostrophic wind from height", "vwind = getSliceAtLevel(v, top) DIV = (ddx(uwind) + ddy(vwind))* (-1.0)", "v component \"\"\" return vr(DerivedGridFactory.createTrueFlowVector(V)) def vor(V): \"\"\" Relative Vorticity", "S (KZD) ) KZD = number of levels ZSUM for", "temp = newUnit(getSliceAtLevel(t, top), \"temperature\", \"celsius\") HT = sqrt(ddx(temp)*ddx(temp) +", "relative v component \"\"\" return DerivedGridFactory.getVComponent(V) def xav(S): \"\"\" Average", "GridMath.FUNC_AVERAGE) def zsum(S): \"\"\" Sum across the levels of a", "+ DDY ( v ) </div> \"\"\" return add(ddx(ur(V)),ddy(vr(V))) def", "return DerivedGridFactory.getVComponent(V) def xav(S): \"\"\" Average along a grid row", "= .5 * S (i,j) + .125 * ( S", "unit) def vmul(V1,V2): \"\"\" Multiply the components of 2 vectors", "Temperature and Relative humidity (requires pressure domain) \"\"\" return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh)", "weights with theoretical response of 1/e for N * delta-x", "(V) ] / LDF (Z) </div> \"\"\" dv = mag(vldf(V,top,bottom))", "sub(V1,V2) def LPIndex(u, v, z, t, top, bottom, unit): \"\"\"", "smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def", "top) DIV = (ddx(uwind) + ddy(vwind))* (-1.0) # DSH =", "(ddx(uwind) + ddy(vwind))* (-1.0) # DSH = ddx(vwind) + ddy(uwind)", "return GridUtil.smooth(S, \"SM9S\") def strd(V): \"\"\" Stretching Deformation <div class=jython>", "+ ddy(uwind))*0.318 L = add(noUnit(Z), add(noUnit(HU), noUnit(HT))) L = (L", "DIRN ( V ) = DIRR ( un(v), vn(v) )", "pressure domain) \"\"\" return DerivedGridFactory.createMixingRatio(temp,rh) def relh(temp,mixr): \"\"\" Create Relative", "return add(ddx(ur(V)),ddy(vr(V))) def dirn(V): \"\"\" North relative direction of a", "= -cosd*dxt-sind*dyt beta = asin(a/mgradt) frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V)) return frnto", "[ - DDY (S) * const / CORL, DDX (S)", "the grid diagnostics from the GEneral Meteorological PAcKage (GEMPAK). Note", "point values </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def savs(S): \"\"\"", "(i,j+1) + S (i-1,j) + S (i,j-1) ) + .0625", "return add(V1,V2) def vecn(S1,S2): \"\"\" Make a true north vector", "calculate the wind shear between discrete layers <div class=jython> EI", "windShear(u, v, z, top, bottom, unit)*7.268 uwind = getSliceAtLevel(u, top)", "in a grid <div class=jython> CORL = TWO_OMEGA*sin(latr) </div> \"\"\"", "points in row YSUM for a column is stored at", "<br> MAG ( GRAD (THTA) ) ) <br> PSI =", "= ddx(vwind) + ddy(uwind) DST = ddx(uwind) - ddy(vwind) DEF", "( DEF + DIV) </div> \"\"\" VWS = windShear(u, v,", "= cos(psi) sind = sin(psi) gradt = grad(S) mgradt =", "DIRR ( un(v), vn(v) ) </div> \"\"\" return dirr(DerivedGridFactory.createTrueFlowVector(V)) def", "u component \"\"\" return ur(DerivedGridFactory.createTrueFlowVector(V)) def ur(V): \"\"\" Grid relative", "D=2): \"\"\" <div class=jython> Apply a rectangular aperature smoothing to", "qvcl(THTA,V): \"\"\" Q-vector ( K / m / s )", "north vector from two components <div class=jython> VECN ( S1,", "= TWO_OMEGA*sin(latr) </div> \"\"\" return DerivedGridFactory.createCoriolisGrid(S) def cress(S, D=2): \"\"\"", "cos(psi) sind = sin(psi) gradt = grad(S) mgradt = mag(gradt)", "5-point smoother (see sm5s) \"\"\" return sm5s(V) def sm9v(V): \"\"\"", "the vector layer difference <div class=jython> VLDF(V) = [u(level1) -", "= number of levels ZSUM for a vertical column is", "= S1 - S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)", "aperature diffraction function in the x and y directions. D", "grid column <div class=jython> YAV (S) = ( S (Y1)", "+ S (KXD) ) KXD = number of points in", "(GEO(S)) ] </div> \"\"\" return sub(obs,geo) def circv(S, D=2): \"\"\"", "bottom, unit): \"\"\" calculate the wind shear between discrete layers", "V1, GRAD (u2) ), DOT ( V1, GRAD (v2) )", "\"\"\" return sub(obs,geo) def circv(S, D=2): \"\"\" <div class=jython> Apply", "( GRAD (S) ) </div> \"\"\" grads = grad(S) return", "from Temperature, RH (requires pressure domain) \"\"\" return DerivedGridFactory.createMixingRatio(temp,rh) def", "[ u1/u2, v1/v2 ] </div> \"\"\" return quo(V1,V2) def vsub(V1,V2):", "str). <P> In the following operators, scalar operands are named", "] </div> \"\"\" return quo(V1,V2) def vsub(V1,V2): \"\"\" subtract the", "layers <div class=jython> LP = 7.268DUDZ + 0.718DTDN + 0.318DUDN", "( S (i+1,j+1) + S (i+1,j-1) + S (i-1,j+1) +", "class=jython> YSUM (S) = ( S (Y1) + S (Y2)", "(see sm9s) \"\"\" return sm9s(V) def thrm(S, level1, level2, unit=None):", "GridMath.FUNC_AVERAGE, GridMath.AXIS_Y) def ysum(S): \"\"\" Sum along a grid column", "smoothed value is given by a weighted average of surrounding", "Note that the names are case sensitive and some are", "[ u1-u2, v1-v2 ] </div> \"\"\" return sub(V1,V2) def LPIndex(u,", "= use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.add(S1,S2,WA) def", "* MAG ( GRAD (THTA) ) * ( DEF *", "the smoothing. (default N=6) </div> \"\"\" return GridUtil.smooth(S, \"GWFS\", int(N))", "</div> \"\"\" product = mul(V1,V2) return add(ur(product),vr(product)) def gwfs(S, N=6):", "/ S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\"", "row XAV for a row is stored at every point", "vecr(qvecu,qvecv) def qvcl(THTA,V): \"\"\" Q-vector ( K / m /", "sub(S1,S2,WA=0): \"\"\" Subtract <div class=jython> SUB (S1, S2) = S1", "( S, V ) = - ( u * DDX", "number of non-missing points in column </div> \"\"\" return GridMath.applyFunctionToAxis(S,", "DDY ( u ) </div> \"\"\" return sub(ddx(vr(V)),ddy(ur(V))) def vr(V):", "ldf(Z,top,bottom) return quo(dv,dz) # Vector output def age(obs,geo): \"\"\" Ageostrophic", "return GridMath.multiply(S1,S2,WA) def quo(S1,S2,WA=0): \"\"\" Divide <div class=jython> QUO (S1,", ") <div class=jython> QVEC ( S, V ) = [", "(default D=2) </div> \"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def savg(S):", "u1-u2, v1-v2 ] </div> \"\"\" return sub(V1,V2) def LPIndex(u, v,", "(GEO(S)) (level1) - v (GEO(S)) (level2) ] </div> \"\"\" return", "** 2 + SHR (V) ** 2 ) ** .5", "- DDY ( u ) </div> \"\"\" return sub(ddx(vr(V)),ddy(ur(V))) def", "a vector \"\"\" if (len(a) == 1): return DerivedGridFactory.createVectorMagnitude(a[0]); else:", "CROS ( V1, V2 ) = u1 * v2 -", "ddx(vwind) + ddy(uwind) DST = ddx(uwind) - ddy(vwind) DEF =", "int(D)) def savg(S): \"\"\" Average over whole grid <div class=jython>", "domain) \"\"\" return DerivedGridFactory.createRelativeHumidity(temp,mixr) def pvor(S,V): \"\"\" Potetial Vorticity (usually", "* ( S (i+1,j+1) + S (i+1,j-1) + S (i-1,j+1)", "S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return", "Average over grid subset <div class=jython> SAVS ( S )", "( S (level1) + S (level2) ) / 2. </div>", "u ) </div> \"\"\" return add(ddx(vr(V)),ddy(ur(V))) def sm5s(S): \"\"\" Smooth", "def rects(S, D=2): \"\"\" <div class=jython> Apply a rectangular aperature", "unit)*7.268 uwind = getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top) temp", "grid \"\"\" return DerivedGridFactory.createLatitudeGrid(S) def lap(S): \"\"\" Laplacian operator <div", "Vorticity (usually from theta and wind) \"\"\" return DerivedGridFactory.createPotentialVorticity(S,V) def", "\"\"\" return DerivedGridFactory.createGeostrophicWindVector(z) def grad(S): \"\"\" Gradient of a scalar", "domain's X coordinate \"\"\" return GridMath.ddx(S); def ddy(S): \"\"\" Take", "frnt(S,V): \"\"\" Frontogenesis function from theta and the wind <div", "rectangular aperature diffraction function in the x and y directions.", "(default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.divide(S1,S2,WA) def sub(S1,S2,WA=0): \"\"\" Subtract", "DIV = (ddx(uwind) + ddy(vwind))* (-1.0) # DSH = ddx(vwind)", "(level1) + S (level2) ) / 2. </div> \"\"\" if", "VLDF(V) = [(u(level1) - u(level2))/2, (v(level1) - v(level2))/2] </div> \"\"\"", "= [(u(level1) - u(level2))/2, (v(level1) - v(level2))/2] </div> \"\"\" return", "a 5-point smoother <div class=jython> SM5S ( S ) =", "GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y) def zav(S): \"\"\" Average across the levels", "magnitude <div class=jython> CROS ( V1, V2 ) = u1", ") </div> \"\"\" grads = grad(S) return div(grads) def lav(S,level1=None,level2=None,", "values in the subset area </div> \"\"\" return savg(S) def", "with Jython built-ins (e.g. str). <P> In the following operators,", "AGE ( S ) = [ u (OBS) - u", "DEF + DIV) </div> \"\"\" VWS = windShear(u, v, z,", "<div class=jython> LAV ( S ) = ( S (level1)", "THRM ( S ) = [ u (GEO(S)) (level1) -", "and y directions. D is the radius of influence in", "(L - 2.520)*(-0.59) P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP = setLevel(P", "class=jython> DIV ( V ) = DDX ( u )", "GridMath.atan2(S1,S2,WA) def add(S1,S2,WA=0): \"\"\" Addition <div class=jython> ADD (S1, S2)", "2. </div> \"\"\" if level1 == None: return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE)", "S1 / S2 )<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)", "(default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.subtract(S1,S2,WA) # Scalar quantities def", "\"\"\" Average along a grid column <div class=jython> YAV (S)", "a vector <div class=jython> DVDX ( V ) = [", "return GridMath.ddx(S); def ddy(S): \"\"\" Take the derivative with respect", "= getSliceAtLevel(v, top) temp = newUnit(getSliceAtLevel(t, top), \"temperature\", \"celsius\") HT", "Apply a Cressman smoothing to the grid points. The smoothed", "+ DST * DST) EI = mul(noUnit(VWS), add(noUnit(DEF), noUnit(DIV))) return", "\"\"\" Average of 2 scalars <div class=jython> AVG (S1, S2)", "</div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X) def yav(S): \"\"\" Average", "return GridMath.add(S1,S2,WA) def mul(S1,S2,WA=0): \"\"\" Multiply <div class=jython> MUL (S1,", "\"\"\" return GridMath.ddy(S); def defr(V): \"\"\" Total deformation <div class=jython>", "be any thermal paramenter, usually THTA. </div> \"\"\" grads =", "a grid row <div class=jython> XSUM (S) = ( S", "for a column is stored at every point in that", "u * DDX (S) + v * DDY (S) )", "return sub(ddx(vr(V)),ddy(ur(V))) def vr(V): \"\"\" Grid relative v component \"\"\"", "adv(S,V): \"\"\" Horizontal Advection, negative by convention <div class=jython> ADV", "LAP ( S ) = DIV ( GRAD (S) )", "class=jython> ZAV (S) = ( S (Z1) + S (Z2)", "</div> \"\"\" return savg(S) def sdiv(S,V): \"\"\" Horizontal Flux Divergence", "shear between discrete layers <div class=jython> LP = 7.268DUDZ +", "grad(S) qvecu = newName(-dot(dvdx(V),grads),\"qvecu\") qvecv = newName(-dot(dvdy(V),grads),\"qvecv\") return vecr(qvecu,qvecv) def", ") </div> \"\"\" return GridUtil.smooth(S, \"SM9S\") def strd(V): \"\"\" Stretching", "( V ) = VOR ( V ) + CORL(V)", "BETA = ASIN ( (-DDX (THTA) * COS (PSI) <br>", "S (i,j-1) ) </div> \"\"\" return GridUtil.smooth(S, \"SM5S\") def sm9s(S):", "NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.add(S1,S2,WA) def mul(S1,S2,WA=0): \"\"\" Multiply <div", "class=jython> JCBN ( S1, S2 ) = DDX (S1) *", "wind <div class=jython> FRNT ( THTA, V ) = 1/2", "sin(psi) gradt = grad(S) mgradt = mag(gradt) a = -cosd*dxt-sind*dyt", "def vor(V): \"\"\" Relative Vorticity <div class=jython> VOR ( V", "avg(S1,S2): \"\"\" Average of 2 scalars <div class=jython> AVG (S1,", "<div class=jython> VECR ( S1, S2 ) = [ S1,", "\"\"\" return layerAverage(V, level1, level2, unit) def vldf(V,level1,level2, unit=None): \"\"\"", "to the grid points. The smoothed value is given by", "ddx(S): \"\"\" Take the derivative with respect to the domain's", "</div> \"\"\" return mag(strd(V),shr(V)) def div(V): \"\"\" Horizontal Divergence <div", "WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.atan2(S1,S2,WA) def add(S1,S2,WA=0): \"\"\"", "V2) = [ u1*u2, v1*v2 ] </div> \"\"\" return mul(V1,V2)", "points in column KNT = number of non-missing points in", "the components of 2 vectors <div class=jython> VSUB (V1, V2)", "Mixing Ratio from Temperature, RH (requires pressure domain) \"\"\" return", "<div class=jython> LAP ( S ) = DIV ( GRAD", "column <div class=jython> YSUM (S) = ( S (Y1) +", "= newName(-dot(dvdy(V),grads),\"qvecv\") return vecr(qvecu,qvecv) def qvcl(THTA,V): \"\"\" Q-vector ( K", "are case sensitive and some are named slightly different from", "for atan2 built-in <div class=jython> ATN2 (S1, S2) = ATAN", "refer to the grid relative components of a vector. \"\"\"", "] </div> \"\"\" dtdp = GridMath.partial(THTA,2) gradt = grad(THTA) qvecudp", "DEF ( V ) = ( STRD (V) ** 2", "\"\"\" return gwfs(V, N) def inad(V1,V2): \"\"\" Inertial advective wind", "avor(V): \"\"\" Absolute Vorticity <div class=jython> AVOR ( V )", "= add(noUnit(Z), add(noUnit(HU), noUnit(HT))) L = (L - 2.520)*(-0.59) P=", "def lap(S): \"\"\" Laplacian operator <div class=jython> LAP ( S", "grid subset <div class=jython> SAVS ( S ) = average", "class=jython> ATN2 (S1, S2) = ATAN ( S1 / S2", "add(V1,V2) def vecn(S1,S2): \"\"\" Make a true north vector from", "def adv(S,V): \"\"\" Horizontal Advection, negative by convention <div class=jython>", "- ( u * DDX (S) + v * DDY", "<br> </div> \"\"\" shear = shr(V) strch = strd(V) psi", ") = ( STRD (V) ** 2 + SHR (V)", "(len(a) == 1): return DerivedGridFactory.createVectorMagnitude(a[0]); else: return DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def mixr(temp,rh):", "\"\"\" calculate the vector layer average <div class=jython> VLDF(V) =", "( V ) + CORL(V) </div> \"\"\" relv = vor(V)", "KNT = number of non-missing points in column </div> \"\"\"", "grid at all points <div class=jython> ZSUM (S) = (", "v1 * v2 </div> \"\"\" product = mul(V1,V2) return add(ur(product),vr(product))", "non-missing points in column </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def", "(see sm5s) \"\"\" return sm5s(V) def sm9v(V): \"\"\" Smooth a", "+ S (i,j-1) ) </div> \"\"\" return GridUtil.smooth(S, \"SM5S\") def", "DIV) </div> \"\"\" VWS = windShear(u, v, z, top, bottom,", "for N * delta-x wave. Increasing N increases the smoothing.", "LP def EllrodIndex(u, v, z, top, bottom, unit): \"\"\" calculate", "\"\"\" This is the doc for the Grid Diagnostics module.", "def mul(S1,S2,WA=0): \"\"\" Multiply <div class=jython> MUL (S1, S2) =", "def vlav(V,level1,level2, unit=None): \"\"\" calculate the vector layer average <div", "(KZD) ) KZD = number of levels ZSUM for a", "[ - ( DOT ( DVDX (V), GRAD (S) )", "mgradt = mag(gradt) a = -cosd*dxt-sind*dyt beta = asin(a/mgradt) frnto", "(S) = ( S (Y1) + S (Y2) + ...", ") / 2 </div> \"\"\" return add(S1,S2)/2 def avor(V): \"\"\"", "S2) = S1 / S2<br> WA = use WEIGHTED_AVERAGE (default", "2 </div> \"\"\" return add(S1,S2)/2 def avor(V): \"\"\" Absolute Vorticity", "grid row <div class=jython> XAV (S) = ( S (X1)", "v, z, top, bottom, unit): \"\"\" calculate the wind shear", "\"\"\" dv = mag(vldf(V,top,bottom)) dz = ldf(Z,top,bottom) return quo(dv,dz) #", "def thta(temp): \"\"\" Potential Temperature from Temperature (requires pressure domain)", ") = [ DDX ( S ), DDY ( S", "= ( 1/( D (THTA) / DP ) ) *", "cresv(S, D=2): \"\"\" <div class=jython> Apply a Cressman smoothing to", "every point </div> \"\"\" return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM) def wshr(V, Z,", "/ KNT KZD = number of levels KNT = number", "(default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def cresv(S,", "(S) * const / CORL, DDX (S) * const /", "class=jython> INAD ( V1, V2 ) = [ DOT (", ") + CORL(V) </div> \"\"\" relv = vor(V) return add(relv,corl(relv))", "GridUtil.smooth(S, \"SM9S\") def strd(V): \"\"\" Stretching Deformation <div class=jython> STRD", ") ] where S can be any thermal paramenter, usually", "XAV for a row is stored at every point in", "Advection, negative by convention <div class=jython> ADV ( S, V", "DDY ( u ) </div> \"\"\" return add(ddx(vr(V)),ddy(ur(V))) def sm5s(S):", "functions to avoid conflicts with Jython built-ins (e.g. str). <P>", "unit=None): \"\"\" calculate the vector layer average <div class=jython> VLDF(V)", "</div> \"\"\" return vecr(ddx(ur(V)), ddx(vr(V))) def dvdy(V): \"\"\" Partial x", "GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP = setLevel(P ,top, unit) return LP def EllrodIndex(u,", "def mag(*a): \"\"\" Magnitude of a vector \"\"\" if (len(a)", "<div class=jython> Apply a circular aperature smoothing to the grid", "circv(S, D=2): \"\"\" <div class=jython> Apply a circular aperature smoothing", "</div> \"\"\" relv = vor(V) return add(relv,corl(relv)) def circs(S, D=2):", "# DSH = ddx(vwind) + ddy(uwind) DST = ddx(uwind) -", "GRAD ( S ) ) </div> \"\"\" return add(mul(S,(div(V))) ,", "relative components of a vector. \"\"\" def GRAVITY(): \"\"\" Gravity", "def vldf(V,level1,level2, unit=None): \"\"\" calculate the vector layer difference <div", "ratio (requires pressure domain) \"\"\" return DerivedGridFactory.createRelativeHumidity(temp,mixr) def pvor(S,V): \"\"\"", "DDY (S2) - DDY (S1) * DDX (S2) </div> \"\"\"", "1/e for N * delta-x wave. Increasing N increases the", "( S (i+1,j) + S (i,j+1) + S (i-1,j) +", "using a 9-point smoother (see sm9s) \"\"\" return sm9s(V) def", "AVOR ( V ) = VOR ( V ) +", "u2 + v1 * v2 </div> \"\"\" product = mul(V1,V2)", "S2 ) = [ S1, S2 ] </div> \"\"\" return", "This is the doc for the Grid Diagnostics module. These", "( V ) = DDX ( u ) + DDY", "at every point in that column. </div> \"\"\" return GridMath.applyFunctionToAxis(S,", "= [ S1, S2 ] </div> \"\"\" return makeTrueVector(S1,S2) def", "(S1, S2) = S1 - S2<br> WA = use WEIGHTED_AVERAGE", "a grid column <div class=jython> YAV (S) = ( S", "smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def", "from Temperature, mixing ratio (requires pressure domain) \"\"\" return DerivedGridFactory.createRelativeHumidity(temp,mixr)", "unit=None): \"\"\" calculate the vector layer difference <div class=jython> VLDF(V)", "+ S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\"", "(PSI))/ <br> MAG ( GRAD (THTA) ) ) <br> PSI", "along a grid column <div class=jython> YAV (S) = (", "WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.atan2(S1,S2,WA)", "( S ) = average of all non-missing grid point", "S (Z2) + ... + S (KZD) ) / KNT", "THTA. </div> \"\"\" grads = grad(S) qvecu = newName(-dot(dvdx(V),grads),\"qvecu\") qvecv", "( S ) = [ u (OBS) - u (GEO(S)),", "</div> \"\"\" return quo(V1,V2) def vsub(V1,V2): \"\"\" subtract the components", "average <div class=jython> VLDF(V) = [(u(level1) - u(level2))/2, (v(level1) -", "</div> \"\"\" return DerivedGridFactory.createCoriolisGrid(S) def cress(S, D=2): \"\"\" <div class=jython>", "* const / CORL ] </div> \"\"\" return DerivedGridFactory.createGeostrophicWindVector(z) def", "xav(S): \"\"\" Average along a grid row <div class=jython> XAV", "- v(level2)] </div> \"\"\" return layerDiff(V,level1,level2, unit) def vmul(V1,V2): \"\"\"", "+ ... + S (KZD) ) KZD = number of", "smoothing. (default N=6) </div> \"\"\" return GridUtil.smooth(S, \"GWFS\", int(N)) def", "m / s ) <div class=jython> QVCL ( THTA, V", "Average of 2 scalars <div class=jython> AVG (S1, S2) =", "to the domain's Y coordinate \"\"\" return GridMath.ddy(S); def defr(V):", "grid relative components of a vector. \"\"\" def GRAVITY(): \"\"\"", "return vecr(ddx(ur(V)), ddx(vr(V))) def dvdy(V): \"\"\" Partial x derivative of", "vectors <div class=jython> VADD (V1, V2) = [ u1+u2, v1+v2", "<div class=jython> VMUL (V1, V2) = [ u1*u2, v1*v2 ]", "vector <div class=jython> DIRN ( V ) = DIRR (", "column <div class=jython> YAV (S) = ( S (Y1) +", "V ) = VOR ( V ) + CORL(V) </div>", "number of points in row KNT = number of non-missing", "class=jython> DOT ( V1, V2 ) = u1 * u2", "\"\"\" return DerivedGridFactory.getVComponent(V) def xav(S): \"\"\" Average along a grid", "ddy(vwind))* (-1.0) # DSH = ddx(vwind) + ddy(uwind) DST =", "/ DP ) ) * [ ( DOT ( DVDX", "Jacobian Determinant <div class=jython> JCBN ( S1, S2 ) =", "= .5*atn2(shear,strch) dxt = ddx(S) dyt = ddy(S) cosd =", "QVCL ( THTA, V ) = ( 1/( D (THTA)", "return vr(DerivedGridFactory.createTrueFlowVector(V)) def vor(V): \"\"\" Relative Vorticity <div class=jython> VOR", "Grid Diagnostics module. These functions are based on the grid", "else: return DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def mixr(temp,rh): \"\"\" Mixing Ratio from Temperature,", "\"\"\" calculate the wind shear between discrete layers <div class=jython>", "Layer Difference <div class=jython> LDF ( S ) = S", "qvecu = newName(-dot(dvdx(V),grads),\"qvecu\") qvecv = newName(-dot(dvdy(V),grads),\"qvecv\") return vecr(qvecu,qvecv) def qvcl(THTA,V):", "\"\"\" Inertial advective wind <div class=jython> INAD ( V1, V2", "scalar grid using a 5-point smoother (see sm5s) \"\"\" return", "v1 </div> \"\"\" return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def ddx(S): \"\"\" Take the", "return sub(ddx(ur(V)),ddy(vr(V))) def thta(temp): \"\"\" Potential Temperature from Temperature (requires", "negative by convention <div class=jython> ADV ( S, V )", "+ S (i+1,j-1) + S (i-1,j+1) + S (i-1,j-1) )", "level1, level2, unit=None): \"\"\" Thermal wind <div class=jython> THRM (", "bottom): \"\"\" Magnitude of the vertical wind shear in a", "def sm5s(S): \"\"\" Smooth a scalar grid using a 5-point", "<div class=jython> SAVG ( S ) = average of all", "ADD (S1, S2) = S1 + S2<br> WA = use", "GRAD (THTA) ) ), ( DOT ( DVDY (V), GRAD", "(V1, V2) = [ u1+u2, v1+v2 ] </div> \"\"\" return", "- 2.520)*(-0.59) P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP = setLevel(P ,top,", "Shear Deformation <div class=jython> SHR ( V ) = DDX", "YAV (S) = ( S (Y1) + S (Y2) +", "V ) = - ( u * DDX (S) +", "Partial x derivative of a vector <div class=jython> DVDX (", "of a vector <div class=jython> DIRN ( V ) =", "<div class=jython> Apply a Cressman smoothing to the grid points.", "</div> \"\"\" shear = shr(V) strch = strd(V) psi =", "(S1) * DDY (S2) - DDY (S1) * DDX (S2)", "VWS = windShear(u, v, z, top, bottom, unit)*100.0 # uwind", "D=2) </div> \"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def corl(S): \"\"\"", "S2) = S1 + S2<br> WA = use WEIGHTED_AVERAGE (default", "JCBN ( S1, S2 ) = DDX (S1) * DDY", "D=2) </div> \"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def dvdx(V): \"\"\"", "2 vectors <div class=jython> VMUL (V1, V2) = [ u1*u2,", "\"\"\" return GridMath.ddx(S); def ddy(S): \"\"\" Take the derivative with", "level2, unit=None): \"\"\" Thermal wind <div class=jython> THRM ( S", "ur(V): \"\"\" Grid relative u component \"\"\" return DerivedGridFactory.getUComponent(V) def", "class=jython> QUO (S1, S2) = S1 / S2<br> WA =", "= VOR ( V ) + CORL(V) </div> \"\"\" relv", "WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.add(S1,S2,WA)", "S1 * S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div>", "WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.subtract(S1,S2,WA) # Scalar quantities", "vector layer average <div class=jython> VLDF(V) = [(u(level1) - u(level2))/2,", "+ CORL(V) </div> \"\"\" relv = vor(V) return add(relv,corl(relv)) def", "shear = shr(V) strch = strd(V) psi = .5*atn2(shear,strch) dxt", "cosd = cos(psi) sind = sin(psi) gradt = grad(S) mgradt", "K / m / s ) <div class=jython> QVCL (", "V ) = 1/2 * MAG ( GRAD (THTA) )", "V1, V2 ) = u1 * u2 + v1 *", "(requires pressure domain) \"\"\" return DerivedGridFactory.createPotentialTemperature(temp) def thte(temp,rh): \"\"\" Equivalent", "= [ - ( DOT ( DVDX (V), GRAD (S)", "u1 * u2 + v1 * v2 </div> \"\"\" product", "class=jython> SUB (S1, S2) = S1 - S2<br> WA =", "Inertial advective wind <div class=jython> INAD ( V1, V2 )", "built-in <div class=jython> ATN2 (S1, S2) = ATAN ( S1", "</div> \"\"\" return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def qvec(S,V): \"\"\" Q-vector at a", "sm9s) \"\"\" return sm9s(V) def thrm(S, level1, level2, unit=None): \"\"\"", "return vecr(qvecu,qvecv) def qvcl(THTA,V): \"\"\" Q-vector ( K / m", "with theoretical response of 1/e for N * delta-x wave.", "\"\"\" VWS = windShear(u, v, z, top, bottom, unit)*100.0 #", "sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718 HU = (ddx(vwind) + ddy(uwind))*0.318 L =", "scalars <div class=jython> AVG (S1, S2) = ( S1 +", "diffraction function in the x and y directions. D is", "in that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X) def", "(u2) ), DOT ( V1, GRAD (v2) ) ] </div>", "of non-missing points in row XAV for a row is", "</div> \"\"\" return GridMath.atan2(S1,S2,WA) def add(S1,S2,WA=0): \"\"\" Addition <div class=jython>", "use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.subtract(S1,S2,WA) # Scalar", "mul(V1,V2) return add(ur(product),vr(product)) def gwfs(S, N=6): \"\"\" <div class=jython> Horizontal", "S2 ] </div> \"\"\" return makeTrueVector(S1,S2) def vecr(S1,S2): \"\"\" Make", "V2) = [ u1-u2, v1-v2 ] </div> \"\"\" return sub(V1,V2)", "KZD = number of levels ZSUM for a vertical column", "\"\"\" return GridMath.add(S1,S2,WA) def mul(S1,S2,WA=0): \"\"\" Multiply <div class=jython> MUL", "\"\"\" return GridUtil.smooth(S, \"SM9S\") def strd(V): \"\"\" Stretching Deformation <div", "GRAD (S) ) </div> \"\"\" grads = grad(S) return div(grads)", "= 7.268DUDZ + 0.718DTDN + 0.318DUDN - 2.52 </div> \"\"\"", "GridMath.multiply(S1,S2,WA) def quo(S1,S2,WA=0): \"\"\" Divide <div class=jython> QUO (S1, S2)", "), ( DOT ( DVDY (V), GRAD (THTA) ) )", "int(D)) def cros(V1,V2): \"\"\" Vector cross product magnitude <div class=jython>", "= vor(V) return add(relv,corl(relv)) def circs(S, D=2): \"\"\" <div class=jython>", "</div> \"\"\" return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def latr(S): \"\"\" Latitudue all points", "( S, V ) = S * DIV ( V", "layer grid <div class=jython> LAV ( S ) = (", "v (GEO(S)) ] </div> \"\"\" return sub(obs,geo) def circv(S, D=2):", "int(D)) def dvdx(V): \"\"\" Partial x derivative of a vector", "\"\"\" North relative v component \"\"\" return vr(DerivedGridFactory.createTrueFlowVector(V)) def vor(V):", "<div class=jython> DVDY ( V ) = [ DDY (u),", "layerAverage(S,level1,level2, unit) def ldf(S,level1,level2, unit=None): \"\"\" Layer Difference <div class=jython>", "\"\"\" Multiply the components of 2 vectors <div class=jython> VMUL", "DDY (S1) * DDX (S2) </div> \"\"\" return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def", "( DOT ( DVDY (V), GRAD (S) ) ) ]", "\"\"\" Magnitude of the vertical wind shear in a layer", "S ) ] </div> \"\"\" return vecr(ddx(S),ddy(S)) def gwfv(V, N=6):", "a grid \"\"\" return DerivedGridFactory.createLatitudeGrid(S) def lap(S): \"\"\" Laplacian operator", "top) vwind = getSliceAtLevel(v, top) DIV = (ddx(uwind) + ddy(vwind))*", "\"\"\" def GRAVITY(): \"\"\" Gravity constant \"\"\" return DerivedGridFactory.GRAVITY; #", "that column. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y) def zav(S):", "( V1, V2 ) = u1 * u2 + v1", "GridUtil.smooth(S, \"CIRC\", int(D)) def corl(S): \"\"\" Coriolis Parameter for all", "column. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y) def zav(S): \"\"\"", "newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return vecr(qvecudp,qvecvdp) def rectv(S, D=2): \"\"\" <div class=jython> Apply", "Relative Humidity from Temperature, mixing ratio (requires pressure domain) \"\"\"", "smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def", "domain's Y coordinate \"\"\" return GridMath.ddy(S); def defr(V): \"\"\" Total", "GRAVITY(): \"\"\" Gravity constant \"\"\" return DerivedGridFactory.GRAVITY; # Math functions", "v2 </div> \"\"\" product = mul(V1,V2) return add(ur(product),vr(product)) def gwfs(S,", "\"\"\" return DerivedGridFactory.createLatitudeGrid(S) def lap(S): \"\"\" Laplacian operator <div class=jython>", "(i,j+1) + S (i-1,j) + S (i,j-1) ) </div> \"\"\"", "return layerDiff(S,level1,level2, unit); def mag(*a): \"\"\" Magnitude of a vector", "sub(ddx(ur(V)),ddy(vr(V))) def thta(temp): \"\"\" Potential Temperature from Temperature (requires pressure", "DDY ( v ) </div> \"\"\" return sub(ddx(ur(V)),ddy(vr(V))) def thta(temp):", "from theta and the wind <div class=jython> FRNT ( THTA,", "in the x and y directions. D is the radius", "= S1 * S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)", "</div> \"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def sm5v(V): \"\"\" Smooth", "Partial x derivative of a vector <div class=jython> DVDY (", "\"\"\" return makeTrueVector(S1,S2) def vecr(S1,S2): \"\"\" Make a vector from", "= [ u (OBS) - u (GEO(S)), v (OBS) -", "= number of non-missing points in column </div> \"\"\" return", ") KYD = number of points in row YSUM for", "KXD = number of points in row KNT = number", "vecr(ddx(S),ddy(S)) def gwfv(V, N=6): \"\"\" <div class=jython> Horizontal smoothing using", "KNT KZD = number of levels KNT = number of", "</div> \"\"\" VWS = windShear(u, v, z, top, bottom, unit)*100.0", "NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.multiply(S1,S2,WA) def quo(S1,S2,WA=0): \"\"\" Divide <div", ") + DOT ( V, GRAD ( S ) )", "convention <div class=jython> ADV ( S, V ) = -", "\"\"\" Sum along a grid column <div class=jython> YSUM (S)", "u1 * v2 - u2 * v1 </div> \"\"\" return", "levels of a grid at all points <div class=jython> ZAV", "= [ - DDY (S) * const / CORL, DDX", "L = (L - 2.520)*(-0.59) P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP", "<div class=jython> VADD (V1, V2) = [ u1+u2, v1+v2 ]", "- ( DOT ( DVDX (V), GRAD (S) ) ),", "VOR ( V ) + CORL(V) </div> \"\"\" relv =", "S1 + S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div>", "coordinate \"\"\" return GridMath.ddy(S); def defr(V): \"\"\" Total deformation <div", "a 9-point smoother (see sm9s) \"\"\" return sm9s(V) def thrm(S,", "and some are named slightly different from GEMPAK functions to", "grad(S) mgradt = mag(gradt) a = -cosd*dxt-sind*dyt beta = asin(a/mgradt)", "and the wind <div class=jython> FRNT ( THTA, V )", "def pvor(S,V): \"\"\" Potetial Vorticity (usually from theta and wind)", "- u(level2))/2, (v(level1) - v(level2))/2] </div> \"\"\" return layerAverage(V, level1,", "(level2) ] </div> \"\"\" return vldf(geo(S),level1,level2, unit) def vadd(V1,V2): \"\"\"", "class=jython> DEF ( V ) = ( STRD (V) **", "unit=None): \"\"\" Thermal wind <div class=jython> THRM ( S )", "from the GEneral Meteorological PAcKage (GEMPAK). Note that the names", "X ( DEF + DIV) </div> \"\"\" VWS = windShear(u,", "return GridMath.ddy(S); def defr(V): \"\"\" Total deformation <div class=jython> DEF", ") + .0625 * ( S (i+1,j+1) + S (i+1,j-1)", "\"\"\" return DerivedGridFactory.createVectorDirection(V) def dot(V1,V2): \"\"\" Vector dot product <div", "distributed weights with theoretical response of 1/e for N *", "coordinate \"\"\" return GridMath.ddx(S); def ddy(S): \"\"\" Take the derivative", "(level1) - u (GEO(S)) (level2), v (GEO(S)) (level1) - v", "column </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def zsum(S): \"\"\" Sum", "qvecv = newName(-dot(dvdy(V),grads),\"qvecv\") return vecr(qvecu,qvecv) def qvcl(THTA,V): \"\"\" Q-vector (", "function. D is the radius of influence in grid increments,", "( u ) </div> \"\"\" return sub(ddx(vr(V)),ddy(ur(V))) def vr(V): \"\"\"", "sm9v(V): \"\"\" Smooth a scalar grid using a 9-point smoother", "every point in that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE,", "<div class=jython> FRNT ( THTA, V ) = 1/2 *", "class=jython> SHR ( V ) = DDX ( v )", ") * ( DEF * COS (2 * BETA) -", "class=jython> SDIV ( S, V ) = S * DIV", "with respect to the domain's Y coordinate \"\"\" return GridMath.ddy(S);", "( S1, S2 ) = DDX (S1) * DDY (S2)", "all points <div class=jython> ZAV (S) = ( S (Z1)", "\"\"\" Z = windShear(u, v, z, top, bottom, unit)*7.268 uwind", "x derivative of a vector <div class=jython> DVDY ( V", "Addition <div class=jython> ADD (S1, S2) = S1 + S2<br>", "V2 ) = u1 * u2 + v1 * v2", "newName(-dot(dvdx(V),grads),\"qvecu\") qvecv = newName(-dot(dvdy(V),grads),\"qvecv\") return vecr(qvecu,qvecv) def qvcl(THTA,V): \"\"\" Q-vector", "\"\"\" return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def ddx(S): \"\"\" Take the derivative with", ") = .25 * S (i,j) + .125 * (", "+ S (Z2) + ... + S (KZD) ) /", "with respect to the domain's X coordinate \"\"\" return GridMath.ddx(S);", "S, V ) = S * DIV ( V )", "(V), GRAD (S) ) ) ] where S can be", "PAcKage (GEMPAK). Note that the names are case sensitive and", "u and v refer to the grid relative components of", "getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top) DIV = (ddx(uwind) +", "S ) = S (level1) - S (level2) </div> \"\"\"", "return makeTrueVector(S1,S2) def vecr(S1,S2): \"\"\" Make a vector from two", "relative u component \"\"\" return ur(DerivedGridFactory.createTrueFlowVector(V)) def ur(V): \"\"\" Grid", ") </div> \"\"\" return sub(ddx(vr(V)),ddy(ur(V))) def vr(V): \"\"\" Grid relative", "a vector from two components <div class=jython> VECR ( S1,", "vectors <div class=jython> VQUO (V1, V2) = [ u1/u2, v1/v2", "a true north vector from two components <div class=jython> VECN", "D=2): \"\"\" <div class=jython> Apply a Cressman smoothing to the", "(requires pressure domain) \"\"\" return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def un(V): \"\"\" North", "S (level1) - S (level2) </div> \"\"\" return layerDiff(S,level1,level2, unit);", "from theta and wind) \"\"\" return DerivedGridFactory.createPotentialVorticity(S,V) def rects(S, D=2):", "( K / m / s ) <div class=jython> QVCL", "\"\"\" North relative u component \"\"\" return ur(DerivedGridFactory.createTrueFlowVector(V)) def ur(V):", "( S ) = [ - DDY (S) * const", "u1+u2, v1+v2 ] </div> \"\"\" return add(V1,V2) def vecn(S1,S2): \"\"\"", "return GridUtil.smooth(S, \"RECT\", int(D)) def sm5v(V): \"\"\" Smooth a scalar", "layerDiff(V,level1,level2, unit) def vmul(V1,V2): \"\"\" Multiply the components of 2", "/ KNT KYD = number of points in column KNT", "ddy(uwind) DST = ddx(uwind) - ddy(vwind) DEF = sqrt(DSH *", "-cosd*dxt-sind*dyt beta = asin(a/mgradt) frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V)) return frnto def", "1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP = setLevel(P ,top, unit) return LP", "\"\"\" return vr(DerivedGridFactory.createTrueFlowVector(V)) def vor(V): \"\"\" Relative Vorticity <div class=jython>", "\"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def cresv(S, D=2): \"\"\" <div", "is stored at every point </div> \"\"\" return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM)", "(GEO(S)) (level2) ] </div> \"\"\" return vldf(geo(S),level1,level2, unit) def vadd(V1,V2):", "along a grid column <div class=jython> YSUM (S) = (", "DDY (S) ) </div> \"\"\" return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def avg(S1,S2): \"\"\"", ") - DDY ( v ) </div> \"\"\" return sub(ddx(ur(V)),ddy(vr(V)))", "WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.multiply(S1,S2,WA) def quo(S1,S2,WA=0): \"\"\"", "\"\"\" Frontogenesis function from theta and the wind <div class=jython>", "(S) ) </div> \"\"\" grads = grad(S) return div(grads) def", "(X1) + S (X2) + ... + S (KXD) )", "return sm9s(V) def thrm(S, level1, level2, unit=None): \"\"\" Thermal wind", "(GEO(S)) (level1) - u (GEO(S)) (level2), v (GEO(S)) (level1) -", "increases the smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CRES\",", "= sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718 HU = (ddx(vwind) + ddy(uwind))*0.318 L", "vsub(V1,V2): \"\"\" subtract the components of 2 vectors <div class=jython>", "= use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.divide(S1,S2,WA) def", "return DerivedGridFactory.createPotentialTemperature(temp) def thte(temp,rh): \"\"\" Equivalent Potential Temperature from Temperature", "\"\"\" return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM) def wshr(V, Z, top, bottom): \"\"\"", "GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X) def yav(S): \"\"\" Average along a grid", "for all points in a grid <div class=jython> CORL =", "/ S2 )<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div>", "* DIV ( V ) + DOT ( V, GRAD", "def dot(V1,V2): \"\"\" Vector dot product <div class=jython> DOT (", "of a vector. \"\"\" def GRAVITY(): \"\"\" Gravity constant \"\"\"", "return layerAverage(S,level1,level2, unit) def ldf(S,level1,level2, unit=None): \"\"\" Layer Difference <div", "Difference <div class=jython> LDF ( S ) = S (level1)", "dxt = ddx(S) dyt = ddy(S) cosd = cos(psi) sind", "u (OBS) - u (GEO(S)), v (OBS) - v (GEO(S))", "S, V ) = - ( u * DDX (S)", "GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM) def wshr(V, Z, top, bottom): \"\"\" Magnitude of", "GRAD (S) ) ) ] where S can be any", "(GEO(S)) (level2), v (GEO(S)) (level1) - v (GEO(S)) (level2) ]", "smoother (see sm5s) \"\"\" return sm5s(V) def sm9v(V): \"\"\" Smooth", "a vector <div class=jython> DIRN ( V ) = DIRR", "V ) = S * DIV ( V ) +", "class=jython> WSHR ( V ) = MAG [ VLDF (V)", ") ] </div> \"\"\" return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def qvec(S,V): \"\"\" Q-vector", "theta and the wind <div class=jython> FRNT ( THTA, V", "= ddx(uwind) - ddy(vwind) DEF = sqrt(DSH * DSH +", "the smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CRES\", int(D))", "layer difference <div class=jython> VLDF(V) = [u(level1) - u(level2), v(level1)", "V ) = [ - ( DOT ( DVDX (V),", "(2 * BETA) - DIV ) <p> Where: BETA =", "unit)*100.0 # uwind = getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top)", "geostrophic wind from height <div class=jython> GEO ( S )", "</div> \"\"\" return sub(ddx(ur(V)),ddy(vr(V))) def thta(temp): \"\"\" Potential Temperature from", "that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X) def yav(S):", "] </div> \"\"\" return vecr(ddy(ur(V)), ddy(vr(V))) def frnt(S,V): \"\"\" Frontogenesis", "(default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def cros(V1,V2):", "+ S (i,j-1) ) + .0625 * ( S (i+1,j+1)", "\"\"\" grads = grad(S) return div(grads) def lav(S,level1=None,level2=None, unit=None): \"\"\"", "SHR / STR ) <br> </div> \"\"\" shear = shr(V)", "Horizontal Flux Divergence <div class=jython> SDIV ( S, V )", ") </div> \"\"\" return add(mul(S,(div(V))) , dot(V,grad(S))) def shr(V): \"\"\"", "difference <div class=jython> VLDF(V) = [u(level1) - u(level2), v(level1) -", "Subtract <div class=jython> SUB (S1, S2) = S1 - S2<br>", "(i,j-1) ) </div> \"\"\" return GridUtil.smooth(S, \"SM5S\") def sm9s(S): \"\"\"", "gwfs(S, N=6): \"\"\" <div class=jython> Horizontal smoothing using normally distributed", "\"\"\" add the components of 2 vectors <div class=jython> VADD", "WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.multiply(S1,S2,WA)", "thermal paramenter, usually THTA. </div> \"\"\" grads = grad(S) qvecu", "ddx(vr(V))) def dvdy(V): \"\"\" Partial x derivative of a vector", "vr(DerivedGridFactory.createTrueFlowVector(V)) def vor(V): \"\"\" Relative Vorticity <div class=jython> VOR (", "getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top) temp = newUnit(getSliceAtLevel(t, top),", "a scalar grid using a 9-point smoother <div class=jython> SM9S", "the GEneral Meteorological PAcKage (GEMPAK). Note that the names are", "vectors <div class=jython> VSUB (V1, V2) = [ u1-u2, v1-v2", "def vecr(S1,S2): \"\"\" Make a vector from two components <div", "the components of 2 vectors <div class=jython> VQUO (V1, V2)", "normally distributed weights with theoretical response of 1/e for N", "] </div> \"\"\" return add(V1,V2) def vecn(S1,S2): \"\"\" Make a", ") = - ( u * DDX (S) + v", "DDX (v) ] </div> \"\"\" return vecr(ddx(ur(V)), ddx(vr(V))) def dvdy(V):", "VECR ( S1, S2 ) = [ S1, S2 ]", "* ( S (i+1,j) + S (i,j+1) + S (i-1,j)", "S (i+1,j-1) + S (i-1,j+1) + S (i-1,j-1) ) </div>", "non-missing points in column </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y)", "grads = grad(S) return div(grads) def lav(S,level1=None,level2=None, unit=None): \"\"\" Layer", "Smooth a scalar grid using a 5-point smoother <div class=jython>", "dyt = ddy(S) cosd = cos(psi) sind = sin(psi) gradt", "u(level2))/2, (v(level1) - v(level2))/2] </div> \"\"\" return layerAverage(V, level1, level2,", "v ) </div> \"\"\" return add(ddx(ur(V)),ddy(vr(V))) def dirn(V): \"\"\" North", "<div class=jython> STRD ( V ) = DDX ( u", "non-missing points in row XAV for a row is stored", "relative direction of a vector \"\"\" return DerivedGridFactory.createVectorDirection(V) def dot(V1,V2):", "def circv(S, D=2): \"\"\" <div class=jython> Apply a circular aperature", "<div class=jython> ADV ( S, V ) = - (", ") KZD = number of levels ZSUM for a vertical", "any thermal paramenter, usually THTA. </div> \"\"\" grads = grad(S)", "def zav(S): \"\"\" Average across the levels of a grid", "DST) EI = mul(noUnit(VWS), add(noUnit(DEF), noUnit(DIV))) return setLevel(EI, top, unit)", "\"\"\" Average over whole grid <div class=jython> SAVG ( S", "and v refer to the grid relative components of a", "atn2(S1,S2,WA=0): \"\"\" Wrapper for atan2 built-in <div class=jython> ATN2 (S1,", "a scalar grid using a 5-point smoother <div class=jython> SM5S", "class=jython> Apply a circular aperature smoothing to the grid points.", "Wrapper for atan2 built-in <div class=jython> ATN2 (S1, S2) =", "mag(vldf(V,top,bottom)) dz = ldf(Z,top,bottom) return quo(dv,dz) # Vector output def", "\"\"\" Partial x derivative of a vector <div class=jython> DVDY", "def quo(S1,S2,WA=0): \"\"\" Divide <div class=jython> QUO (S1, S2) =", "the circular aperature diffraction function. D is the radius of", "( V ) + DOT ( V, GRAD ( S", "values </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def savs(S): \"\"\" Average", "V ) + CORL(V) </div> \"\"\" relv = vor(V) return", "- DDY (S1) * DDX (S2) </div> \"\"\" return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2)))", "operands are named V<sub>n</sub>. Lowercase u and v refer to", "S (KXD) ) / KNT KXD = number of points", "int(D)) def sm5v(V): \"\"\" Smooth a scalar grid using a", "pressure domain) \"\"\" return DerivedGridFactory.createPotentialTemperature(temp) def thte(temp,rh): \"\"\" Equivalent Potential", "and Relative humidity (requires pressure domain) \"\"\" return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def", "(requires pressure domain) \"\"\" return DerivedGridFactory.createMixingRatio(temp,rh) def relh(temp,mixr): \"\"\" Create", "over whole grid <div class=jython> SAVG ( S ) =", "calculate the wind shear between discrete layers <div class=jython> LP", "+ 0.318DUDN - 2.52 </div> \"\"\" Z = windShear(u, v,", "LDF (Z) </div> \"\"\" dv = mag(vldf(V,top,bottom)) dz = ldf(Z,top,bottom)", "return vldf(geo(S),level1,level2, unit) def vadd(V1,V2): \"\"\" add the components of", "vector from two components <div class=jython> VECN ( S1, S2", "* v2 - u2 * v1 </div> \"\"\" return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1)))", "\"\"\" return add(ddx(ur(V)),ddy(vr(V))) def dirn(V): \"\"\" North relative direction of", "</div> \"\"\" return add(V1,V2) def vecn(S1,S2): \"\"\" Make a true", "Relative humidity (requires pressure domain) \"\"\" return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def un(V):", "Average along a grid column <div class=jython> YAV (S) =", "S (Y2) + ... + S (KYD) ) KYD =", "S2) = S1 - S2<br> WA = use WEIGHTED_AVERAGE (default", "( (-DDX (THTA) * COS (PSI) <br> - DDY (THTA)", "THTA, V ) = 1/2 * MAG ( GRAD (THTA)", "GEMPAK functions to avoid conflicts with Jython built-ins (e.g. str).", "2 vectors <div class=jython> VQUO (V1, V2) = [ u1/u2,", "<div class=jython> SDIV ( S, V ) = S *", "V1, V2 ) = u1 * v2 - u2 *", "- DDY ( v ) </div> \"\"\" return sub(ddx(ur(V)),ddy(vr(V))) def", "(KXD) ) KXD = number of points in row XSUM", "s ) <div class=jython> QVEC ( S, V ) =", "- v (GEO(S)) (level2) ] </div> \"\"\" return vldf(geo(S),level1,level2, unit)", "vector from two components <div class=jython> VECR ( S1, S2", "( DOT ( DVDX (V), GRAD (S) ) ), -", "return div(grads) def lav(S,level1=None,level2=None, unit=None): \"\"\" Layer Average of a", "cros(V1,V2): \"\"\" Vector cross product magnitude <div class=jython> CROS (", "+ ddy(uwind) DST = ddx(uwind) - ddy(vwind) DEF = sqrt(DSH", "from two components <div class=jython> VECR ( S1, S2 )", "are named S<sub>n</sub> and vector operands are named V<sub>n</sub>. Lowercase", "\"\"\" geostrophic wind from height <div class=jython> GEO ( S", "</div> \"\"\" return GridMath.subtract(S1,S2,WA) # Scalar quantities def adv(S,V): \"\"\"", "= DDX ( u ) + DDY ( v )", "vn(v) ) </div> \"\"\" return dirr(DerivedGridFactory.createTrueFlowVector(V)) def dirr(V): \"\"\" Grid", "level1, level2, unit) def vldf(V,level1,level2, unit=None): \"\"\" calculate the vector", "= grad(S) return div(grads) def lav(S,level1=None,level2=None, unit=None): \"\"\" Layer Average", ") = [ u (OBS) - u (GEO(S)), v (OBS)", "DDX ( S ), DDY ( S ) ] </div>", "Temperature, mixing ratio (requires pressure domain) \"\"\" return DerivedGridFactory.createRelativeHumidity(temp,mixr) def", "(level2) </div> \"\"\" return layerDiff(S,level1,level2, unit); def mag(*a): \"\"\" Magnitude", "circular aperature smoothing to the grid points. The weighting function", "stored at every point in that column. </div> \"\"\" return", "DDY (u), DDY (v) ] </div> \"\"\" return vecr(ddy(ur(V)), ddy(vr(V)))", "+ S (i-1,j) + S (i,j-1) ) + .0625 *", "</div> \"\"\" return GridUtil.smooth(S, \"SM9S\") def strd(V): \"\"\" Stretching Deformation", "add(ddx(vr(V)),ddy(ur(V))) def sm5s(S): \"\"\" Smooth a scalar grid using a", "in a layer <div class=jython> WSHR ( V ) =", ") = [ DOT ( V1, GRAD (u2) ), DOT", "<div class=jython> Horizontal smoothing using normally distributed weights with theoretical", "use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.multiply(S1,S2,WA) def quo(S1,S2,WA=0):", "def corl(S): \"\"\" Coriolis Parameter for all points in a", "from two components <div class=jython> VECN ( S1, S2 )", "bottom, unit)*100.0 # uwind = getSliceAtLevel(u, top) vwind = getSliceAtLevel(v,", "a vector. \"\"\" def GRAVITY(): \"\"\" Gravity constant \"\"\" return", "( v ) </div> \"\"\" return add(ddx(ur(V)),ddy(vr(V))) def dirn(V): \"\"\"", "VLDF (V) ] / LDF (Z) </div> \"\"\" dv =", "number of levels ZSUM for a vertical column is stored", "<div class=jython> ZSUM (S) = ( S (Z1) + S", "quantities def adv(S,V): \"\"\" Horizontal Advection, negative by convention <div", "sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def ddx(S): \"\"\" Take the derivative with respect to", "- DDY (S) * const / CORL, DDX (S) *", "( V1, V2 ) = [ DOT ( V1, GRAD", "+ ... + S (KYD) ) / KNT KYD =", "\"\"\" return vldf(geo(S),level1,level2, unit) def vadd(V1,V2): \"\"\" add the components", "direction of a vector <div class=jython> DIRN ( V )", "S (i+1,j) + S (i,j+1) + S (i-1,j) + S", "= number of points in row XSUM for a row", "all points in a grid <div class=jython> CORL = TWO_OMEGA*sin(latr)", "\"\"\" Vector dot product <div class=jython> DOT ( V1, V2", "influence in grid increments, increasing D increases the smoothing. (default", "Lowercase u and v refer to the grid relative components", "unit=None): \"\"\" Layer Average of a multi layer grid <div", "bottom, unit)*7.268 uwind = getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top)", "Increasing N increases the smoothing. (default N=6) </div> \"\"\" return", "mixing ratio (requires pressure domain) \"\"\" return DerivedGridFactory.createRelativeHumidity(temp,mixr) def pvor(S,V):", "return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def zsum(S): \"\"\" Sum across the levels", "the components of 2 vectors <div class=jython> VMUL (V1, V2)", "[ VLDF (V) ] / LDF (Z) </div> \"\"\" dv", "= ( STRD (V) ** 2 + SHR (V) **", "<div class=jython> DIV ( V ) = DDX ( u", "\"\"\" return sm5s(V) def sm9v(V): \"\"\" Smooth a scalar grid", "v(level1) - v(level2)] </div> \"\"\" return layerDiff(V,level1,level2, unit) def vmul(V1,V2):", "t, top, bottom, unit): \"\"\" calculate the wind shear between", "return frnto def geo(z): \"\"\" geostrophic wind from height <div", "return GridMath.atan2(S1,S2,WA) def add(S1,S2,WA=0): \"\"\" Addition <div class=jython> ADD (S1,", "component \"\"\" return DerivedGridFactory.getVComponent(V) def xav(S): \"\"\" Average along a", "components of 2 vectors <div class=jython> VQUO (V1, V2) =", "in row XAV for a row is stored at every", "Divergence <div class=jython> SDIV ( S, V ) = S", "N) def inad(V1,V2): \"\"\" Inertial advective wind <div class=jython> INAD", "<div class=jython> QUO (S1, S2) = S1 / S2<br> WA", "DEF * COS (2 * BETA) - DIV ) <p>", "m / s ) <div class=jython> QVEC ( S, V", "directions. D is the radius of influence in grid increments,", "by a weighted average of surrounding grid points. D is", "XSUM for a row is stored at every point in", "return sm5s(V) def sm9v(V): \"\"\" Smooth a scalar grid using", "cross product magnitude <div class=jython> CROS ( V1, V2 )", "in that column. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y) def", "between discrete layers <div class=jython> EI = VWS X (", "GridMath.FUNC_AVERAGE) else: return layerAverage(S,level1,level2, unit) def ldf(S,level1,level2, unit=None): \"\"\" Layer", "SAVG ( S ) = average of all non-missing grid", "... + S (KYD) ) / KNT KYD = number", "/ s ) <div class=jython> QVCL ( THTA, V )", "savg(S): \"\"\" Average over whole grid <div class=jython> SAVG (", "ASIN ( (-DDX (THTA) * COS (PSI) <br> - DDY", "= use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.multiply(S1,S2,WA) def", "S1 + S2 ) / 2 </div> \"\"\" return add(S1,S2)/2", "all non-missing grid point values </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE)", "= newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return vecr(qvecudp,qvecvdp) def rectv(S, D=2):", "quo(S1,S2,WA=0): \"\"\" Divide <div class=jython> QUO (S1, S2) = S1", "layerAverage(V, level1, level2, unit) def vldf(V,level1,level2, unit=None): \"\"\" calculate the", "grid points. The smoothed value is given by a weighted", "S (i-1,j) + S (i,j-1) ) </div> \"\"\" return GridUtil.smooth(S,", "= (L - 2.520)*(-0.59) P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP =", "of all non-missing grid point values in the subset area", "N increases the smoothing. (default N=6) </div> \"\"\" return GridUtil.smooth(S,", "2 vectors <div class=jython> VSUB (V1, V2) = [ u1-u2,", "\"CIRC\", int(D)) def cresv(S, D=2): \"\"\" <div class=jython> Apply a", "grid using a 5-point smoother (see sm5s) \"\"\" return sm5s(V)", "The smoothed value is given by a weighted average of", "S ) = ( S (level1) + S (level2) )", "= ( S (level1) + S (level2) ) / 2.", "return GridUtil.smooth(S, \"SM5S\") def sm9s(S): \"\"\" Smooth a scalar grid", "* S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\"", "(S) = ( S (Z1) + S (Z2) + ...", "DDX (S) * const / CORL ] </div> \"\"\" return", "DST = ddx(uwind) - ddy(vwind) DEF = sqrt(DSH * DSH", "S (i,j+1) + S (i-1,j) + S (i,j-1) ) +", "class=jython> Apply a rectangular aperature smoothing to the grid points.", "class=jython> STRD ( V ) = DDX ( u )", "calculate the vector layer difference <div class=jython> VLDF(V) = [u(level1)", "S ) = .5 * S (i,j) + .125 *", "class=jython> VECR ( S1, S2 ) = [ S1, S2", "= newName(-dot(dvdx(V),grads),\"qvecu\") qvecv = newName(-dot(dvdy(V),grads),\"qvecv\") return vecr(qvecu,qvecv) def qvcl(THTA,V): \"\"\"", "of 1/e for N * delta-x wave. Increasing N increases", "derivative of a vector <div class=jython> DVDY ( V )", "top, bottom, unit)*7.268 uwind = getSliceAtLevel(u, top) vwind = getSliceAtLevel(v,", "GridUtil.smooth(S, \"RECT\", int(D)) def savg(S): \"\"\" Average over whole grid", "\"\"\" return GridMath.subtract(S1,S2,WA) # Scalar quantities def adv(S,V): \"\"\" Horizontal", "\"\"\" Layer Difference <div class=jython> LDF ( S ) =", "( DOT ( DVDX (V), GRAD (THTA) ) ), (", "def wshr(V, Z, top, bottom): \"\"\" Magnitude of the vertical", "Layer Average of a multi layer grid <div class=jython> LAV", "ZSUM (S) = ( S (Z1) + S (Z2) +", "ddy(vwind) DEF = sqrt(DSH * DSH + DST * DST)", "</div> \"\"\" return makeVector(S1,S2) def vlav(V,level1,level2, unit=None): \"\"\" calculate the", "( S ) = [ DDX ( S ), DDY", ") ] </div> \"\"\" return vecr(ddx(S),ddy(S)) def gwfv(V, N=6): \"\"\"", "def cress(S, D=2): \"\"\" <div class=jython> Apply a Cressman smoothing", "\"\"\" return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def un(V): \"\"\" North relative u component", "\"\"\" Horizontal Advection, negative by convention <div class=jython> ADV (", "def vr(V): \"\"\" Grid relative v component \"\"\" return DerivedGridFactory.getVComponent(V)", "class=jython> VECN ( S1, S2 ) = [ S1, S2", "( S ) = ( S (level1) + S (level2)", "( K / m / s ) <div class=jython> QVEC", "ATAN2 ( SHR / STR ) <br> </div> \"\"\" shear", "on the grid diagnostics from the GEneral Meteorological PAcKage (GEMPAK).", "Math functions def atn2(S1,S2,WA=0): \"\"\" Wrapper for atan2 built-in <div", "= ATAN ( S1 / S2 )<br> WA = use", "</div> \"\"\" return vldf(geo(S),level1,level2, unit) def vadd(V1,V2): \"\"\" add the", "of a scalar <div class=jython> GRAD ( S ) =", ")<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return", "Temperature (requires pressure domain) \"\"\" return DerivedGridFactory.createPotentialTemperature(temp) def thte(temp,rh): \"\"\"", "\"\"\" Vector cross product magnitude <div class=jython> CROS ( V1,", "Deformation <div class=jython> STRD ( V ) = DDX (", "two components <div class=jython> VECN ( S1, S2 ) =", "** 2 ) ** .5 </div> \"\"\" return mag(strd(V),shr(V)) def", "North relative direction of a vector <div class=jython> DIRN (", "def yav(S): \"\"\" Average along a grid column <div class=jython>", "<div class=jython> GEO ( S ) = [ - DDY", "= number of non-missing points in row XAV for a", "== 1): return DerivedGridFactory.createVectorMagnitude(a[0]); else: return DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def mixr(temp,rh): \"\"\"", "1/2 ATAN2 ( SHR / STR ) <br> </div> \"\"\"", "S1 - S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div>", "DOT ( V1, GRAD (v2) ) ] </div> \"\"\" return", "a row is stored at every point in that row.", "QVEC ( S, V ) = [ - ( DOT", "LDF ( S ) = S (level1) - S (level2)", "increases the smoothing. (default N=6) </div> \"\"\" return GridUtil.smooth(S, \"GWFS\",", "\"\"\" Average over grid subset <div class=jython> SAVS ( S", "dirr(V): \"\"\" Grid relative direction of a vector \"\"\" return", "diffraction function. D is the radius of influence in grid", "def sm9v(V): \"\"\" Smooth a scalar grid using a 9-point", "<div class=jython> SAVS ( S ) = average of all", "function is the circular aperature diffraction function. D is the", "return makeVector(S1,S2) def vlav(V,level1,level2, unit=None): \"\"\" calculate the vector layer", ".5 </div> \"\"\" return mag(strd(V),shr(V)) def div(V): \"\"\" Horizontal Divergence", "\"\"\" Layer Average of a multi layer grid <div class=jython>", "grad(S) return div(grads) def lav(S,level1=None,level2=None, unit=None): \"\"\" Layer Average of", "<p> Where: BETA = ASIN ( (-DDX (THTA) * COS", "LP = 7.268DUDZ + 0.718DTDN + 0.318DUDN - 2.52 </div>", "S (X2) + ... + S (KXD) ) / KNT", "* v1 </div> \"\"\" return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def ddx(S): \"\"\" Take", "North relative v component \"\"\" return vr(DerivedGridFactory.createTrueFlowVector(V)) def vor(V): \"\"\"", "</div> \"\"\" return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def ddx(S): \"\"\" Take the derivative", "), DOT ( V1, GRAD (v2) ) ] </div> \"\"\"", "- ( DOT ( DVDY (V), GRAD (S) ) )", "1): return DerivedGridFactory.createVectorMagnitude(a[0]); else: return DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def mixr(temp,rh): \"\"\" Mixing", "\"\"\" return DerivedGridFactory.createPotentialVorticity(S,V) def rects(S, D=2): \"\"\" <div class=jython> Apply", "\"\"\" dtdp = GridMath.partial(THTA,2) gradt = grad(THTA) qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\")", "(level2), v (GEO(S)) (level1) - v (GEO(S)) (level2) ] </div>", "grid point values </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def savs(S):", "S (i,j+1) + S (i-1,j) + S (i,j-1) ) </div>", "Sum along a grid column <div class=jython> YSUM (S) =", "( S (Y1) + S (Y2) + ... + S", "the product of the rectangular aperature diffraction function in the", "Cressman smoothing to the grid points. The smoothed value is", "<div class=jython> DEF ( V ) = ( STRD (V)", "VADD (V1, V2) = [ u1+u2, v1+v2 ] </div> \"\"\"", "= (ddx(uwind) + ddy(vwind))* (-1.0) # DSH = ddx(vwind) +", "DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def mixr(temp,rh): \"\"\" Mixing Ratio from Temperature, RH (requires", "a rectangular aperature smoothing to the grid points. The weighting", "level2, unit) def vldf(V,level1,level2, unit=None): \"\"\" calculate the vector layer", "\"\"\" if level1 == None: return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE) else: return", "v * DDY (S) ) </div> \"\"\" return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def", "(v) ] </div> \"\"\" return vecr(ddx(ur(V)), ddx(vr(V))) def dvdy(V): \"\"\"", "scalar grid using a 9-point smoother <div class=jython> SM9S (", "COS (PSI) <br> - DDY (THTA) * SIN (PSI))/ <br>", "def atn2(S1,S2,WA=0): \"\"\" Wrapper for atan2 built-in <div class=jython> ATN2", "direction of a vector \"\"\" return DerivedGridFactory.createVectorDirection(V) def dot(V1,V2): \"\"\"", "* DSH + DST * DST) EI = mul(noUnit(VWS), add(noUnit(DEF),", "module. These functions are based on the grid diagnostics from", "at all points <div class=jython> ZSUM (S) = ( S", "domain) \"\"\" return DerivedGridFactory.createPotentialTemperature(temp) def thte(temp,rh): \"\"\" Equivalent Potential Temperature", "of 2 scalars <div class=jython> AVG (S1, S2) = (", "] </div> \"\"\" return makeTrueVector(S1,S2) def vecr(S1,S2): \"\"\" Make a", "</div> \"\"\" return gwfs(V, N) def inad(V1,V2): \"\"\" Inertial advective", "a grid <div class=jython> CORL = TWO_OMEGA*sin(latr) </div> \"\"\" return", "of a vector <div class=jython> DVDY ( V ) =", "+ ... + S (KXD) ) / KNT KXD =", "CORL, DDX (S) * const / CORL ] </div> \"\"\"", "V1, GRAD (v2) ) ] </div> \"\"\" return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def", "GridMath.divide(S1,S2,WA) def sub(S1,S2,WA=0): \"\"\" Subtract <div class=jython> SUB (S1, S2)", "return add(mul(S,(div(V))) , dot(V,grad(S))) def shr(V): \"\"\" Shear Deformation <div", "GridMath.FUNC_AVERAGE) def savs(S): \"\"\" Average over grid subset <div class=jython>", "class=jython> GRAD ( S ) = [ DDX ( S", "S (level2) ) / 2. </div> \"\"\" if level1 ==", "KNT KXD = number of points in row KNT =", "return dirr(DerivedGridFactory.createTrueFlowVector(V)) def dirr(V): \"\"\" Grid relative direction of a", "operator <div class=jython> LAP ( S ) = DIV (", "windShear(u, v, z, top, bottom, unit)*100.0 # uwind = getSliceAtLevel(u,", "layers <div class=jython> EI = VWS X ( DEF +", "</div> \"\"\" return sub(obs,geo) def circv(S, D=2): \"\"\" <div class=jython>", "* BETA) - DIV ) <p> Where: BETA = ASIN", "points in a grid \"\"\" return DerivedGridFactory.createLatitudeGrid(S) def lap(S): \"\"\"", "1/2 * MAG ( GRAD (THTA) ) * ( DEF", "</div> \"\"\" dtdp = GridMath.partial(THTA,2) gradt = grad(THTA) qvecudp =", "<div class=jython> XSUM (S) = ( S (X1) + S", "KYD = number of points in column KNT = number", "\"\"\" Sum along a grid row <div class=jython> XSUM (S)", "\"\"\" return sm9s(V) def thrm(S, level1, level2, unit=None): \"\"\" Thermal", "of non-missing points in column </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE,", "def lav(S,level1=None,level2=None, unit=None): \"\"\" Layer Average of a multi layer", "circs(S, D=2): \"\"\" <div class=jython> Apply a circular aperature smoothing", "S2 )<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\"", "discrete layers <div class=jython> EI = VWS X ( DEF", "scalar operands are named S<sub>n</sub> and vector operands are named", "Equivalent Potential Temperature from Temperature and Relative humidity (requires pressure", "levels KNT = number of non-missing points in column </div>", "<div class=jython> JCBN ( S1, S2 ) = DDX (S1)", "class=jython> ZSUM (S) = ( S (Z1) + S (Z2)", "a vector <div class=jython> DVDY ( V ) = [", "KNT KYD = number of points in column KNT =", "</div> \"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def cros(V1,V2): \"\"\" Vector", "S2) = ATAN ( S1 / S2 )<br> WA =", "def shr(V): \"\"\" Shear Deformation <div class=jython> SHR ( V", "gradt = grad(THTA) qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return", "v (OBS) - v (GEO(S)) ] </div> \"\"\" return sub(obs,geo)", "return GridMath.divide(S1,S2,WA) def sub(S1,S2,WA=0): \"\"\" Subtract <div class=jython> SUB (S1,", "Apply a rectangular aperature smoothing to the grid points. The", "return DerivedGridFactory.createMixingRatio(temp,rh) def relh(temp,mixr): \"\"\" Create Relative Humidity from Temperature,", "\"\"\" return dirr(DerivedGridFactory.createTrueFlowVector(V)) def dirr(V): \"\"\" Grid relative direction of", "of surrounding grid points. D is the radius of influence", "at every point </div> \"\"\" return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM) def wshr(V,", "at all points <div class=jython> ZAV (S) = ( S", "vadd(V1,V2): \"\"\" add the components of 2 vectors <div class=jython>", "DIV ) <p> Where: BETA = ASIN ( (-DDX (THTA)", "\"\"\" Smooth a scalar grid using a 9-point smoother (see", "S ) = .25 * S (i,j) + .125 *", ") / KNT KYD = number of points in column", "/ LDF (Z) </div> \"\"\" dv = mag(vldf(V,top,bottom)) dz =", "the wind <div class=jython> FRNT ( THTA, V ) =", "class=jython> THRM ( S ) = [ u (GEO(S)) (level1)", "KNT = number of non-missing points in row XAV for", "along a grid row <div class=jython> XSUM (S) = (", "vor(V): \"\"\" Relative Vorticity <div class=jython> VOR ( V )", "yav(S): \"\"\" Average along a grid column <div class=jython> YAV", "GridUtil.smooth(S, \"CIRC\", int(D)) def cresv(S, D=2): \"\"\" <div class=jython> Apply", "mag(*a): \"\"\" Magnitude of a vector \"\"\" if (len(a) ==", "Temperature from Temperature (requires pressure domain) \"\"\" return DerivedGridFactory.createPotentialTemperature(temp) def", "class=jython> EI = VWS X ( DEF + DIV) </div>", "... + S (KZD) ) / KNT KZD = number", "by convention <div class=jython> ADV ( S, V ) =", "GridMath.ddx(S); def ddy(S): \"\"\" Take the derivative with respect to", ",top, unit) return LP def EllrodIndex(u, v, z, top, bottom,", "V ) = MAG [ VLDF (V) ] / LDF", "= asin(a/mgradt) frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V)) return frnto def geo(z): \"\"\"", "Potetial Vorticity (usually from theta and wind) \"\"\" return DerivedGridFactory.createPotentialVorticity(S,V)", "\"\"\" Average across the levels of a grid at all", "unit) return LP def EllrodIndex(u, v, z, top, bottom, unit):", "row <div class=jython> XSUM (S) = ( S (X1) +", "\"\"\" calculate the vector layer difference <div class=jython> VLDF(V) =", ") = [ S1, S2 ] </div> \"\"\" return makeVector(S1,S2)", "return quo(V1,V2) def vsub(V1,V2): \"\"\" subtract the components of 2", "for a row is stored at every point in that", "is stored at every point in that column. </div> \"\"\"", "return GridMath.subtract(S1,S2,WA) # Scalar quantities def adv(S,V): \"\"\" Horizontal Advection,", "can be any thermal paramenter, usually THTA. </div> \"\"\" grads", "Absolute Vorticity <div class=jython> AVOR ( V ) = VOR", "CORL(V) </div> \"\"\" relv = vor(V) return add(relv,corl(relv)) def circs(S,", "the subset area </div> \"\"\" return savg(S) def sdiv(S,V): \"\"\"", "vecr(ddx(ur(V)), ddx(vr(V))) def dvdy(V): \"\"\" Partial x derivative of a", "(KYD) ) / KNT KYD = number of points in", "return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM) def wshr(V, Z, top, bottom): \"\"\" Magnitude", "\"\"\" Gravity constant \"\"\" return DerivedGridFactory.GRAVITY; # Math functions def", "class=jython> DIRN ( V ) = DIRR ( un(v), vn(v)", "= number of points in row KNT = number of", "of a grid at all points <div class=jython> ZSUM (S)", ") ) ] </div> \"\"\" dtdp = GridMath.partial(THTA,2) gradt =", ") = VOR ( V ) + CORL(V) </div> \"\"\"", "sm9s(S): \"\"\" Smooth a scalar grid using a 9-point smoother", "<P> In the following operators, scalar operands are named S<sub>n</sub>", "\"\"\" shear = shr(V) strch = strd(V) psi = .5*atn2(shear,strch)", "x and y directions. D is the radius of influence", "VWS X ( DEF + DIV) </div> \"\"\" VWS =", "class=jython> MUL (S1, S2) = S1 * S2<br> WA =", "\"\"\" Create Relative Humidity from Temperature, mixing ratio (requires pressure", "Horizontal smoothing using normally distributed weights with theoretical response of", "\"\"\" Laplacian operator <div class=jython> LAP ( S ) =", "V ) = [ DDY (u), DDY (v) ] </div>", "level ( K / m / s ) <div class=jython>", "and vector operands are named V<sub>n</sub>. Lowercase u and v", "+ S (KZD) ) KZD = number of levels ZSUM", "* [ ( DOT ( DVDX (V), GRAD (THTA) )", "newUnit(getSliceAtLevel(t, top), \"temperature\", \"celsius\") HT = sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718 HU", "v (GEO(S)) (level2) ] </div> \"\"\" return vldf(geo(S),level1,level2, unit) def", "shr(V): \"\"\" Shear Deformation <div class=jython> SHR ( V )", "N=6) </div> \"\"\" return gwfs(V, N) def inad(V1,V2): \"\"\" Inertial", "scalar grid using a 9-point smoother (see sm9s) \"\"\" return", "<div class=jython> DOT ( V1, V2 ) = u1 *", "in column </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def zsum(S): \"\"\"", "MUL (S1, S2) = S1 * S2<br> WA = use", "... + S (KZD) ) KZD = number of levels", "asin(a/mgradt) frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V)) return frnto def geo(z): \"\"\" geostrophic", "sdiv(S,V): \"\"\" Horizontal Flux Divergence <div class=jython> SDIV ( S,", "(PSI) <br> - DDY (THTA) * SIN (PSI))/ <br> MAG", "\"\"\" Smooth a scalar grid using a 5-point smoother (see", "(default N=6) </div> \"\"\" return gwfs(V, N) def inad(V1,V2): \"\"\"", "- S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\"", "u2 * v1 </div> \"\"\" return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def ddx(S): \"\"\"", "every point in that column. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM,", "<div class=jython> SUB (S1, S2) = S1 - S2<br> WA", "function from theta and the wind <div class=jython> FRNT (", "[u(level1) - u(level2), v(level1) - v(level2)] </div> \"\"\" return layerDiff(V,level1,level2,", ") = [ DDY (u), DDY (v) ] </div> \"\"\"", "Create Relative Humidity from Temperature, mixing ratio (requires pressure domain)", "Divide <div class=jython> QUO (S1, S2) = S1 / S2<br>", "rects(S, D=2): \"\"\" <div class=jython> Apply a rectangular aperature smoothing", "None: return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE) else: return layerAverage(S,level1,level2, unit) def ldf(S,level1,level2,", "= [ u (GEO(S)) (level1) - u (GEO(S)) (level2), v", "\"\"\" return vecr(ddx(ur(V)), ddx(vr(V))) def dvdy(V): \"\"\" Partial x derivative", "some are named slightly different from GEMPAK functions to avoid", "to the grid points. The weighting function is the circular", "( DEF * COS (2 * BETA) - DIV )", "the Grid Diagnostics module. These functions are based on the", "subset <div class=jython> SAVS ( S ) = average of", "+ S (X2) + ... + S (KXD) ) KXD", "Sum along a grid row <div class=jython> XSUM (S) =", "class=jython> QVCL ( THTA, V ) = ( 1/( D", "\"\"\" Grid relative u component \"\"\" return DerivedGridFactory.getUComponent(V) def vn(V):", "S1, S2 ) = DDX (S1) * DDY (S2) -", "(Z1) + S (Z2) + ... + S (KZD) )", "... + S (KXD) ) KXD = number of points", "\"\"\" return vecr(ddy(ur(V)), ddy(vr(V))) def frnt(S,V): \"\"\" Frontogenesis function from", "whole grid <div class=jython> SAVG ( S ) = average", "These functions are based on the grid diagnostics from the", "\"\"\" Divide the components of 2 vectors <div class=jython> VQUO", "</div> \"\"\" return sub(ddx(vr(V)),ddy(ur(V))) def vr(V): \"\"\" Grid relative v", "- v (GEO(S)) ] </div> \"\"\" return sub(obs,geo) def circv(S,", "vector. \"\"\" def GRAVITY(): \"\"\" Gravity constant \"\"\" return DerivedGridFactory.GRAVITY;", "S1, S2 ) = [ S1, S2 ] </div> \"\"\"", "wind shear in a layer <div class=jython> WSHR ( V", "* delta-x wave. Increasing N increases the smoothing. (default N=6)", "VQUO (V1, V2) = [ u1/u2, v1/v2 ] </div> \"\"\"", "DEF = sqrt(DSH * DSH + DST * DST) EI", "gwfs(V, N) def inad(V1,V2): \"\"\" Inertial advective wind <div class=jython>", "= [ DDX ( S ), DDY ( S )", "2.520)*(-0.59) P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP = setLevel(P ,top, unit)", "are based on the grid diagnostics from the GEneral Meteorological", "2 ) ** .5 </div> \"\"\" return mag(strd(V),shr(V)) def div(V):", "DerivedGridFactory.createPotentialTemperature(temp) def thte(temp,rh): \"\"\" Equivalent Potential Temperature from Temperature and", "return sub(V1,V2) def LPIndex(u, v, z, t, top, bottom, unit):", "(S1, S2) = S1 * S2<br> WA = use WEIGHTED_AVERAGE", "( THTA, V ) = 1/2 * MAG ( GRAD", "weighted average of surrounding grid points. D is the radius", "(-DDX (THTA) * COS (PSI) <br> - DDY (THTA) *", ") = [ - ( DOT ( DVDX (V), GRAD", ") = DIRR ( un(v), vn(v) ) </div> \"\"\" return", "V ) = ( STRD (V) ** 2 + SHR", "ddy(S) cosd = cos(psi) sind = sin(psi) gradt = grad(S)", "wind shear between discrete layers <div class=jython> EI = VWS", "aperature diffraction function. D is the radius of influence in", "return GridUtil.smooth(S, \"RECT\", int(D)) def savg(S): \"\"\" Average over whole", "- u2 * v1 </div> \"\"\" return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def ddx(S):", "wind) \"\"\" return DerivedGridFactory.createPotentialVorticity(S,V) def rects(S, D=2): \"\"\" <div class=jython>", "the smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CIRC\", int(D))", "(S1, S2) = ( S1 + S2 ) / 2", "MAG ( GRAD (THTA) ) * ( DEF * COS", "u (GEO(S)) (level2), v (GEO(S)) (level1) - v (GEO(S)) (level2)", "( S, V ) = [ - ( DOT (", "S (i-1,j-1) ) </div> \"\"\" return GridUtil.smooth(S, \"SM9S\") def strd(V):", "return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X) def yav(S): \"\"\" Average along a", "\"SM5S\") def sm9s(S): \"\"\" Smooth a scalar grid using a", "from height <div class=jython> GEO ( S ) = [", "pvor(S,V): \"\"\" Potetial Vorticity (usually from theta and wind) \"\"\"", "DDX ( u ) + DDY ( v ) </div>", "/ STR ) <br> </div> \"\"\" shear = shr(V) strch", "all points in a grid \"\"\" return DerivedGridFactory.createLatitudeGrid(S) def lap(S):", "GridMath.FUNC_SUM, GridMath.AXIS_Y) def zav(S): \"\"\" Average across the levels of", "named V<sub>n</sub>. Lowercase u and v refer to the grid", "dirn(V): \"\"\" North relative direction of a vector <div class=jython>", "\"\"\" Smooth a scalar grid using a 5-point smoother <div", "GridMath.AXIS_Y) def ysum(S): \"\"\" Sum along a grid column <div", "of levels ZSUM for a vertical column is stored at", "xsum(S): \"\"\" Sum along a grid row <div class=jython> XSUM", "+ S (i,j+1) + S (i-1,j) + S (i,j-1) )", "= average of all non-missing grid point values </div> \"\"\"", "u ) + DDY ( v ) </div> \"\"\" return", "/ CORL ] </div> \"\"\" return DerivedGridFactory.createGeostrophicWindVector(z) def grad(S): \"\"\"", "u1/u2, v1/v2 ] </div> \"\"\" return quo(V1,V2) def vsub(V1,V2): \"\"\"", ".5 * S (i,j) + .125 * ( S (i+1,j)", "Temperature, RH (requires pressure domain) \"\"\" return DerivedGridFactory.createMixingRatio(temp,rh) def relh(temp,mixr):", "\"\"\" Latitudue all points in a grid \"\"\" return DerivedGridFactory.createLatitudeGrid(S)", ") ) <br> PSI = 1/2 ATAN2 ( SHR /", "(level1) - v (GEO(S)) (level2) ] </div> \"\"\" return vldf(geo(S),level1,level2,", "S (i-1,j) + S (i,j-1) ) + .0625 * (", "DVDY (V), GRAD (S) ) ) ] where S can", "(V) ** 2 ) ** .5 </div> \"\"\" return mag(strd(V),shr(V))", "\"\"\" Coriolis Parameter for all points in a grid <div", "ur(DerivedGridFactory.createTrueFlowVector(V)) def ur(V): \"\"\" Grid relative u component \"\"\" return", "sind = sin(psi) gradt = grad(S) mgradt = mag(gradt) a", "... + S (KXD) ) / KNT KXD = number", "return add(ddx(vr(V)),ddy(ur(V))) def sm5s(S): \"\"\" Smooth a scalar grid using", "number of non-missing points in column </div> \"\"\" return GridMath.applyFunctionToLevels(S,", "- DDY (THTA) * SIN (PSI))/ <br> MAG ( GRAD", "S can be any thermal paramenter, usually THTA. </div> \"\"\"", "of points in row YSUM for a column is stored", "(X2) + ... + S (KXD) ) KXD = number", ") </div> \"\"\" return add(ddx(ur(V)),ddy(vr(V))) def dirn(V): \"\"\" North relative", "\"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def savs(S): \"\"\" Average over grid", "def thrm(S, level1, level2, unit=None): \"\"\" Thermal wind <div class=jython>", "mag(gradt) a = -cosd*dxt-sind*dyt beta = asin(a/mgradt) frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V))", "] </div> \"\"\" return vecr(ddx(ur(V)), ddx(vr(V))) def dvdy(V): \"\"\" Partial", "aperature smoothing to the grid points. The weighting function is", "</div> \"\"\" dv = mag(vldf(V,top,bottom)) dz = ldf(Z,top,bottom) return quo(dv,dz)", "/ CORL, DDX (S) * const / CORL ] </div>", "V ) = DIRR ( un(v), vn(v) ) </div> \"\"\"", "def ysum(S): \"\"\" Sum along a grid column <div class=jython>", "v, z, top, bottom, unit)*100.0 # uwind = getSliceAtLevel(u, top)", "circular aperature diffraction function. D is the radius of influence", "(X2) + ... + S (KXD) ) / KNT KXD", "V ) = DDX ( u ) - DDY (", "Laplacian operator <div class=jython> LAP ( S ) = DIV", ") = DDX (S1) * DDY (S2) - DDY (S1)", "sm5s(V) def sm9v(V): \"\"\" Smooth a scalar grid using a", "+ S (Z2) + ... + S (KZD) ) KZD", "qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return vecr(qvecudp,qvecvdp) def rectv(S,", "un(V): \"\"\" North relative u component \"\"\" return ur(DerivedGridFactory.createTrueFlowVector(V)) def", "# Vector output def age(obs,geo): \"\"\" Ageostrophic wind <div class=jython>", "VECN ( S1, S2 ) = [ S1, S2 ]", "add(S1,S2,WA=0): \"\"\" Addition <div class=jython> ADD (S1, S2) = S1", "Average of a multi layer grid <div class=jython> LAV (", "a 9-point smoother <div class=jython> SM9S ( S ) =", "(u), DDX (v) ] </div> \"\"\" return vecr(ddx(ur(V)), ddx(vr(V))) def", "Grid relative v component \"\"\" return DerivedGridFactory.getVComponent(V) def xav(S): \"\"\"", "smoother <div class=jython> SM5S ( S ) = .5 *", "( DOT ( DVDY (V), GRAD (THTA) ) ) ]", "ZSUM for a vertical column is stored at every point", "STR ) <br> </div> \"\"\" shear = shr(V) strch =", "(i-1,j+1) + S (i-1,j-1) ) </div> \"\"\" return GridUtil.smooth(S, \"SM9S\")", "</div> \"\"\" return GridUtil.smooth(S, \"SM5S\") def sm9s(S): \"\"\" Smooth a", "The weighting function is the product of the rectangular aperature", "DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def un(V): \"\"\" North relative u component \"\"\" return", "+ v1 * v2 </div> \"\"\" product = mul(V1,V2) return", "\"\"\" return add(S1,S2)/2 def avor(V): \"\"\" Absolute Vorticity <div class=jython>", "= ( S1 + S2 ) / 2 </div> \"\"\"", "zav(S): \"\"\" Average across the levels of a grid at", "frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V)) return frnto def geo(z): \"\"\" geostrophic wind", "vecr(S1,S2): \"\"\" Make a vector from two components <div class=jython>", "<div class=jython> SHR ( V ) = DDX ( v", "( S1, S2 ) = [ S1, S2 ] </div>", "* COS (PSI) <br> - DDY (THTA) * SIN (PSI))/", "def div(V): \"\"\" Horizontal Divergence <div class=jython> DIV ( V", "def frnt(S,V): \"\"\" Frontogenesis function from theta and the wind", "derivative with respect to the domain's Y coordinate \"\"\" return", "the grid points. The weighting function is the circular aperature", "def thte(temp,rh): \"\"\" Equivalent Potential Temperature from Temperature and Relative", "ysum(S): \"\"\" Sum along a grid column <div class=jython> YSUM", "] </div> \"\"\" return DerivedGridFactory.createGeostrophicWindVector(z) def grad(S): \"\"\" Gradient of", "\"\"\" return GridUtil.smooth(S, \"SM5S\") def sm9s(S): \"\"\" Smooth a scalar", "\"\"\" return DerivedGridFactory.createPotentialTemperature(temp) def thte(temp,rh): \"\"\" Equivalent Potential Temperature from", "a grid at all points <div class=jython> ZAV (S) =", ") = average of all non-missing grid point values </div>", "= ( S (X1) + S (X2) + ... +", "components of 2 vectors <div class=jython> VADD (V1, V2) =", "+ 0.718DTDN + 0.318DUDN - 2.52 </div> \"\"\" Z =", "\"\"\" Take the derivative with respect to the domain's X", "S (X2) + ... + S (KXD) ) KXD =", "ddy(vr(V))) def frnt(S,V): \"\"\" Frontogenesis function from theta and the", "= newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return vecr(qvecudp,qvecvdp) def rectv(S, D=2): \"\"\" <div class=jython>", ") = MAG [ VLDF (V) ] / LDF (Z)", "rectangular aperature smoothing to the grid points. The weighting function", "] </div> \"\"\" return vecr(ddx(S),ddy(S)) def gwfv(V, N=6): \"\"\" <div", "\"\"\" return mag(strd(V),shr(V)) def div(V): \"\"\" Horizontal Divergence <div class=jython>", "functions are based on the grid diagnostics from the GEneral", "advective wind <div class=jython> INAD ( V1, V2 ) =", "Take the derivative with respect to the domain's X coordinate", "( S ) = [ u (GEO(S)) (level1) - u", "return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def savs(S): \"\"\" Average over grid subset", "def circs(S, D=2): \"\"\" <div class=jython> Apply a circular aperature", "def ldf(S,level1,level2, unit=None): \"\"\" Layer Difference <div class=jython> LDF (", "top) temp = newUnit(getSliceAtLevel(t, top), \"temperature\", \"celsius\") HT = sqrt(ddx(temp)*ddx(temp)", "row YSUM for a column is stored at every point", "\"\"\" North relative direction of a vector <div class=jython> DIRN", "= .5*mgradt*(defr(V)*cos(2*beta)-div(V)) return frnto def geo(z): \"\"\" geostrophic wind from", "\"\"\" return DerivedGridFactory.createRelativeHumidity(temp,mixr) def pvor(S,V): \"\"\" Potetial Vorticity (usually from", "increases the smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"RECT\",", "Vorticity <div class=jython> AVOR ( V ) = VOR (", "vector \"\"\" if (len(a) == 1): return DerivedGridFactory.createVectorMagnitude(a[0]); else: return", "GridUtil.smooth(S, \"GWFS\", int(N)) def jcbn(S1,S2): \"\"\" Jacobian Determinant <div class=jython>", "class=jython> LP = 7.268DUDZ + 0.718DTDN + 0.318DUDN - 2.52", "= ddx(S) dyt = ddy(S) cosd = cos(psi) sind =", "for the Grid Diagnostics module. These functions are based on", "class=jython> XSUM (S) = ( S (X1) + S (X2)", "= ( S (Z1) + S (Z2) + ... +", "v1-v2 ] </div> \"\"\" return sub(V1,V2) def LPIndex(u, v, z,", "return add(relv,corl(relv)) def circs(S, D=2): \"\"\" <div class=jython> Apply a", "named slightly different from GEMPAK functions to avoid conflicts with", "points in column </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def zsum(S):", "return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def latr(S): \"\"\" Latitudue all points in a", "return DerivedGridFactory.getUComponent(V) def vn(V): \"\"\" North relative v component \"\"\"", "S2 ] </div> \"\"\" return makeVector(S1,S2) def vlav(V,level1,level2, unit=None): \"\"\"", "[ u (GEO(S)) (level1) - u (GEO(S)) (level2), v (GEO(S))", "return LP def EllrodIndex(u, v, z, top, bottom, unit): \"\"\"", "class=jython> Horizontal smoothing using normally distributed weights with theoretical response", "GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y) def ysum(S): \"\"\" Sum along a grid", "\"\"\" return sub(V1,V2) def LPIndex(u, v, z, t, top, bottom,", "YSUM (S) = ( S (Y1) + S (Y2) +", "GRAD (THTA) ) ) ] </div> \"\"\" dtdp = GridMath.partial(THTA,2)", "= MAG [ VLDF (V) ] / LDF (Z) </div>", "geo(z): \"\"\" geostrophic wind from height <div class=jython> GEO (", "the derivative with respect to the domain's X coordinate \"\"\"", "(v) ] </div> \"\"\" return vecr(ddy(ur(V)), ddy(vr(V))) def frnt(S,V): \"\"\"", "(THTA) ) ) <br> PSI = 1/2 ATAN2 ( SHR", "grid <div class=jython> SAVG ( S ) = average of", "GridMath.FUNC_AVERAGE, GridMath.AXIS_X) def xsum(S): \"\"\" Sum along a grid row", "column </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y) def ysum(S): \"\"\"", "] / LDF (Z) </div> \"\"\" dv = mag(vldf(V,top,bottom)) dz", "wind <div class=jython> INAD ( V1, V2 ) = [", "using a 5-point smoother (see sm5s) \"\"\" return sm5s(V) def", "(Z2) + ... + S (KZD) ) KZD = number", "quo(V1,V2) def vsub(V1,V2): \"\"\" subtract the components of 2 vectors", "<div class=jython> VSUB (V1, V2) = [ u1-u2, v1-v2 ]", "humidity (requires pressure domain) \"\"\" return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def un(V): \"\"\"", ") </div> \"\"\" return sub(ddx(ur(V)),ddy(vr(V))) def thta(temp): \"\"\" Potential Temperature", "+ .0625 * ( S (i+1,j+1) + S (i+1,j-1) +", "DOT ( DVDX (V), GRAD (THTA) ) ), ( DOT", "= newUnit(getSliceAtLevel(t, top), \"temperature\", \"celsius\") HT = sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718", "(THTA) * COS (PSI) <br> - DDY (THTA) * SIN", "AVG (S1, S2) = ( S1 + S2 ) /", "</div> \"\"\" Z = windShear(u, v, z, top, bottom, unit)*7.268", "value is given by a weighted average of surrounding grid", "N=6): \"\"\" <div class=jython> Horizontal smoothing using normally distributed weights", "\"\"\" return layerDiff(V,level1,level2, unit) def vmul(V1,V2): \"\"\" Multiply the components", "\"\"\" Horizontal Divergence <div class=jython> DIV ( V ) =", "row KNT = number of non-missing points in row XAV", "class=jython> SAVS ( S ) = average of all non-missing", "GridMath.add(S1,S2,WA) def mul(S1,S2,WA=0): \"\"\" Multiply <div class=jython> MUL (S1, S2)", ") = DDX ( u ) - DDY ( v", "= DDX ( u ) - DDY ( v )", "relative v component \"\"\" return vr(DerivedGridFactory.createTrueFlowVector(V)) def vor(V): \"\"\" Relative", "vector <div class=jython> DVDY ( V ) = [ DDY", "D=2) </div> \"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def cresv(S, D=2):", ") + DDY ( v ) </div> \"\"\" return add(ddx(ur(V)),ddy(vr(V)))", "domain) \"\"\" return DerivedGridFactory.createMixingRatio(temp,rh) def relh(temp,mixr): \"\"\" Create Relative Humidity", "(S2) </div> \"\"\" return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def latr(S): \"\"\" Latitudue all", "stored at every point </div> \"\"\" return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM) def", "K / m / s ) <div class=jython> QVEC (", "two components <div class=jython> VECR ( S1, S2 ) =", "to the grid relative components of a vector. \"\"\" def", "= windShear(u, v, z, top, bottom, unit)*100.0 # uwind =", "\"\"\" Stretching Deformation <div class=jython> STRD ( V ) =", "N=6) </div> \"\"\" return GridUtil.smooth(S, \"GWFS\", int(N)) def jcbn(S1,S2): \"\"\"", "GRAD ( S ) = [ DDX ( S ),", "S (i+1,j+1) + S (i+1,j-1) + S (i-1,j+1) + S", "return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def ddx(S): \"\"\" Take the derivative with respect", "def cresv(S, D=2): \"\"\" <div class=jython> Apply a Cressman smoothing", "\"celsius\") HT = sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718 HU = (ddx(vwind) +", "to the grid points. The weighting function is the product", "DOT ( DVDY (V), GRAD (S) ) ) ] where", "savs(S): \"\"\" Average over grid subset <div class=jython> SAVS (", "grid points. D is the radius of influence in grid", "respect to the domain's X coordinate \"\"\" return GridMath.ddx(S); def", "the grid relative components of a vector. \"\"\" def GRAVITY():", "GridMath.FUNC_SUM) def wshr(V, Z, top, bottom): \"\"\" Magnitude of the", "following operators, scalar operands are named S<sub>n</sub> and vector operands", "\"CIRC\", int(D)) def corl(S): \"\"\" Coriolis Parameter for all points", "return GridUtil.smooth(S, \"CIRC\", int(D)) def corl(S): \"\"\" Coriolis Parameter for", "increments, increasing D increases the smoothing. (default D=2) </div> \"\"\"", "component \"\"\" return DerivedGridFactory.getUComponent(V) def vn(V): \"\"\" North relative v", "vquo(V1,V2): \"\"\" Divide the components of 2 vectors <div class=jython>", "\"\"\" Thermal wind <div class=jython> THRM ( S ) =", "Parameter for all points in a grid <div class=jython> CORL", "Flux Divergence <div class=jython> SDIV ( S, V ) =", "domain) \"\"\" return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def un(V): \"\"\" North relative u", "ddx(S) dyt = ddy(S) cosd = cos(psi) sind = sin(psi)", "- 2.52 </div> \"\"\" Z = windShear(u, v, z, top,", "class=jython> AVOR ( V ) = VOR ( V )", "unit) def vadd(V1,V2): \"\"\" add the components of 2 vectors", "return vecr(ddx(S),ddy(S)) def gwfv(V, N=6): \"\"\" <div class=jython> Horizontal smoothing", "def defr(V): \"\"\" Total deformation <div class=jython> DEF ( V", "return layerDiff(V,level1,level2, unit) def vmul(V1,V2): \"\"\" Multiply the components of", "GridMath.AXIS_X) def xsum(S): \"\"\" Sum along a grid row <div", "\"GWFS\", int(N)) def jcbn(S1,S2): \"\"\" Jacobian Determinant <div class=jython> JCBN", "v(level2))/2] </div> \"\"\" return layerAverage(V, level1, level2, unit) def vldf(V,level1,level2,", "u component \"\"\" return DerivedGridFactory.getUComponent(V) def vn(V): \"\"\" North relative", "of the rectangular aperature diffraction function in the x and", "components <div class=jython> VECR ( S1, S2 ) = [", "V2) = [ u1+u2, v1+v2 ] </div> \"\"\" return add(V1,V2)", "a multi layer grid <div class=jython> LAV ( S )", "Latitudue all points in a grid \"\"\" return DerivedGridFactory.createLatitudeGrid(S) def", "( V ) = DIRR ( un(v), vn(v) ) </div>", "/ 2 </div> \"\"\" return add(S1,S2)/2 def avor(V): \"\"\" Absolute", "grid <div class=jython> CORL = TWO_OMEGA*sin(latr) </div> \"\"\" return DerivedGridFactory.createCoriolisGrid(S)", "of points in row XSUM for a row is stored", "DDY (S) * const / CORL, DDX (S) * const", "v2 - u2 * v1 </div> \"\"\" return sub(mul(ur(V1),vr(V2)),mul(ur(V2),vr(V1))) def", "v1*v2 ] </div> \"\"\" return mul(V1,V2) def vquo(V1,V2): \"\"\" Divide", "</div> \"\"\" if level1 == None: return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE) else:", "column is stored at every point in that column. </div>", "average of all non-missing grid point values in the subset", "Thermal wind <div class=jython> THRM ( S ) = [", "2.52 </div> \"\"\" Z = windShear(u, v, z, top, bottom,", "top, bottom, unit): \"\"\" calculate the wind shear between discrete", "-add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def avg(S1,S2): \"\"\" Average of 2 scalars <div class=jython>", "NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.atan2(S1,S2,WA) def add(S1,S2,WA=0): \"\"\" Addition <div", "= ldf(Z,top,bottom) return quo(dv,dz) # Vector output def age(obs,geo): \"\"\"", "DDX ( u ) - DDY ( v ) </div>", "vector layer difference <div class=jython> VLDF(V) = [u(level1) - u(level2),", "product <div class=jython> DOT ( V1, V2 ) = u1", "of a vector <div class=jython> DVDX ( V ) =", "SUB (S1, S2) = S1 - S2<br> WA = use", "S ) ) </div> \"\"\" return add(mul(S,(div(V))) , dot(V,grad(S))) def", "(KZD) ) / KNT KZD = number of levels KNT", "* ( DEF * COS (2 * BETA) - DIV", "* SIN (PSI))/ <br> MAG ( GRAD (THTA) ) )", "def qvcl(THTA,V): \"\"\" Q-vector ( K / m / s", "- S (level2) </div> \"\"\" return layerDiff(S,level1,level2, unit); def mag(*a):", "row is stored at every point in that row. </div>", "a column is stored at every point in that column.", "def avg(S1,S2): \"\"\" Average of 2 scalars <div class=jython> AVG", ") = u1 * v2 - u2 * v1 </div>", "GridMath.partial(THTA,2) gradt = grad(THTA) qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\")", "V1, V2 ) = [ DOT ( V1, GRAD (u2)", "WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.divide(S1,S2,WA)", "return DerivedGridFactory.createRelativeHumidity(temp,mixr) def pvor(S,V): \"\"\" Potetial Vorticity (usually from theta", "= number of points in column KNT = number of", "V ) + DOT ( V, GRAD ( S )", "THTA, V ) = ( 1/( D (THTA) / DP", "= - ( u * DDX (S) + v *", "defr(V): \"\"\" Total deformation <div class=jython> DEF ( V )", "Smooth a scalar grid using a 9-point smoother (see sm9s)", "DSH = ddx(vwind) + ddy(uwind) DST = ddx(uwind) - ddy(vwind)", "return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE) else: return layerAverage(S,level1,level2, unit) def ldf(S,level1,level2, unit=None):", "* v2 </div> \"\"\" product = mul(V1,V2) return add(ur(product),vr(product)) def", "grid using a 9-point smoother (see sm9s) \"\"\" return sm9s(V)", "<div class=jython> ADD (S1, S2) = S1 + S2<br> WA", "V ) = ( 1/( D (THTA) / DP )", "based on the grid diagnostics from the GEneral Meteorological PAcKage", "(KYD) ) KYD = number of points in row YSUM", "point in that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X)", "+ ddy(vwind))* (-1.0) # DSH = ddx(vwind) + ddy(uwind) DST", "thte(temp,rh): \"\"\" Equivalent Potential Temperature from Temperature and Relative humidity", "number of points in row YSUM for a column is", "(THTA) ) * ( DEF * COS (2 * BETA)", "for a vertical column is stored at every point </div>", "makeVector(S1,S2) def vlav(V,level1,level2, unit=None): \"\"\" calculate the vector layer average", "pressure domain) \"\"\" return DerivedGridFactory.createRelativeHumidity(temp,mixr) def pvor(S,V): \"\"\" Potetial Vorticity", "(-1.0) # DSH = ddx(vwind) + ddy(uwind) DST = ddx(uwind)", "NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.divide(S1,S2,WA) def sub(S1,S2,WA=0): \"\"\" Subtract <div", "point values in the subset area </div> \"\"\" return savg(S)", "def sub(S1,S2,WA=0): \"\"\" Subtract <div class=jython> SUB (S1, S2) =", "return DerivedGridFactory.GRAVITY; # Math functions def atn2(S1,S2,WA=0): \"\"\" Wrapper for", "YSUM for a column is stored at every point in", "<div class=jython> LP = 7.268DUDZ + 0.718DTDN + 0.318DUDN -", "stored at every point in that row. </div> \"\"\" return", "return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def avg(S1,S2): \"\"\" Average of 2 scalars <div", "\"\"\" relv = vor(V) return add(relv,corl(relv)) def circs(S, D=2): \"\"\"", "class=jython> SM5S ( S ) = .5 * S (i,j)", "(S) ) ), - ( DOT ( DVDY (V), GRAD", "unit) def vldf(V,level1,level2, unit=None): \"\"\" calculate the vector layer difference", "dvdx(V): \"\"\" Partial x derivative of a vector <div class=jython>", "The weighting function is the circular aperature diffraction function. D", "def cros(V1,V2): \"\"\" Vector cross product magnitude <div class=jython> CROS", "* DDY (S2) - DDY (S1) * DDX (S2) </div>", "(e.g. str). <P> In the following operators, scalar operands are", ") ) </div> \"\"\" return add(mul(S,(div(V))) , dot(V,grad(S))) def shr(V):", "points in row KNT = number of non-missing points in", "= S * DIV ( V ) + DOT (", "\"\"\" return makeVector(S1,S2) def vlav(V,level1,level2, unit=None): \"\"\" calculate the vector", "smoothing using normally distributed weights with theoretical response of 1/e", "<div class=jython> Apply a rectangular aperature smoothing to the grid", "KZD = number of levels KNT = number of non-missing", "\"\"\" product = mul(V1,V2) return add(ur(product),vr(product)) def gwfs(S, N=6): \"\"\"", "Grid relative u component \"\"\" return DerivedGridFactory.getUComponent(V) def vn(V): \"\"\"", "</div> \"\"\" return GridMath.multiply(S1,S2,WA) def quo(S1,S2,WA=0): \"\"\" Divide <div class=jython>", "grid <div class=jython> LAV ( S ) = ( S", "the vertical wind shear in a layer <div class=jython> WSHR", "( THTA, V ) = ( 1/( D (THTA) /", "weighting function is the circular aperature diffraction function. D is", "in the subset area </div> \"\"\" return savg(S) def sdiv(S,V):", "CORL = TWO_OMEGA*sin(latr) </div> \"\"\" return DerivedGridFactory.createCoriolisGrid(S) def cress(S, D=2):", "def sm5v(V): \"\"\" Smooth a scalar grid using a 5-point", "\"\"\" return add(V1,V2) def vecn(S1,S2): \"\"\" Make a true north", "= S1 + S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)", "( V1, GRAD (u2) ), DOT ( V1, GRAD (v2)", "sub(ddx(vr(V)),ddy(ur(V))) def vr(V): \"\"\" Grid relative v component \"\"\" return", "average of all non-missing grid point values </div> \"\"\" return", "number of points in row XSUM for a row is", "\"\"\" Grid relative v component \"\"\" return DerivedGridFactory.getVComponent(V) def xav(S):", ") = ( 1/( D (THTA) / DP ) )", "smoothing. (default N=6) </div> \"\"\" return gwfs(V, N) def inad(V1,V2):", "mixr(temp,rh): \"\"\" Mixing Ratio from Temperature, RH (requires pressure domain)", "add(ur(product),vr(product)) def gwfs(S, N=6): \"\"\" <div class=jython> Horizontal smoothing using", "return quo(dv,dz) # Vector output def age(obs,geo): \"\"\" Ageostrophic wind", "vr(V): \"\"\" Grid relative v component \"\"\" return DerivedGridFactory.getVComponent(V) def", "VOR ( V ) = DDX ( v ) -", "+ DIV) </div> \"\"\" VWS = windShear(u, v, z, top,", "\"\"\" Horizontal Flux Divergence <div class=jython> SDIV ( S, V", "dirr(DerivedGridFactory.createTrueFlowVector(V)) def dirr(V): \"\"\" Grid relative direction of a vector", "\"SM9S\") def strd(V): \"\"\" Stretching Deformation <div class=jython> STRD (", "number of non-missing points in row XAV for a row", "the vector layer average <div class=jython> VLDF(V) = [(u(level1) -", "thta(temp): \"\"\" Potential Temperature from Temperature (requires pressure domain) \"\"\"", "+ SHR (V) ** 2 ) ** .5 </div> \"\"\"", "D=2) </div> \"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def savg(S): \"\"\"", ") <br> PSI = 1/2 ATAN2 ( SHR / STR", "and wind) \"\"\" return DerivedGridFactory.createPotentialVorticity(S,V) def rects(S, D=2): \"\"\" <div", "\"\"\" return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def latr(S): \"\"\" Latitudue all points in", "<div class=jython> ZAV (S) = ( S (Z1) + S", "), DDY ( S ) ] </div> \"\"\" return vecr(ddx(S),ddy(S))", "# uwind = getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top) DIV", "levels of a grid at all points <div class=jython> ZSUM", "add(ddx(ur(V)),ddy(vr(V))) def dirn(V): \"\"\" North relative direction of a vector", "corl(S): \"\"\" Coriolis Parameter for all points in a grid", "derivative with respect to the domain's X coordinate \"\"\" return", "( DVDX (V), GRAD (THTA) ) ), ( DOT (", "smoothing to the grid points. The weighting function is the", "</div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y) def zav(S): \"\"\" Average", "def GRAVITY(): \"\"\" Gravity constant \"\"\" return DerivedGridFactory.GRAVITY; # Math", "the following operators, scalar operands are named S<sub>n</sub> and vector", "def ddy(S): \"\"\" Take the derivative with respect to the", "of 2 vectors <div class=jython> VSUB (V1, V2) = [", "class=jython> VLDF(V) = [u(level1) - u(level2), v(level1) - v(level2)] </div>", "(default N=6) </div> \"\"\" return GridUtil.smooth(S, \"GWFS\", int(N)) def jcbn(S1,S2):", "DIV ( GRAD (S) ) </div> \"\"\" grads = grad(S)", "the components of 2 vectors <div class=jython> VADD (V1, V2)", "(V1, V2) = [ u1-u2, v1-v2 ] </div> \"\"\" return", "vertical column is stored at every point </div> \"\"\" return", "int(N)) def jcbn(S1,S2): \"\"\" Jacobian Determinant <div class=jython> JCBN (", "NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.subtract(S1,S2,WA) # Scalar quantities def adv(S,V):", "= mul(V1,V2) return add(ur(product),vr(product)) def gwfs(S, N=6): \"\"\" <div class=jython>", "a vector \"\"\" return DerivedGridFactory.createVectorDirection(V) def dot(V1,V2): \"\"\" Vector dot", "return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X) def xsum(S): \"\"\" Sum along a", "pressure domain) \"\"\" return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def un(V): \"\"\" North relative", "V ) = DDX ( v ) + DDY (", "diagnostics from the GEneral Meteorological PAcKage (GEMPAK). Note that the", "shr(V) strch = strd(V) psi = .5*atn2(shear,strch) dxt = ddx(S)", "SM5S ( S ) = .5 * S (i,j) +", "S ) = [ - DDY (S) * const /", ") </div> \"\"\" return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def avg(S1,S2): \"\"\" Average of", "(GEMPAK). Note that the names are case sensitive and some", ") = .5 * S (i,j) + .125 * (", "names are case sensitive and some are named slightly different", "x derivative of a vector <div class=jython> DVDX ( V", "return GridUtil.smooth(S, \"CRES\", int(D)) def cros(V1,V2): \"\"\" Vector cross product", "</div> \"\"\" return add(S1,S2)/2 def avor(V): \"\"\" Absolute Vorticity <div", "return gwfs(V, N) def inad(V1,V2): \"\"\" Inertial advective wind <div", "= DDX ( v ) + DDY ( u )", "( 1/( D (THTA) / DP ) ) * [", "class=jython> SM9S ( S ) = .25 * S (i,j)", "* DDX (S) + v * DDY (S) ) </div>", "KXD = number of points in row XSUM for a", "in that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X) def", "given by a weighted average of surrounding grid points. D", "return GridUtil.smooth(S, \"CIRC\", int(D)) def cresv(S, D=2): \"\"\" <div class=jython>", "Apply a circular aperature smoothing to the grid points. The", "return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def qvec(S,V): \"\"\" Q-vector at a level (", "class=jython> QVEC ( S, V ) = [ - (", "\"\"\" grads = grad(S) qvecu = newName(-dot(dvdx(V),grads),\"qvecu\") qvecv = newName(-dot(dvdy(V),grads),\"qvecv\")", "[ S1, S2 ] </div> \"\"\" return makeVector(S1,S2) def vlav(V,level1,level2,", "] </div> \"\"\" return vldf(geo(S),level1,level2, unit) def vadd(V1,V2): \"\"\" add", "ddx(uwind) - ddy(vwind) DEF = sqrt(DSH * DSH + DST", "/ m / s ) <div class=jython> QVEC ( S,", "Horizontal Divergence <div class=jython> DIV ( V ) = DDX", "( V ) = MAG [ VLDF (V) ] /", "CORL ] </div> \"\"\" return DerivedGridFactory.createGeostrophicWindVector(z) def grad(S): \"\"\" Gradient", "class=jython> VADD (V1, V2) = [ u1+u2, v1+v2 ] </div>", "<div class=jython> YSUM (S) = ( S (Y1) + S", "GridUtil.smooth(S, \"CRES\", int(D)) def dvdx(V): \"\"\" Partial x derivative of", "a weighted average of surrounding grid points. D is the", "points. The weighting function is the circular aperature diffraction function.", "* COS (2 * BETA) - DIV ) <p> Where:", ") ) ] where S can be any thermal paramenter,", "newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return vecr(qvecudp,qvecvdp) def rectv(S, D=2): \"\"\"", "</div> \"\"\" return GridMath.divide(S1,S2,WA) def sub(S1,S2,WA=0): \"\"\" Subtract <div class=jython>", "\"\"\" Potential Temperature from Temperature (requires pressure domain) \"\"\" return", "the wind shear between discrete layers <div class=jython> LP =", "WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.add(S1,S2,WA) def mul(S1,S2,WA=0): \"\"\"", "of points in column KNT = number of non-missing points", "COS (2 * BETA) - DIV ) <p> Where: BETA", "smoothing to the grid points. The smoothed value is given", "S2) = S1 * S2<br> WA = use WEIGHTED_AVERAGE (default", "wshr(V, Z, top, bottom): \"\"\" Magnitude of the vertical wind", "Temperature from Temperature and Relative humidity (requires pressure domain) \"\"\"", "\"\"\" Multiply <div class=jython> MUL (S1, S2) = S1 *", "\"\"\" Q-vector ( K / m / s ) <div", "def vn(V): \"\"\" North relative v component \"\"\" return vr(DerivedGridFactory.createTrueFlowVector(V))", "Multiply the components of 2 vectors <div class=jython> VMUL (V1,", "(default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.atan2(S1,S2,WA) def add(S1,S2,WA=0): \"\"\" Addition", "(u), DDY (v) ] </div> \"\"\" return vecr(ddy(ur(V)), ddy(vr(V))) def", "= getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top) temp = newUnit(getSliceAtLevel(t,", "of points in row KNT = number of non-missing points", "in row KNT = number of non-missing points in row", "gradt = grad(S) mgradt = mag(gradt) a = -cosd*dxt-sind*dyt beta", "use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.divide(S1,S2,WA) def sub(S1,S2,WA=0):", "DerivedGridFactory.createVectorMagnitude(a[0]); else: return DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def mixr(temp,rh): \"\"\" Mixing Ratio from", "</div> \"\"\" return layerAverage(V, level1, level2, unit) def vldf(V,level1,level2, unit=None):", "= S (level1) - S (level2) </div> \"\"\" return layerDiff(S,level1,level2,", "class=jython> LDF ( S ) = S (level1) - S", "S (i,j-1) ) + .0625 * ( S (i+1,j+1) +", "\"\"\" Total deformation <div class=jython> DEF ( V ) =", "(Y2) + ... + S (KYD) ) / KNT KYD", "S (Z1) + S (Z2) + ... + S (KZD)", "class=jython> XAV (S) = ( S (X1) + S (X2)", ") / 2. </div> \"\"\" if level1 == None: return", ") = ( S (level1) + S (level2) ) /", "+ S (i-1,j) + S (i,j-1) ) </div> \"\"\" return", "a = -cosd*dxt-sind*dyt beta = asin(a/mgradt) frnto = .5*mgradt*(defr(V)*cos(2*beta)-div(V)) return", "gwfv(V, N=6): \"\"\" <div class=jython> Horizontal smoothing using normally distributed", "a scalar <div class=jython> GRAD ( S ) = [", "subset area </div> \"\"\" return savg(S) def sdiv(S,V): \"\"\" Horizontal", "DIV ( V ) + DOT ( V, GRAD (", "of a multi layer grid <div class=jython> LAV ( S", "return GridUtil.smooth(S, \"GWFS\", int(N)) def jcbn(S1,S2): \"\"\" Jacobian Determinant <div", "points in row XAV for a row is stored at", "the domain's Y coordinate \"\"\" return GridMath.ddy(S); def defr(V): \"\"\"", "z, top, bottom, unit)*7.268 uwind = getSliceAtLevel(u, top) vwind =", "points. D is the radius of influence in grid increments,", "paramenter, usually THTA. </div> \"\"\" grads = grad(S) qvecu =", "def vecn(S1,S2): \"\"\" Make a true north vector from two", "TWO_OMEGA*sin(latr) </div> \"\"\" return DerivedGridFactory.createCoriolisGrid(S) def cress(S, D=2): \"\"\" <div", "a grid column <div class=jython> YSUM (S) = ( S", "\"CRES\", int(D)) def cros(V1,V2): \"\"\" Vector cross product magnitude <div", "vector \"\"\" return DerivedGridFactory.createVectorDirection(V) def dot(V1,V2): \"\"\" Vector dot product", "(default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.add(S1,S2,WA) def mul(S1,S2,WA=0): \"\"\" Multiply", "</div> \"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def cresv(S, D=2): \"\"\"", "grid diagnostics from the GEneral Meteorological PAcKage (GEMPAK). Note that", ") = DDX ( v ) - DDY ( u", "number of levels KNT = number of non-missing points in", "zsum(S): \"\"\" Sum across the levels of a grid at", ") = S (level1) - S (level2) </div> \"\"\" return", "= [ DDX (u), DDX (v) ] </div> \"\"\" return", "that the names are case sensitive and some are named", ") = DDX ( u ) + DDY ( v", "return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y) def ysum(S): \"\"\" Sum along a", "return DerivedGridFactory.createPotentialVorticity(S,V) def rects(S, D=2): \"\"\" <div class=jython> Apply a", "Relative Vorticity <div class=jython> VOR ( V ) = DDX", "(S) ) ) ] where S can be any thermal", "scalar <div class=jython> GRAD ( S ) = [ DDX", "def dvdx(V): \"\"\" Partial x derivative of a vector <div", "class=jython> DVDY ( V ) = [ DDY (u), DDY", "S<sub>n</sub> and vector operands are named V<sub>n</sub>. Lowercase u and", "[ DDY (u), DDY (v) ] </div> \"\"\" return vecr(ddy(ur(V)),", "\"\"\" Average along a grid row <div class=jython> XAV (S)", "S ) = [ u (OBS) - u (GEO(S)), v", "vecn(S1,S2): \"\"\" Make a true north vector from two components", "vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def qvec(S,V): \"\"\" Q-vector at a level ( K", "operands are named S<sub>n</sub> and vector operands are named V<sub>n</sub>.", "* u2 + v1 * v2 </div> \"\"\" product =", "+ S (KXD) ) / KNT KXD = number of", "\"\"\" return savg(S) def sdiv(S,V): \"\"\" Horizontal Flux Divergence <div", "S2) = ( S1 + S2 ) / 2 </div>", "a layer <div class=jython> WSHR ( V ) = MAG", "= GridMath.partial(THTA,2) gradt = grad(THTA) qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp =", "<div class=jython> SM9S ( S ) = .25 * S", "(i,j-1) ) + .0625 * ( S (i+1,j+1) + S", "(S) = ( S (X1) + S (X2) + ...", "noUnit(HT))) L = (L - 2.520)*(-0.59) P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,\"exp\"))", "GEneral Meteorological PAcKage (GEMPAK). Note that the names are case", "the grid points. The weighting function is the product of", "Multiply <div class=jython> MUL (S1, S2) = S1 * S2<br>", "points. The smoothed value is given by a weighted average", "z, t, top, bottom, unit): \"\"\" calculate the wind shear", "(KXD) ) / KNT KXD = number of points in", "+ S (X2) + ... + S (KXD) ) /", "- DIV ) <p> Where: BETA = ASIN ( (-DDX", "Vector output def age(obs,geo): \"\"\" Ageostrophic wind <div class=jython> AGE", "GridUtil.smooth(S, \"RECT\", int(D)) def sm5v(V): \"\"\" Smooth a scalar grid", "def vadd(V1,V2): \"\"\" add the components of 2 vectors <div", "all points <div class=jython> ZSUM (S) = ( S (Z1)", "FRNT ( THTA, V ) = 1/2 * MAG (", "= ( S (Y1) + S (Y2) + ... +", "of non-missing points in column </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE)", "+ ... + S (KZD) ) / KNT KZD =", "** .5 </div> \"\"\" return mag(strd(V),shr(V)) def div(V): \"\"\" Horizontal", "GRAD (u2) ), DOT ( V1, GRAD (v2) ) ]", "dvdy(V): \"\"\" Partial x derivative of a vector <div class=jython>", "Magnitude of the vertical wind shear in a layer <div", "getSliceAtLevel(v, top) DIV = (ddx(uwind) + ddy(vwind))* (-1.0) # DSH", "\"\"\" return GridMath.multiply(S1,S2,WA) def quo(S1,S2,WA=0): \"\"\" Divide <div class=jython> QUO", "</div> \"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def savg(S): \"\"\" Average", "def ur(V): \"\"\" Grid relative u component \"\"\" return DerivedGridFactory.getUComponent(V)", "use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.atan2(S1,S2,WA) def add(S1,S2,WA=0):", "conflicts with Jython built-ins (e.g. str). <P> In the following", "unit): \"\"\" calculate the wind shear between discrete layers <div", "multi layer grid <div class=jython> LAV ( S ) =", "(S1, S2) = ATAN ( S1 / S2 )<br> WA", "DerivedGridFactory.getUComponent(V) def vn(V): \"\"\" North relative v component \"\"\" return", "\"\"\" <div class=jython> Apply a circular aperature smoothing to the", "div(V): \"\"\" Horizontal Divergence <div class=jython> DIV ( V )", "] </div> \"\"\" return sub(obs,geo) def circv(S, D=2): \"\"\" <div", "\"\"\" return DerivedGridFactory.GRAVITY; # Math functions def atn2(S1,S2,WA=0): \"\"\" Wrapper", "return savg(S) def sdiv(S,V): \"\"\" Horizontal Flux Divergence <div class=jython>", "V2 ) = [ DOT ( V1, GRAD (u2) ),", "dv = mag(vldf(V,top,bottom)) dz = ldf(Z,top,bottom) return quo(dv,dz) # Vector", "Frontogenesis function from theta and the wind <div class=jython> FRNT", "( SHR / STR ) <br> </div> \"\"\" shear =", "add(mul(S,(div(V))) , dot(V,grad(S))) def shr(V): \"\"\" Shear Deformation <div class=jython>", "using a 9-point smoother <div class=jython> SM9S ( S )", "DDY ( v ) </div> \"\"\" return add(ddx(ur(V)),ddy(vr(V))) def dirn(V):", "/ KNT KXD = number of points in row KNT", "</div> \"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def corl(S): \"\"\" Coriolis", "GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def zsum(S): \"\"\" Sum across the levels of", "def strd(V): \"\"\" Stretching Deformation <div class=jython> STRD ( V", "\"\"\" return add(ddx(vr(V)),ddy(ur(V))) def sm5s(S): \"\"\" Smooth a scalar grid", "every point in that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM,", "</div> \"\"\" return add(ddx(vr(V)),ddy(ur(V))) def sm5s(S): \"\"\" Smooth a scalar", "lap(S): \"\"\" Laplacian operator <div class=jython> LAP ( S )", "5-point smoother <div class=jython> SM5S ( S ) = .5", "at a level ( K / m / s )", "\"\"\" return vecr(ddx(S),ddy(S)) def gwfv(V, N=6): \"\"\" <div class=jython> Horizontal", "increases the smoothing. (default N=6) </div> \"\"\" return gwfs(V, N)", "newName(-dot(dvdy(V),grads),\"qvecv\") return vecr(qvecu,qvecv) def qvcl(THTA,V): \"\"\" Q-vector ( K /", "(Y2) + ... + S (KYD) ) KYD = number", "S, V ) = [ - ( DOT ( DVDX", "[ u1+u2, v1+v2 ] </div> \"\"\" return add(V1,V2) def vecn(S1,S2):", "= DDX (S1) * DDY (S2) - DDY (S1) *", "def vquo(V1,V2): \"\"\" Divide the components of 2 vectors <div", ") / KNT KXD = number of points in row", "(Z) </div> \"\"\" dv = mag(vldf(V,top,bottom)) dz = ldf(Z,top,bottom) return", "SDIV ( S, V ) = S * DIV (", "v(level2)] </div> \"\"\" return layerDiff(V,level1,level2, unit) def vmul(V1,V2): \"\"\" Multiply", "\"\"\" subtract the components of 2 vectors <div class=jython> VSUB", "components <div class=jython> VECN ( S1, S2 ) = [", "( v ) + DDY ( u ) </div> \"\"\"", "</div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y) def ysum(S): \"\"\" Sum", "of all non-missing grid point values </div> \"\"\" return GridMath.applyFunctionToLevels(S,", "GRAD (THTA) ) * ( DEF * COS (2 *", "</div> \"\"\" return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM) def wshr(V, Z, top, bottom):", "grid row <div class=jython> XSUM (S) = ( S (X1)", ") / KNT KZD = number of levels KNT =", "grid increments, increasing D increases the smoothing. (default D=2) </div>", "increasing D increases the smoothing. (default D=2) </div> \"\"\" return", "ldf(S,level1,level2, unit=None): \"\"\" Layer Difference <div class=jython> LDF ( S", "<div class=jython> MUL (S1, S2) = S1 * S2<br> WA", "S (KYD) ) / KNT KYD = number of points", "1/( D (THTA) / DP ) ) * [ (", "<div class=jython> SM5S ( S ) = .5 * S", "DDX ( v ) + DDY ( u ) </div>", "ATAN ( S1 / S2 )<br> WA = use WEIGHTED_AVERAGE", "P= 1.0/(1.0 + GridMath.applyFunctionOverGridsExt(L,\"exp\")) LP = setLevel(P ,top, unit) return", "= use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.subtract(S1,S2,WA) #", "VLDF(V) = [u(level1) - u(level2), v(level1) - v(level2)] </div> \"\"\"", "( S ) = .5 * S (i,j) + .125", "\"\"\" return sub(ddx(vr(V)),ddy(ur(V))) def vr(V): \"\"\" Grid relative v component", "[ DDX (u), DDX (v) ] </div> \"\"\" return vecr(ddx(ur(V)),", "inad(V1,V2): \"\"\" Inertial advective wind <div class=jython> INAD ( V1,", "mag(strd(V),shr(V)) def div(V): \"\"\" Horizontal Divergence <div class=jython> DIV (", "= getSliceAtLevel(v, top) DIV = (ddx(uwind) + ddy(vwind))* (-1.0) #", "\"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X) def xsum(S): \"\"\" Sum along", "class=jython> DVDX ( V ) = [ DDX (u), DDX", "point </div> \"\"\" return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_SUM) def wshr(V, Z, top,", "strd(V) psi = .5*atn2(shear,strch) dxt = ddx(S) dyt = ddy(S)", "( S1 + S2 ) / 2 </div> \"\"\" return", "(V1, V2) = [ u1*u2, v1*v2 ] </div> \"\"\" return", "[ S1, S2 ] </div> \"\"\" return makeTrueVector(S1,S2) def vecr(S1,S2):", "a grid at all points <div class=jython> ZSUM (S) =", "atan2 built-in <div class=jython> ATN2 (S1, S2) = ATAN (", "vectors <div class=jython> VMUL (V1, V2) = [ u1*u2, v1*v2", "uwind = getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top) DIV =", "is the product of the rectangular aperature diffraction function in", "def xav(S): \"\"\" Average along a grid row <div class=jython>", "psi = .5*atn2(shear,strch) dxt = ddx(S) dyt = ddy(S) cosd", "operators, scalar operands are named S<sub>n</sub> and vector operands are", "\"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def zsum(S): \"\"\" Sum across the", "( DVDY (V), GRAD (THTA) ) ) ] </div> \"\"\"", ") + DDY ( u ) </div> \"\"\" return add(ddx(vr(V)),ddy(ur(V)))", "</div> \"\"\" return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def avg(S1,S2): \"\"\" Average of 2", "return sub(obs,geo) def circv(S, D=2): \"\"\" <div class=jython> Apply a", ") = 1/2 * MAG ( GRAD (THTA) ) *", "named S<sub>n</sub> and vector operands are named V<sub>n</sub>. Lowercase u", "components of a vector. \"\"\" def GRAVITY(): \"\"\" Gravity constant", ") ** .5 </div> \"\"\" return mag(strd(V),shr(V)) def div(V): \"\"\"", "Y coordinate \"\"\" return GridMath.ddy(S); def defr(V): \"\"\" Total deformation", "(GEO(S)), v (OBS) - v (GEO(S)) ] </div> \"\"\" return", "def zsum(S): \"\"\" Sum across the levels of a grid", "div(grads) def lav(S,level1=None,level2=None, unit=None): \"\"\" Layer Average of a multi", "( V1, V2 ) = u1 * v2 - u2", "DOT ( V1, GRAD (u2) ), DOT ( V1, GRAD", "def jcbn(S1,S2): \"\"\" Jacobian Determinant <div class=jython> JCBN ( S1,", "WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.divide(S1,S2,WA) def sub(S1,S2,WA=0): \"\"\"", "\"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def savg(S): \"\"\" Average over", "class=jython> SAVG ( S ) = average of all non-missing", "GridUtil.smooth(S, \"SM5S\") def sm9s(S): \"\"\" Smooth a scalar grid using", "qvec(S,V): \"\"\" Q-vector at a level ( K / m", "( S (X1) + S (X2) + ... + S", "- u (GEO(S)) (level2), v (GEO(S)) (level1) - v (GEO(S))", "use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.add(S1,S2,WA) def mul(S1,S2,WA=0):", "non-missing grid point values in the subset area </div> \"\"\"", "Z, top, bottom): \"\"\" Magnitude of the vertical wind shear", "\"\"\" return mul(V1,V2) def vquo(V1,V2): \"\"\" Divide the components of", "\"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def corl(S): \"\"\" Coriolis Parameter", "DDY ( S ) ] </div> \"\"\" return vecr(ddx(S),ddy(S)) def", "S ) = average of all non-missing grid point values", "= grad(THTA) qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return vecr(qvecudp,qvecvdp)", "<div class=jython> AVOR ( V ) = VOR ( V", "layer <div class=jython> WSHR ( V ) = MAG [", "class=jython> ADV ( S, V ) = - ( u", "return mul(V1,V2) def vquo(V1,V2): \"\"\" Divide the components of 2", "S2 ) = DDX (S1) * DDY (S2) - DDY", "DDX (S2) </div> \"\"\" return sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def latr(S): \"\"\" Latitudue", "grid using a 9-point smoother <div class=jython> SM9S ( S", "a scalar grid using a 9-point smoother (see sm9s) \"\"\"", "= ddy(S) cosd = cos(psi) sind = sin(psi) gradt =", "Deformation <div class=jython> SHR ( V ) = DDX (", "points in row XSUM for a row is stored at", "grid at all points <div class=jython> ZAV (S) = (", "wind <div class=jython> AGE ( S ) = [ u", "V2 ) = u1 * v2 - u2 * v1", "[ ( DOT ( DVDX (V), GRAD (THTA) ) ),", "sqrt(DSH * DSH + DST * DST) EI = mul(noUnit(VWS),", "2 scalars <div class=jython> AVG (S1, S2) = ( S1", "9-point smoother <div class=jython> SM9S ( S ) = .25", "row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X) def xsum(S): \"\"\"", "in column </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y) def ysum(S):", "Stretching Deformation <div class=jython> STRD ( V ) = DDX", "(V1, V2) = [ u1/u2, v1/v2 ] </div> \"\"\" return", "point in that column. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y)", "z, top, bottom, unit): \"\"\" calculate the wind shear between", "grid points. The weighting function is the circular aperature diffraction", "using normally distributed weights with theoretical response of 1/e for", "ddy(S): \"\"\" Take the derivative with respect to the domain's", ") = [ DDX (u), DDX (v) ] </div> \"\"\"", "D increases the smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S,", "return DerivedGridFactory.createLatitudeGrid(S) def lap(S): \"\"\" Laplacian operator <div class=jython> LAP", ") = S * DIV ( V ) + DOT", "is the circular aperature diffraction function. D is the radius", "WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div> \"\"\" return GridMath.subtract(S1,S2,WA)", "v, z, top, bottom, unit)*7.268 uwind = getSliceAtLevel(u, top) vwind", "= [u(level1) - u(level2), v(level1) - v(level2)] </div> \"\"\" return", "is given by a weighted average of surrounding grid points.", "using a 5-point smoother <div class=jython> SM5S ( S )", "qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return vecr(qvecudp,qvecvdp) def rectv(S, D=2): \"\"\" <div", "S (level2) </div> \"\"\" return layerDiff(S,level1,level2, unit); def mag(*a): \"\"\"", "dot product <div class=jython> DOT ( V1, V2 ) =", "a grid row <div class=jython> XAV (S) = ( S", "\"\"\" return DerivedGridFactory.createCoriolisGrid(S) def cress(S, D=2): \"\"\" <div class=jython> Apply", "( S ) ] </div> \"\"\" return vecr(ddx(S),ddy(S)) def gwfv(V,", "\"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def cros(V1,V2): \"\"\" Vector cross", "( V ) = DDX ( v ) + DDY", "latr(S): \"\"\" Latitudue all points in a grid \"\"\" return", "area </div> \"\"\" return savg(S) def sdiv(S,V): \"\"\" Horizontal Flux", "<br> PSI = 1/2 ATAN2 ( SHR / STR )", "if (len(a) == 1): return DerivedGridFactory.createVectorMagnitude(a[0]); else: return DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def", "wind <div class=jython> THRM ( S ) = [ u", "S1, S2 ] </div> \"\"\" return makeTrueVector(S1,S2) def vecr(S1,S2): \"\"\"", "DerivedGridFactory.getVComponent(V) def xav(S): \"\"\" Average along a grid row <div", "Gravity constant \"\"\" return DerivedGridFactory.GRAVITY; # Math functions def atn2(S1,S2,WA=0):", "QUO (S1, S2) = S1 / S2<br> WA = use", "the domain's X coordinate \"\"\" return GridMath.ddx(S); def ddy(S): \"\"\"", "SM9S ( S ) = .25 * S (i,j) +", "product magnitude <div class=jython> CROS ( V1, V2 ) =", "SHR ( V ) = DDX ( v ) +", "DOT ( V1, V2 ) = u1 * u2 +", "DOT ( V, GRAD ( S ) ) </div> \"\"\"", "\"\"\" Magnitude of a vector \"\"\" if (len(a) == 1):", "v ) </div> \"\"\" return sub(ddx(ur(V)),ddy(vr(V))) def thta(temp): \"\"\" Potential", "STRD ( V ) = DDX ( u ) -", "S (i-1,j+1) + S (i-1,j-1) ) </div> \"\"\" return GridUtil.smooth(S,", "over grid subset <div class=jython> SAVS ( S ) =", "of a grid at all points <div class=jython> ZAV (S)", "scalar grid using a 5-point smoother <div class=jython> SM5S (", "def mixr(temp,rh): \"\"\" Mixing Ratio from Temperature, RH (requires pressure", "<div class=jython> VOR ( V ) = DDX ( v", "setLevel(P ,top, unit) return LP def EllrodIndex(u, v, z, top,", "(S) * const / CORL ] </div> \"\"\" return DerivedGridFactory.createGeostrophicWindVector(z)", "= [ DDY (u), DDY (v) ] </div> \"\"\" return", "Make a true north vector from two components <div class=jython>", "(OBS) - u (GEO(S)), v (OBS) - v (GEO(S)) ]", "2 + SHR (V) ** 2 ) ** .5 </div>", "Average along a grid row <div class=jython> XAV (S) =", ") = [ - DDY (S) * const / CORL,", "vector <div class=jython> DVDX ( V ) = [ DDX", "vldf(geo(S),level1,level2, unit) def vadd(V1,V2): \"\"\" add the components of 2", "strd(V): \"\"\" Stretching Deformation <div class=jython> STRD ( V )", "<div class=jython> THRM ( S ) = [ u (GEO(S))", "<div class=jython> VQUO (V1, V2) = [ u1/u2, v1/v2 ]", "relh(temp,mixr): \"\"\" Create Relative Humidity from Temperature, mixing ratio (requires", "# Math functions def atn2(S1,S2,WA=0): \"\"\" Wrapper for atan2 built-in", "<div class=jython> INAD ( V1, V2 ) = [ DOT", "(i,j) + .125 * ( S (i+1,j) + S (i,j+1)", "PSI = 1/2 ATAN2 ( SHR / STR ) <br>", "Vector dot product <div class=jython> DOT ( V1, V2 )", "(i+1,j+1) + S (i+1,j-1) + S (i-1,j+1) + S (i-1,j-1)", "def avor(V): \"\"\" Absolute Vorticity <div class=jython> AVOR ( V", "\"\"\" Divide <div class=jython> QUO (S1, S2) = S1 /", "LP = setLevel(P ,top, unit) return LP def EllrodIndex(u, v,", "average of surrounding grid points. D is the radius of", "MAG ( GRAD (THTA) ) ) <br> PSI = 1/2", "u ) </div> \"\"\" return sub(ddx(vr(V)),ddy(ur(V))) def vr(V): \"\"\" Grid", "components of 2 vectors <div class=jython> VSUB (V1, V2) =", "<div class=jython> GRAD ( S ) = [ DDX (", "= .25 * S (i,j) + .125 * ( S", "GRAD (S) ) ), - ( DOT ( DVDY (V),", ") ), ( DOT ( DVDY (V), GRAD (THTA) )", "+ S (i-1,j-1) ) </div> \"\"\" return GridUtil.smooth(S, \"SM9S\") def", "... + S (KYD) ) KYD = number of points", "in row YSUM for a column is stored at every", "def grad(S): \"\"\" Gradient of a scalar <div class=jython> GRAD", "DerivedGridFactory.createRelativeHumidity(temp,mixr) def pvor(S,V): \"\"\" Potetial Vorticity (usually from theta and", "== None: return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE) else: return layerAverage(S,level1,level2, unit) def", "sm5v(V): \"\"\" Smooth a scalar grid using a 5-point smoother", "if level1 == None: return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE) else: return layerAverage(S,level1,level2,", "def age(obs,geo): \"\"\" Ageostrophic wind <div class=jython> AGE ( S", "V2) = [ u1/u2, v1/v2 ] </div> \"\"\" return quo(V1,V2)", "\"\"\" if (len(a) == 1): return DerivedGridFactory.createVectorMagnitude(a[0]); else: return DerivedGridFactory.createVectorMagnitude(a[0],a[1]);", "grads = grad(S) qvecu = newName(-dot(dvdx(V),grads),\"qvecu\") qvecv = newName(-dot(dvdy(V),grads),\"qvecv\") return", "increases the smoothing. (default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CIRC\",", "return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_Y) def zav(S): \"\"\" Average across the", "S (Z2) + ... + S (KZD) ) KZD =", "ATN2 (S1, S2) = ATAN ( S1 / S2 )<br>", "dot(V,grad(S))) def shr(V): \"\"\" Shear Deformation <div class=jython> SHR (", "respect to the domain's Y coordinate \"\"\" return GridMath.ddy(S); def", "2 vectors <div class=jython> VADD (V1, V2) = [ u1+u2,", "different from GEMPAK functions to avoid conflicts with Jython built-ins", "( u * DDX (S) + v * DDY (S)", "= sin(psi) gradt = grad(S) mgradt = mag(gradt) a =", "+ S (i-1,j+1) + S (i-1,j-1) ) </div> \"\"\" return", "* DDY (S) ) </div> \"\"\" return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def avg(S1,S2):", "\"\"\" Potetial Vorticity (usually from theta and wind) \"\"\" return", ") <p> Where: BETA = ASIN ( (-DDX (THTA) *", "vor(V) return add(relv,corl(relv)) def circs(S, D=2): \"\"\" <div class=jython> Apply", "0.318DUDN - 2.52 </div> \"\"\" Z = windShear(u, v, z,", "top) vwind = getSliceAtLevel(v, top) temp = newUnit(getSliceAtLevel(t, top), \"temperature\",", "= shr(V) strch = strd(V) psi = .5*atn2(shear,strch) dxt =", "return vecr(ddy(ur(V)), ddy(vr(V))) def frnt(S,V): \"\"\" Frontogenesis function from theta", "(default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CIRC\", int(D)) def corl(S):", "+ DDY ( u ) </div> \"\"\" return add(ddx(vr(V)),ddy(ur(V))) def", "u ) - DDY ( v ) </div> \"\"\" return", "is the doc for the Grid Diagnostics module. These functions", "</div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def savs(S): \"\"\" Average over", "\"\"\" Sum across the levels of a grid at all", ") - DDY ( u ) </div> \"\"\" return sub(ddx(vr(V)),ddy(ur(V)))", "+ S2 ) / 2 </div> \"\"\" return add(S1,S2)/2 def", "= mag(vldf(V,top,bottom)) dz = ldf(Z,top,bottom) return quo(dv,dz) # Vector output", "Magnitude of a vector \"\"\" if (len(a) == 1): return", "DerivedGridFactory.createVectorDirection(V) def dot(V1,V2): \"\"\" Vector dot product <div class=jython> DOT", "function is the product of the rectangular aperature diffraction function", "</div> \"\"\" return sub(V1,V2) def LPIndex(u, v, z, t, top,", "\"\"\" return DerivedGridFactory.createMixingRatio(temp,rh) def relh(temp,mixr): \"\"\" Create Relative Humidity from", "function in the x and y directions. D is the", "response of 1/e for N * delta-x wave. Increasing N", "top, bottom): \"\"\" Magnitude of the vertical wind shear in", "def geo(z): \"\"\" geostrophic wind from height <div class=jython> GEO", "SAVS ( S ) = average of all non-missing grid", "7.268DUDZ + 0.718DTDN + 0.318DUDN - 2.52 </div> \"\"\" Z", "Average over whole grid <div class=jython> SAVG ( S )", "the derivative with respect to the domain's Y coordinate \"\"\"", "DerivedGridFactory.createLatitudeGrid(S) def lap(S): \"\"\" Laplacian operator <div class=jython> LAP (", "\"\"\" return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def qvec(S,V): \"\"\" Q-vector at a level", "VMUL (V1, V2) = [ u1*u2, v1*v2 ] </div> \"\"\"", "L = add(noUnit(Z), add(noUnit(HU), noUnit(HT))) L = (L - 2.520)*(-0.59)", "ZAV (S) = ( S (Z1) + S (Z2) +", "(ddx(vwind) + ddy(uwind))*0.318 L = add(noUnit(Z), add(noUnit(HU), noUnit(HT))) L =", "is the radius of influence in grid increments, increasing D", "= DIV ( GRAD (S) ) </div> \"\"\" grads =", "= strd(V) psi = .5*atn2(shear,strch) dxt = ddx(S) dyt =", "thrm(S, level1, level2, unit=None): \"\"\" Thermal wind <div class=jython> THRM", "= number of levels KNT = number of non-missing points", "calculate the vector layer average <div class=jython> VLDF(V) = [(u(level1)", "delta-x wave. Increasing N increases the smoothing. (default N=6) </div>", "column is stored at every point </div> \"\"\" return GridMath.applyFunctionOverLevels(S,", "<div class=jython> LDF ( S ) = S (level1) -", "grad(THTA) qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp = newName(quo(dot(dvdy(V),gradt),dtdp),\"qvecvdp\") return vecr(qvecudp,qvecvdp) def", "\"\"\" <div class=jython> Horizontal smoothing using normally distributed weights with", "EI = VWS X ( DEF + DIV) </div> \"\"\"", "DDY (v) ] </div> \"\"\" return vecr(ddy(ur(V)), ddy(vr(V))) def frnt(S,V):", "V, GRAD ( S ) ) </div> \"\"\" return add(mul(S,(div(V)))", "Divide the components of 2 vectors <div class=jython> VQUO (V1,", "\"\"\" Absolute Vorticity <div class=jython> AVOR ( V ) =", "= ASIN ( (-DDX (THTA) * COS (PSI) <br> -", "D (THTA) / DP ) ) * [ ( DOT", "(v(level1) - v(level2))/2] </div> \"\"\" return layerAverage(V, level1, level2, unit)", ") = u1 * u2 + v1 * v2 </div>", "North relative u component \"\"\" return ur(DerivedGridFactory.createTrueFlowVector(V)) def ur(V): \"\"\"", "relative u component \"\"\" return DerivedGridFactory.getUComponent(V) def vn(V): \"\"\" North", "Take the derivative with respect to the domain's Y coordinate", "return add(ur(product),vr(product)) def gwfs(S, N=6): \"\"\" <div class=jython> Horizontal smoothing", "XAV (S) = ( S (X1) + S (X2) +", "def latr(S): \"\"\" Latitudue all points in a grid \"\"\"", "(THTA) ) ), ( DOT ( DVDY (V), GRAD (THTA)", "<div class=jython> QVEC ( S, V ) = [ -", "DDY (THTA) * SIN (PSI))/ <br> MAG ( GRAD (THTA)", "int(D)) def corl(S): \"\"\" Coriolis Parameter for all points in", "- v(level2))/2] </div> \"\"\" return layerAverage(V, level1, level2, unit) def", "DST * DST) EI = mul(noUnit(VWS), add(noUnit(DEF), noUnit(DIV))) return setLevel(EI,", "(level1) - S (level2) </div> \"\"\" return layerDiff(S,level1,level2, unit); def", "\"\"\" Shear Deformation <div class=jython> SHR ( V ) =", "S (KZD) ) / KNT KZD = number of levels", "v1+v2 ] </div> \"\"\" return add(V1,V2) def vecn(S1,S2): \"\"\" Make", ") KXD = number of points in row XSUM for", "component \"\"\" return vr(DerivedGridFactory.createTrueFlowVector(V)) def vor(V): \"\"\" Relative Vorticity <div", "v refer to the grid relative components of a vector.", "\"\"\" return layerDiff(S,level1,level2, unit); def mag(*a): \"\"\" Magnitude of a", "vertical wind shear in a layer <div class=jython> WSHR (", "a 5-point smoother (see sm5s) \"\"\" return sm5s(V) def sm9v(V):", "<div class=jython> CROS ( V1, V2 ) = u1 *", ".25 * S (i,j) + .125 * ( S (i+1,j)", "/ m / s ) <div class=jython> QVCL ( THTA,", "(i-1,j) + S (i,j-1) ) </div> \"\"\" return GridUtil.smooth(S, \"SM5S\")", "] </div> \"\"\" return sub(V1,V2) def LPIndex(u, v, z, t,", "add(noUnit(HU), noUnit(HT))) L = (L - 2.520)*(-0.59) P= 1.0/(1.0 +", "</div> \"\"\" return GridUtil.smooth(S, \"GWFS\", int(N)) def jcbn(S1,S2): \"\"\" Jacobian", "where S can be any thermal paramenter, usually THTA. </div>", "y directions. D is the radius of influence in grid", "dz = ldf(Z,top,bottom) return quo(dv,dz) # Vector output def age(obs,geo):", "Scalar quantities def adv(S,V): \"\"\" Horizontal Advection, negative by convention", "class=jython> CROS ( V1, V2 ) = u1 * v2", "return DerivedGridFactory.createEquivalentPotentialTemperature(temp,rh) def un(V): \"\"\" North relative u component \"\"\"", "def dirr(V): \"\"\" Grid relative direction of a vector \"\"\"", "DDX (u), DDX (v) ] </div> \"\"\" return vecr(ddx(ur(V)), ddx(vr(V)))", "v (GEO(S)) (level1) - v (GEO(S)) (level2) ] </div> \"\"\"", "(v2) ) ] </div> \"\"\" return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def qvec(S,V): \"\"\"", "vn(V): \"\"\" North relative v component \"\"\" return vr(DerivedGridFactory.createTrueFlowVector(V)) def", "class=jython> LAP ( S ) = DIV ( GRAD (S)", "DVDY (V), GRAD (THTA) ) ) ] </div> \"\"\" dtdp", "def rectv(S, D=2): \"\"\" <div class=jython> Apply a rectangular aperature", "+ S (level2) ) / 2. </div> \"\"\" if level1", "GRAD (THTA) ) ) <br> PSI = 1/2 ATAN2 (", "[ u1*u2, v1*v2 ] </div> \"\"\" return mul(V1,V2) def vquo(V1,V2):", "\"\"\" return quo(V1,V2) def vsub(V1,V2): \"\"\" subtract the components of", "( GRAD (THTA) ) ) <br> PSI = 1/2 ATAN2", "/ s ) <div class=jython> QVEC ( S, V )", "In the following operators, scalar operands are named S<sub>n</sub> and", "Q-vector at a level ( K / m / s", "class=jython> LAV ( S ) = ( S (level1) +", "DerivedGridFactory.createGeostrophicWindVector(z) def grad(S): \"\"\" Gradient of a scalar <div class=jython>", "= [ u1/u2, v1/v2 ] </div> \"\"\" return quo(V1,V2) def", "\"\"\" return GridMath.atan2(S1,S2,WA) def add(S1,S2,WA=0): \"\"\" Addition <div class=jython> ADD", "add(relv,corl(relv)) def circs(S, D=2): \"\"\" <div class=jython> Apply a circular", "= average of all non-missing grid point values in the", "Jython built-ins (e.g. str). <P> In the following operators, scalar", "DSH + DST * DST) EI = mul(noUnit(VWS), add(noUnit(DEF), noUnit(DIV)))", "= DIRR ( un(v), vn(v) ) </div> \"\"\" return dirr(DerivedGridFactory.createTrueFlowVector(V))", "INAD ( V1, V2 ) = [ DOT ( V1,", ") = DDX ( v ) + DDY ( u", "(Y1) + S (Y2) + ... + S (KYD) )", "\"\"\" Make a vector from two components <div class=jython> VECR", "S (i,j) + .125 * ( S (i+1,j) + S", "height <div class=jython> GEO ( S ) = [ -", "\"RECT\", int(D)) def sm5v(V): \"\"\" Smooth a scalar grid using", "functions def atn2(S1,S2,WA=0): \"\"\" Wrapper for atan2 built-in <div class=jython>", "top, bottom, unit)*100.0 # uwind = getSliceAtLevel(u, top) vwind =", "u1*u2, v1*v2 ] </div> \"\"\" return mul(V1,V2) def vquo(V1,V2): \"\"\"", "theta and wind) \"\"\" return DerivedGridFactory.createPotentialVorticity(S,V) def rects(S, D=2): \"\"\"", "add the components of 2 vectors <div class=jython> VADD (V1,", "are named V<sub>n</sub>. Lowercase u and v refer to the", "[ DOT ( V1, GRAD (u2) ), DOT ( V1,", "DDX (S) + v * DDY (S) ) </div> \"\"\"", "D=2): \"\"\" <div class=jython> Apply a circular aperature smoothing to", "row <div class=jython> XAV (S) = ( S (X1) +", "<div class=jython> EI = VWS X ( DEF + DIV)", "HU = (ddx(vwind) + ddy(uwind))*0.318 L = add(noUnit(Z), add(noUnit(HU), noUnit(HT)))", "u (GEO(S)), v (OBS) - v (GEO(S)) ] </div> \"\"\"", ") </div> \"\"\" return add(ddx(vr(V)),ddy(ur(V))) def sm5s(S): \"\"\" Smooth a", "Smooth a scalar grid using a 9-point smoother <div class=jython>", "] </div> \"\"\" return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2)))) def qvec(S,V): \"\"\" Q-vector at", "a Cressman smoothing to the grid points. The smoothed value", "built-ins (e.g. str). <P> In the following operators, scalar operands", "Ratio from Temperature, RH (requires pressure domain) \"\"\" return DerivedGridFactory.createMixingRatio(temp,rh)", ".125 * ( S (i+1,j) + S (i,j+1) + S", "const / CORL ] </div> \"\"\" return DerivedGridFactory.createGeostrophicWindVector(z) def grad(S):", "XSUM (S) = ( S (X1) + S (X2) +", "\"\"\" Equivalent Potential Temperature from Temperature and Relative humidity (requires", "mul(S1,S2,WA=0): \"\"\" Multiply <div class=jython> MUL (S1, S2) = S1", "\"\"\" Ageostrophic wind <div class=jython> AGE ( S ) =", "mul(V1,V2) def vquo(V1,V2): \"\"\" Divide the components of 2 vectors", "the levels of a grid at all points <div class=jython>", "D=2) </div> \"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def sm5v(V): \"\"\"", "\"\"\" Mixing Ratio from Temperature, RH (requires pressure domain) \"\"\"", "= [ DOT ( V1, GRAD (u2) ), DOT (", "DP ) ) * [ ( DOT ( DVDX (V),", "\"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def dvdx(V): \"\"\" Partial x", "- u (GEO(S)), v (OBS) - v (GEO(S)) ] </div>", "rectv(S, D=2): \"\"\" <div class=jython> Apply a rectangular aperature smoothing", "def savs(S): \"\"\" Average over grid subset <div class=jython> SAVS", "product of the rectangular aperature diffraction function in the x", "( u ) + DDY ( v ) </div> \"\"\"", "\"\"\" return DerivedGridFactory.getUComponent(V) def vn(V): \"\"\" North relative v component", "the rectangular aperature diffraction function in the x and y", "to avoid conflicts with Jython built-ins (e.g. str). <P> In", "class=jython> YAV (S) = ( S (Y1) + S (Y2)", "\"\"\" Partial x derivative of a vector <div class=jython> DVDX", "+ S (KYD) ) / KNT KYD = number of", "( S ) ) </div> \"\"\" return add(mul(S,(div(V))) , dot(V,grad(S)))", "= u1 * u2 + v1 * v2 </div> \"\"\"", "wind from height <div class=jython> GEO ( S ) =", "</div> \"\"\" grads = grad(S) qvecu = newName(-dot(dvdx(V),grads),\"qvecu\") qvecv =", "sub(mul(ddx(S1),ddy(S2)),mul(ddy(S1),ddx(S2))) def latr(S): \"\"\" Latitudue all points in a grid", "( u ) - DDY ( v ) </div> \"\"\"", "Grid relative direction of a vector \"\"\" return DerivedGridFactory.createVectorDirection(V) def", ") * [ ( DOT ( DVDX (V), GRAD (THTA)", "a vertical column is stored at every point </div> \"\"\"", "\"\"\" return add(mul(S,(div(V))) , dot(V,grad(S))) def shr(V): \"\"\" Shear Deformation", "</div> \"\"\" return DerivedGridFactory.createGeostrophicWindVector(z) def grad(S): \"\"\" Gradient of a", "\"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X) def yav(S): \"\"\" Average along", "DOT ( DVDX (V), GRAD (S) ) ), - (", "(V) ** 2 + SHR (V) ** 2 ) **", "+ v * DDY (S) ) </div> \"\"\" return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S)))", "vwind = getSliceAtLevel(v, top) temp = newUnit(getSliceAtLevel(t, top), \"temperature\", \"celsius\")", "= grad(S) mgradt = mag(gradt) a = -cosd*dxt-sind*dyt beta =", "DVDX ( V ) = [ DDX (u), DDX (v)", "<div class=jython> AGE ( S ) = [ u (OBS)", ".5*atn2(shear,strch) dxt = ddx(S) dyt = ddy(S) cosd = cos(psi)", "HT = sqrt(ddx(temp)*ddx(temp) + ddy(temp)*ddy(temp))*0.718 HU = (ddx(vwind) + ddy(uwind))*0.318", "wave. Increasing N increases the smoothing. (default N=6) </div> \"\"\"", "the radius of influence in grid increments, increasing D increases", "of levels KNT = number of non-missing points in column", "Make a vector from two components <div class=jython> VECR (", "class=jython> AVG (S1, S2) = ( S1 + S2 )", "v, z, t, top, bottom, unit): \"\"\" calculate the wind", "MAG [ VLDF (V) ] / LDF (Z) </div> \"\"\"", "+ S (KZD) ) / KNT KZD = number of", ") <br> </div> \"\"\" shear = shr(V) strch = strd(V)", "to the domain's X coordinate \"\"\" return GridMath.ddx(S); def ddy(S):", "D=2) </div> \"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def cros(V1,V2): \"\"\"", "DerivedGridFactory.createPotentialVorticity(S,V) def rects(S, D=2): \"\"\" <div class=jython> Apply a rectangular", "def vsub(V1,V2): \"\"\" subtract the components of 2 vectors <div", "Ageostrophic wind <div class=jython> AGE ( S ) = [", "(S) + v * DDY (S) ) </div> \"\"\" return", "(level2) ) / 2. </div> \"\"\" if level1 == None:", "SIN (PSI))/ <br> MAG ( GRAD (THTA) ) ) <br>", "are named slightly different from GEMPAK functions to avoid conflicts", "</div> \"\"\" return layerDiff(V,level1,level2, unit) def vmul(V1,V2): \"\"\" Multiply the", "/ 2. </div> \"\"\" if level1 == None: return GridMath.applyFunctionOverLevels(S,", "9-point smoother (see sm9s) \"\"\" return sm9s(V) def thrm(S, level1,", "( DVDX (V), GRAD (S) ) ), - ( DOT", "return add(S1,S2)/2 def avor(V): \"\"\" Absolute Vorticity <div class=jython> AVOR", "in grid increments, increasing D increases the smoothing. (default D=2)", "deformation <div class=jython> DEF ( V ) = ( STRD", "S1 / S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR) </div>", "\"\"\" Q-vector at a level ( K / m /", "\"\"\" return GridUtil.smooth(S, \"RECT\", int(D)) def sm5v(V): \"\"\" Smooth a", "surrounding grid points. D is the radius of influence in", "\"\"\" <div class=jython> Apply a Cressman smoothing to the grid", "from Temperature and Relative humidity (requires pressure domain) \"\"\" return", "= windShear(u, v, z, top, bottom, unit)*7.268 uwind = getSliceAtLevel(u,", "sm5s) \"\"\" return sm5s(V) def sm9v(V): \"\"\" Smooth a scalar", "Meteorological PAcKage (GEMPAK). Note that the names are case sensitive", "return DerivedGridFactory.createVectorMagnitude(a[0]); else: return DerivedGridFactory.createVectorMagnitude(a[0],a[1]); def mixr(temp,rh): \"\"\" Mixing Ratio", "( S1 / S2 )<br> WA = use WEIGHTED_AVERAGE (default", "of a vector \"\"\" return DerivedGridFactory.createVectorDirection(V) def dot(V1,V2): \"\"\" Vector", "Potential Temperature from Temperature (requires pressure domain) \"\"\" return DerivedGridFactory.createPotentialTemperature(temp)", "S ) = [ u (GEO(S)) (level1) - u (GEO(S))", "def vmul(V1,V2): \"\"\" Multiply the components of 2 vectors <div", "all non-missing grid point values in the subset area </div>", "unit); def mag(*a): \"\"\" Magnitude of a vector \"\"\" if", "level1 == None: return GridMath.applyFunctionOverLevels(S, GridMath.FUNC_AVERAGE) else: return layerAverage(S,level1,level2, unit)", "avoid conflicts with Jython built-ins (e.g. str). <P> In the", "points <div class=jython> ZSUM (S) = ( S (Z1) +", "= mag(gradt) a = -cosd*dxt-sind*dyt beta = asin(a/mgradt) frnto =", "= VWS X ( DEF + DIV) </div> \"\"\" VWS", "= S1 / S2<br> WA = use WEIGHTED_AVERAGE (default NEAREST_NEIGHBOR)", "\"\"\" return GridUtil.smooth(S, \"GWFS\", int(N)) def jcbn(S1,S2): \"\"\" Jacobian Determinant", "S (level1) + S (level2) ) / 2. </div> \"\"\"", "def qvec(S,V): \"\"\" Q-vector at a level ( K /", "(default D=2) </div> \"\"\" return GridUtil.smooth(S, \"CRES\", int(D)) def dvdx(V):", ") ] </div> \"\"\" dtdp = GridMath.partial(THTA,2) gradt = grad(THTA)", "class=jython> VLDF(V) = [(u(level1) - u(level2))/2, (v(level1) - v(level2))/2] </div>", ") ), - ( DOT ( DVDY (V), GRAD (S)", "LAV ( S ) = ( S (level1) + S", "\"\"\" return -add(mul(ur(V),ddx(S)),mul(vr(V),ddy(S))) def avg(S1,S2): \"\"\" Average of 2 scalars", ".0625 * ( S (i+1,j+1) + S (i+1,j-1) + S", "+ .125 * ( S (i+1,j) + S (i,j+1) +", "\"\"\" return sub(ddx(ur(V)),ddy(vr(V))) def thta(temp): \"\"\" Potential Temperature from Temperature", "GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X) def xsum(S): \"\"\" Sum along a grid", "( S ) = .25 * S (i,j) + .125", "DVDX (V), GRAD (THTA) ) ), ( DOT ( DVDY", "</div> \"\"\" return vecr(ddx(S),ddy(S)) def gwfv(V, N=6): \"\"\" <div class=jython>", "relv = vor(V) return add(relv,corl(relv)) def circs(S, D=2): \"\"\" <div", "= [ u1+u2, v1+v2 ] </div> \"\"\" return add(V1,V2) def", "</div> \"\"\" return mul(V1,V2) def vquo(V1,V2): \"\"\" Divide the components", "\"CRES\", int(D)) def dvdx(V): \"\"\" Partial x derivative of a", "age(obs,geo): \"\"\" Ageostrophic wind <div class=jython> AGE ( S )", "LPIndex(u, v, z, t, top, bottom, unit): \"\"\" calculate the", "Diagnostics module. These functions are based on the grid diagnostics", "Humidity from Temperature, mixing ratio (requires pressure domain) \"\"\" return", "EllrodIndex(u, v, z, top, bottom, unit): \"\"\" calculate the wind", "relative direction of a vector <div class=jython> DIRN ( V", "* S (i,j) + .125 * ( S (i+1,j) +", "<div class=jython> DVDX ( V ) = [ DDX (u),", "Sum across the levels of a grid at all points", "def add(S1,S2,WA=0): \"\"\" Addition <div class=jython> ADD (S1, S2) =", "0.718DTDN + 0.318DUDN - 2.52 </div> \"\"\" Z = windShear(u,", "- ddy(vwind) DEF = sqrt(DSH * DSH + DST *", "true north vector from two components <div class=jython> VECN (", "v ) - DDY ( u ) </div> \"\"\" return", "across the levels of a grid at all points <div", "levels ZSUM for a vertical column is stored at every", "(i+1,j-1) + S (i-1,j+1) + S (i-1,j-1) ) </div> \"\"\"", "dtdp = GridMath.partial(THTA,2) gradt = grad(THTA) qvecudp = newName(quo(dot(dvdx(V),gradt),dtdp),\"qvecudp\") qvecvdp", "* const / CORL, DDX (S) * const / CORL", "DVDX (V), GRAD (S) ) ), - ( DOT (", "S ) = DIV ( GRAD (S) ) </div> \"\"\"", "from Temperature (requires pressure domain) \"\"\" return DerivedGridFactory.createPotentialTemperature(temp) def thte(temp,rh):", "in a grid \"\"\" return DerivedGridFactory.createLatitudeGrid(S) def lap(S): \"\"\" Laplacian", "def relh(temp,mixr): \"\"\" Create Relative Humidity from Temperature, mixing ratio", "dot(V1,V2): \"\"\" Vector dot product <div class=jython> DOT ( V1,", "class=jython> VSUB (V1, V2) = [ u1-u2, v1-v2 ] </div>", "V ) = DDX ( v ) - DDY (", "class=jython> ADD (S1, S2) = S1 + S2<br> WA =", "frnto def geo(z): \"\"\" geostrophic wind from height <div class=jython>", "= setLevel(P ,top, unit) return LP def EllrodIndex(u, v, z,", "</div> \"\"\" return makeTrueVector(S1,S2) def vecr(S1,S2): \"\"\" Make a vector", "slightly different from GEMPAK functions to avoid conflicts with Jython", "doc for the Grid Diagnostics module. These functions are based", "<div class=jython> VECN ( S1, S2 ) = [ S1,", "\"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_Y) def ysum(S): \"\"\" Sum along", "Divergence <div class=jython> DIV ( V ) = DDX (", "class=jython> AGE ( S ) = [ u (OBS) -", "vlav(V,level1,level2, unit=None): \"\"\" calculate the vector layer average <div class=jython>", "( V ) = DDX ( v ) - DDY", "= grad(S) qvecu = newName(-dot(dvdx(V),grads),\"qvecu\") qvecv = newName(-dot(dvdy(V),grads),\"qvecv\") return vecr(qvecu,qvecv)", "S1, S2 ] </div> \"\"\" return makeVector(S1,S2) def vlav(V,level1,level2, unit=None):", "Vector cross product magnitude <div class=jython> CROS ( V1, V2", "int(D)) def cresv(S, D=2): \"\"\" <div class=jython> Apply a Cressman", "<div class=jython> QVCL ( THTA, V ) = ( 1/(", "\"\"\" Make a true north vector from two components <div", "row XSUM for a row is stored at every point", "savg(S) def sdiv(S,V): \"\"\" Horizontal Flux Divergence <div class=jython> SDIV", "grad(S): \"\"\" Gradient of a scalar <div class=jython> GRAD (", "smoother (see sm9s) \"\"\" return sm9s(V) def thrm(S, level1, level2,", "def dirn(V): \"\"\" North relative direction of a vector <div", "] </div> \"\"\" return makeVector(S1,S2) def vlav(V,level1,level2, unit=None): \"\"\" calculate", "lav(S,level1=None,level2=None, unit=None): \"\"\" Layer Average of a multi layer grid", "S ), DDY ( S ) ] </div> \"\"\" return", ") = DIV ( GRAD (S) ) </div> \"\"\" grads", "</div> \"\"\" return layerDiff(S,level1,level2, unit); def mag(*a): \"\"\" Magnitude of", "ADV ( S, V ) = - ( u *", "Where: BETA = ASIN ( (-DDX (THTA) * COS (PSI)", "return DerivedGridFactory.createCoriolisGrid(S) def cress(S, D=2): \"\"\" <div class=jython> Apply a", "S (X1) + S (X2) + ... + S (KXD)", "Determinant <div class=jython> JCBN ( S1, S2 ) = DDX", "+ ... + S (KYD) ) KYD = number of", "vldf(V,level1,level2, unit=None): \"\"\" calculate the vector layer difference <div class=jython>", "<div class=jython> WSHR ( V ) = MAG [ VLDF", "discrete layers <div class=jython> LP = 7.268DUDZ + 0.718DTDN +", "point in that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X)", "points in a grid <div class=jython> CORL = TWO_OMEGA*sin(latr) </div>", "def EllrodIndex(u, v, z, top, bottom, unit): \"\"\" calculate the", "non-missing grid point values </div> \"\"\" return GridMath.applyFunctionToLevels(S, GridMath.FUNC_AVERAGE) def", "Q-vector ( K / m / s ) <div class=jython>", "N increases the smoothing. (default N=6) </div> \"\"\" return gwfs(V,", "the grid points. The smoothed value is given by a", "\"\"\" Smooth a scalar grid using a 9-point smoother <div", "layerDiff(S,level1,level2, unit); def mag(*a): \"\"\" Magnitude of a vector \"\"\"", "(Z2) + ... + S (KZD) ) / KNT KZD", "vecr(ddy(ur(V)), ddy(vr(V))) def frnt(S,V): \"\"\" Frontogenesis function from theta and", ") = [ u (GEO(S)) (level1) - u (GEO(S)) (level2),", "of influence in grid increments, increasing D increases the smoothing.", "row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_SUM, GridMath.AXIS_X) def yav(S): \"\"\"", "return mag(strd(V),shr(V)) def div(V): \"\"\" Horizontal Divergence <div class=jython> DIV", "uwind = getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top) temp =", "class=jython> GEO ( S ) = [ - DDY (S)", "(i-1,j) + S (i,j-1) ) + .0625 * ( S", "theoretical response of 1/e for N * delta-x wave. Increasing", "unit=None): \"\"\" Layer Difference <div class=jython> LDF ( S )", "DDX (S1) * DDY (S2) - DDY (S1) * DDX", "class=jython> Apply a Cressman smoothing to the grid points. The", "(OBS) - v (GEO(S)) ] </div> \"\"\" return sub(obs,geo) def", "SHR (V) ** 2 ) ** .5 </div> \"\"\" return", "vector operands are named V<sub>n</sub>. Lowercase u and v refer", "= getSliceAtLevel(u, top) vwind = getSliceAtLevel(v, top) DIV = (ddx(uwind)", "\"RECT\", int(D)) def savg(S): \"\"\" Average over whole grid <div", "\"\"\" Grid relative direction of a vector \"\"\" return DerivedGridFactory.createVectorDirection(V)", "\"\"\" return GridMath.divide(S1,S2,WA) def sub(S1,S2,WA=0): \"\"\" Subtract <div class=jython> SUB", "V ) = [ DDX (u), DDX (v) ] </div>", "\"\"\" Addition <div class=jython> ADD (S1, S2) = S1 +", "= number of points in row YSUM for a column", "( V1, GRAD (v2) ) ] </div> \"\"\" return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2))))", "sensitive and some are named slightly different from GEMPAK functions", "Gradient of a scalar <div class=jython> GRAD ( S )", "Coriolis Parameter for all points in a grid <div class=jython>", "[ DDX ( S ), DDY ( S ) ]", "(S1, S2) = S1 + S2<br> WA = use WEIGHTED_AVERAGE", "product = mul(V1,V2) return add(ur(product),vr(product)) def gwfs(S, N=6): \"\"\" <div", "] where S can be any thermal paramenter, usually THTA.", "that row. </div> \"\"\" return GridMath.applyFunctionToAxis(S, GridMath.FUNC_AVERAGE, GridMath.AXIS_X) def xsum(S):", "D is the radius of influence in grid increments, increasing", "KYD = number of points in row YSUM for a", "z, top, bottom, unit)*100.0 # uwind = getSliceAtLevel(u, top) vwind", "</div> \"\"\" return add(ddx(ur(V)),ddy(vr(V))) def dirn(V): \"\"\" North relative direction", "\"\"\" return ur(DerivedGridFactory.createTrueFlowVector(V)) def ur(V): \"\"\" Grid relative u component", "un(v), vn(v) ) </div> \"\"\" return dirr(DerivedGridFactory.createTrueFlowVector(V)) def dirr(V): \"\"\"", "return ur(DerivedGridFactory.createTrueFlowVector(V)) def ur(V): \"\"\" Grid relative u component \"\"\"", "GridMath.subtract(S1,S2,WA) # Scalar quantities def adv(S,V): \"\"\" Horizontal Advection, negative", "class=jython> VQUO (V1, V2) = [ u1/u2, v1/v2 ] </div>", "def savg(S): \"\"\" Average over whole grid <div class=jython> SAVG", "<div class=jython> XAV (S) = ( S (X1) + S", "* DST) EI = mul(noUnit(VWS), add(noUnit(DEF), noUnit(DIV))) return setLevel(EI, top,", "of a vector \"\"\" if (len(a) == 1): return DerivedGridFactory.createVectorMagnitude(a[0]);", "VSUB (V1, V2) = [ u1-u2, v1-v2 ] </div> \"\"\"", "const / CORL, DDX (S) * const / CORL ]", "DDX ( v ) - DDY ( u ) </div>", "return vecr(qvecudp,qvecvdp) def rectv(S, D=2): \"\"\" <div class=jython> Apply a", "shear in a layer <div class=jython> WSHR ( V )", "= [ u1*u2, v1*v2 ] </div> \"\"\" return mul(V1,V2) def", "GridUtil.smooth(S, \"CRES\", int(D)) def cros(V1,V2): \"\"\" Vector cross product magnitude", "</div> \"\"\" return add(mul(S,(div(V))) , dot(V,grad(S))) def shr(V): \"\"\" Shear" ]
[ "= bot.find_elements_by_class_name('tweet') links = [element.get_attribute('data-permalink-path') for element in tweets] #like", "Keys #to send key to browser import getpass #to get", "= input('Please enter keyword: ') user = twitter_bot(username, password) user.login()", "for link in links: bot.get('https://twitter.com/' + link) try: bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10)", "self.password = password self.bot = webdriver.Firefox() #login function def login(self):", "password.clear() #fill in email field email.send_keys(self.username) time.sleep(2) #fill in password", "email field email.send_keys(self.username) time.sleep(2) #fill in password field password.send_keys(<PASSWORD>) time.sleep(2)", "+ link) try: bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10) except Exception as ex: time.sleep(60)", "to wait for the browser to get the website time.sleep(3)", "document.body.scrollHeight)') time.sleep(10) tweets = bot.find_elements_by_class_name('tweet') links = [element.get_attribute('data-permalink-path') for element", "ex: time.sleep(60) if __name__ == '__main__': username = input('Email: ')", "#like posts for link in links: bot.get('https://twitter.com/' + link) try:", "element in tweets] #like posts for link in links: bot.get('https://twitter.com/'", "= username self.password = password self.bot = webdriver.Firefox() #login function", "') search = input('Please enter keyword: ') user = twitter_bot(username,", "password field #clear the email and password field just in", "== '__main__': username = input('Email: ') password = <PASSWORD>('Password: ')", "import time #to pause the program #a calss to store", "#a calss to store all twetter related objects and functions", "calss to store all twetter related objects and functions class", "'__main__': username = input('Email: ') password = <PASSWORD>('Password: ') search", "import Keys #to send key to browser import getpass #to", "functions class twitter_bot: def __init__(self, username, password): self.username = username", "self.bot #use keyword to search bot.get('https://twitter.com/search?q=' + search + '&src=typd')", "webdriver #to get the browser from selenium.webdriver.common.keys import Keys #to", "website time.sleep(3) email = bot.find_element_by_class_name('js-username-field') #get the email field password", "Exception as ex: time.sleep(60) if __name__ == '__main__': username =", "#to get password safely import time #to pause the program", "store all twetter related objects and functions class twitter_bot: def", "bot.get('https://twitter.com/login') #sleep to wait for the browser to get the", "password field password.send_keys(<PASSWORD>) time.sleep(2) #click the login button bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3)", "#get posts for i in range(0, 30): bot.execute_script('window.scrollTo(0, document.body.scrollHeight)') time.sleep(10)", "#clear the email and password field just in case of", "link) try: bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10) except Exception as ex: time.sleep(60) if", "__name__ == '__main__': username = input('Email: ') password = <PASSWORD>('Password:", "from selenium import webdriver #to get the browser from selenium.webdriver.common.keys", "email = bot.find_element_by_class_name('js-username-field') #get the email field password = bot.find_element_by_class_name('js-password-field')", "case of autofill email.clear() password.clear() #fill in email field email.send_keys(self.username)", "30): bot.execute_script('window.scrollTo(0, document.body.scrollHeight)') time.sleep(10) tweets = bot.find_elements_by_class_name('tweet') links = [element.get_attribute('data-permalink-path')", "all twetter related objects and functions class twitter_bot: def __init__(self,", "in range(0, 30): bot.execute_script('window.scrollTo(0, document.body.scrollHeight)') time.sleep(10) tweets = bot.find_elements_by_class_name('tweet') links", "except Exception as ex: time.sleep(60) if __name__ == '__main__': username", "time.sleep(60) if __name__ == '__main__': username = input('Email: ') password", "tweets = bot.find_elements_by_class_name('tweet') links = [element.get_attribute('data-permalink-path') for element in tweets]", "import webdriver #to get the browser from selenium.webdriver.common.keys import Keys", "time #to pause the program #a calss to store all", "import getpass #to get password safely import time #to pause", "bot.find_elements_by_class_name('tweet') links = [element.get_attribute('data-permalink-path') for element in tweets] #like posts", "the email field password = bot.find_element_by_class_name('js-password-field') #get the password field", "time.sleep(10) except Exception as ex: time.sleep(60) if __name__ == '__main__':", "the email and password field just in case of autofill", "and functions class twitter_bot: def __init__(self, username, password): self.username =", "for the browser to get the website time.sleep(3) email =", "getpass #to get password safely import time #to pause the", "<PASSWORD>('Password: ') search = input('Please enter keyword: ') user =", "time.sleep(2) #click the login button bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3) def like_tweet(self, search):", "= self.bot #use keyword to search bot.get('https://twitter.com/search?q=' + search +", "bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10) except Exception as ex: time.sleep(60) if __name__ ==", "program #a calss to store all twetter related objects and", "keyword to search bot.get('https://twitter.com/search?q=' + search + '&src=typd') bot.implicitly_wait(3) #get", "bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3) def like_tweet(self, search): bot = self.bot #use keyword", "password field just in case of autofill email.clear() password.clear() #fill", "password = bot.find_element_by_class_name('js-password-field') #get the password field #clear the email", "+ '&src=typd') bot.implicitly_wait(3) #get posts for i in range(0, 30):", "bot.implicitly_wait(3) #get posts for i in range(0, 30): bot.execute_script('window.scrollTo(0, document.body.scrollHeight)')", "to browser import getpass #to get password safely import time", "if __name__ == '__main__': username = input('Email: ') password =", "#fill in email field email.send_keys(self.username) time.sleep(2) #fill in password field", "class twitter_bot: def __init__(self, username, password): self.username = username self.password", "#click the login button bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3) def like_tweet(self, search): bot", "wait for the browser to get the website time.sleep(3) email", "password = <PASSWORD>('Password: ') search = input('Please enter keyword: ')", "password self.bot = webdriver.Firefox() #login function def login(self): bot =", "the browser to get the website time.sleep(3) email = bot.find_element_by_class_name('js-username-field')", "bot = self.bot #use keyword to search bot.get('https://twitter.com/search?q=' + search", "email field password = bot.find_element_by_class_name('js-password-field') #get the password field #clear", "time.sleep(3) def like_tweet(self, search): bot = self.bot #use keyword to", "posts for i in range(0, 30): bot.execute_script('window.scrollTo(0, document.body.scrollHeight)') time.sleep(10) tweets", "password safely import time #to pause the program #a calss", "def login(self): bot = self.bot bot.get('https://twitter.com/login') #sleep to wait for", "= self.bot bot.get('https://twitter.com/login') #sleep to wait for the browser to", "links = [element.get_attribute('data-permalink-path') for element in tweets] #like posts for", "= input('Email: ') password = <PASSWORD>('Password: ') search = input('Please", "= bot.find_element_by_class_name('js-username-field') #get the email field password = bot.find_element_by_class_name('js-password-field') #get", "autofill email.clear() password.clear() #fill in email field email.send_keys(self.username) time.sleep(2) #fill", "#to pause the program #a calss to store all twetter", "browser import getpass #to get password safely import time #to", "browser from selenium.webdriver.common.keys import Keys #to send key to browser", "the password field #clear the email and password field just", "to get the website time.sleep(3) email = bot.find_element_by_class_name('js-username-field') #get the", "field just in case of autofill email.clear() password.clear() #fill in", "login(self): bot = self.bot bot.get('https://twitter.com/login') #sleep to wait for the", "just in case of autofill email.clear() password.clear() #fill in email", "self.username = username self.password = password self.bot = webdriver.Firefox() #login", "browser to get the website time.sleep(3) email = bot.find_element_by_class_name('js-username-field') #get", "safely import time #to pause the program #a calss to", "def __init__(self, username, password): self.username = username self.password = password", "search + '&src=typd') bot.implicitly_wait(3) #get posts for i in range(0,", "pause the program #a calss to store all twetter related", "function def login(self): bot = self.bot bot.get('https://twitter.com/login') #sleep to wait", "time.sleep(10) tweets = bot.find_elements_by_class_name('tweet') links = [element.get_attribute('data-permalink-path') for element in", "bot.find_element_by_class_name('js-username-field') #get the email field password = bot.find_element_by_class_name('js-password-field') #get the", "from selenium.webdriver.common.keys import Keys #to send key to browser import", "search): bot = self.bot #use keyword to search bot.get('https://twitter.com/search?q=' +", "posts for link in links: bot.get('https://twitter.com/' + link) try: bot.find_element_by_class_name('HeartAnimation').click()", "of autofill email.clear() password.clear() #fill in email field email.send_keys(self.username) time.sleep(2)", "bot = self.bot bot.get('https://twitter.com/login') #sleep to wait for the browser", "email.send_keys(self.username) time.sleep(2) #fill in password field password.send_keys(<PASSWORD>) time.sleep(2) #click the", "+ search + '&src=typd') bot.implicitly_wait(3) #get posts for i in", "in tweets] #like posts for link in links: bot.get('https://twitter.com/' +", "key to browser import getpass #to get password safely import", "bot.find_element_by_class_name('js-password-field') #get the password field #clear the email and password", "#fill in password field password.send_keys(<PASSWORD>) time.sleep(2) #click the login button", "links: bot.get('https://twitter.com/' + link) try: bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10) except Exception as", "self.bot bot.get('https://twitter.com/login') #sleep to wait for the browser to get", "login button bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3) def like_tweet(self, search): bot = self.bot", "send key to browser import getpass #to get password safely", "twetter related objects and functions class twitter_bot: def __init__(self, username,", "#get the email field password = bot.find_element_by_class_name('js-password-field') #get the password", "bot.execute_script('window.scrollTo(0, document.body.scrollHeight)') time.sleep(10) tweets = bot.find_elements_by_class_name('tweet') links = [element.get_attribute('data-permalink-path') for", "#to send key to browser import getpass #to get password", "the website time.sleep(3) email = bot.find_element_by_class_name('js-username-field') #get the email field", "in case of autofill email.clear() password.clear() #fill in email field", "'&src=typd') bot.implicitly_wait(3) #get posts for i in range(0, 30): bot.execute_script('window.scrollTo(0,", "field #clear the email and password field just in case", "twitter_bot: def __init__(self, username, password): self.username = username self.password =", "selenium.webdriver.common.keys import Keys #to send key to browser import getpass", "password): self.username = username self.password = password self.bot = webdriver.Firefox()", "password.send_keys(<PASSWORD>) time.sleep(2) #click the login button bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3) def like_tweet(self,", "= password self.bot = webdriver.Firefox() #login function def login(self): bot", "= bot.find_element_by_class_name('js-password-field') #get the password field #clear the email and", "like_tweet(self, search): bot = self.bot #use keyword to search bot.get('https://twitter.com/search?q='", "') password = <PASSWORD>('Password: ') search = input('Please enter keyword:", "i in range(0, 30): bot.execute_script('window.scrollTo(0, document.body.scrollHeight)') time.sleep(10) tweets = bot.find_elements_by_class_name('tweet')", "search = input('Please enter keyword: ') user = twitter_bot(username, password)", "field password.send_keys(<PASSWORD>) time.sleep(2) #click the login button bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3) def", "the browser from selenium.webdriver.common.keys import Keys #to send key to", "#to get the browser from selenium.webdriver.common.keys import Keys #to send", "bot.get('https://twitter.com/' + link) try: bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10) except Exception as ex:", "link in links: bot.get('https://twitter.com/' + link) try: bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10) except", "selenium import webdriver #to get the browser from selenium.webdriver.common.keys import", "field email.send_keys(self.username) time.sleep(2) #fill in password field password.send_keys(<PASSWORD>) time.sleep(2) #click", "username self.password = password self.bot = webdriver.Firefox() #login function def", "time.sleep(3) email = bot.find_element_by_class_name('js-username-field') #get the email field password =", "objects and functions class twitter_bot: def __init__(self, username, password): self.username", "tweets] #like posts for link in links: bot.get('https://twitter.com/' + link)", "email and password field just in case of autofill email.clear()", "bot.get('https://twitter.com/search?q=' + search + '&src=typd') bot.implicitly_wait(3) #get posts for i", "username = input('Email: ') password = <PASSWORD>('Password: ') search =", "to search bot.get('https://twitter.com/search?q=' + search + '&src=typd') bot.implicitly_wait(3) #get posts", "= webdriver.Firefox() #login function def login(self): bot = self.bot bot.get('https://twitter.com/login')", "related objects and functions class twitter_bot: def __init__(self, username, password):", "button bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3) def like_tweet(self, search): bot = self.bot #use", "get the website time.sleep(3) email = bot.find_element_by_class_name('js-username-field') #get the email", "input('Email: ') password = <PASSWORD>('Password: ') search = input('Please enter", "and password field just in case of autofill email.clear() password.clear()", "input('Please enter keyword: ') user = twitter_bot(username, password) user.login() time.sleep(10)", "time.sleep(2) #fill in password field password.send_keys(<PASSWORD>) time.sleep(2) #click the login", "field password = bot.find_element_by_class_name('js-password-field') #get the password field #clear the", "range(0, 30): bot.execute_script('window.scrollTo(0, document.body.scrollHeight)') time.sleep(10) tweets = bot.find_elements_by_class_name('tweet') links =", "in email field email.send_keys(self.username) time.sleep(2) #fill in password field password.send_keys(<PASSWORD>)", "= [element.get_attribute('data-permalink-path') for element in tweets] #like posts for link", "for element in tweets] #like posts for link in links:", "in links: bot.get('https://twitter.com/' + link) try: bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10) except Exception", "email.clear() password.clear() #fill in email field email.send_keys(self.username) time.sleep(2) #fill in", "[element.get_attribute('data-permalink-path') for element in tweets] #like posts for link in", "get password safely import time #to pause the program #a", "#use keyword to search bot.get('https://twitter.com/search?q=' + search + '&src=typd') bot.implicitly_wait(3)", "__init__(self, username, password): self.username = username self.password = password self.bot", "self.bot = webdriver.Firefox() #login function def login(self): bot = self.bot", "to store all twetter related objects and functions class twitter_bot:", "#sleep to wait for the browser to get the website", "= <PASSWORD>('Password: ') search = input('Please enter keyword: ') user", "search bot.get('https://twitter.com/search?q=' + search + '&src=typd') bot.implicitly_wait(3) #get posts for", "the login button bot.find_element_by_class_name(\"EdgeButtom--medium\").click() time.sleep(3) def like_tweet(self, search): bot =", "#get the password field #clear the email and password field", "#login function def login(self): bot = self.bot bot.get('https://twitter.com/login') #sleep to", "get the browser from selenium.webdriver.common.keys import Keys #to send key", "username, password): self.username = username self.password = password self.bot =", "def like_tweet(self, search): bot = self.bot #use keyword to search", "the program #a calss to store all twetter related objects", "in password field password.send_keys(<PASSWORD>) time.sleep(2) #click the login button bot.find_element_by_class_name(\"EdgeButtom--medium\").click()", "enter keyword: ') user = twitter_bot(username, password) user.login() time.sleep(10) user.like_tweet(search)", "try: bot.find_element_by_class_name('HeartAnimation').click() time.sleep(10) except Exception as ex: time.sleep(60) if __name__", "webdriver.Firefox() #login function def login(self): bot = self.bot bot.get('https://twitter.com/login') #sleep", "as ex: time.sleep(60) if __name__ == '__main__': username = input('Email:", "for i in range(0, 30): bot.execute_script('window.scrollTo(0, document.body.scrollHeight)') time.sleep(10) tweets =" ]
[ "name), if None, will use the last layer before average", "np.uint8(0.6*img + 0.4 * cam[:,:,:3]) overlay = Image.fromarray(overlay) if overlay.size", "= model.to(device) self.model = model self.device = device self.feature_maps =", "return outputs.detach(), overlay def get_layer_name(self, model): layer_name = None for", "isinstance(img, np.ndarray): img = np.asarray(img) img_size = img.shape[:2][::-1] # w,", "close_some_grad=True): if layer_name is None: layer_name = self.get_layer_name(model) if layer_name", "break model = model.to(device) self.model = model self.device = device", "cam.to(dtype=torch.uint8, device=\"cpu\") cam = cam.numpy().transpose(1,2,0) cam = cv.resize(cam, img.size[:2], interpolation=4)", "= None for n, m in model.named_children(): for sub_n, sub_m", "will use the last layer before average pooling , default", "= model self.device = device self.feature_maps = {} self.gradients =", "import cm import numpy as np class GradCAM: \"\"\" ####", "overlay.resize(img_size, Image.BILINEAR) return outputs.detach(), overlay def get_layer_name(self, model): layer_name =", "\"\"\" #### Args: layer_name: module name (not child name), if", "from matplotlib import cm import numpy as np class GradCAM:", "torch import torch.nn as nn from torch.nn import functional as", "sub_n, sub_m in m.named_modules(): if '.'.join((n, sub_n)) == layer_name: sub_m.register_forward_hook(self.forward_hook)", "layer_name = tmp tmp = '.'.join((n, sub_n)) return layer_name def", "\"\"\" def __init__(self, model, device, layer_name=None, close_some_grad=True): if layer_name is", "self.feature_maps[\"output\"] # \"gradients\" is a tuple with one item grad_weights", "\"gradients\" is a tuple with one item grad_weights = self.gradients[\"output\"][0]", "1x2 outputs[0][pred_label].backward() with torch.no_grad(): feature_maps = self.feature_maps[\"output\"] # \"gradients\" is", "* 255 cam = cam.to(dtype=torch.uint8, device=\"cpu\") cam = cam.numpy().transpose(1,2,0) cam", "in model.named_children(): if close_some_grad: m.requires_grad_(False) for sub_n, sub_m in m.named_modules():", "if not isinstance(img, np.ndarray): img = np.asarray(img) img_size = img.shape[:2][::-1]", "= tmp tmp = '.'.join((n, sub_n)) return layer_name def forward_hook(self,", "m.named_modules(): if isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name = tmp tmp =", "= device self.feature_maps = {} self.gradients = {} def get_heatmap(self,", "#self.feature_maps[\"input\"] = x self.feature_maps[\"output\"] = y def backward_hook(self, module, x,", "shape = 1x2 outputs[0][pred_label].backward() with torch.no_grad(): feature_maps = self.feature_maps[\"output\"] #", "cam = cam.to(dtype=torch.uint8, device=\"cpu\") cam = cam.numpy().transpose(1,2,0) cam = cv.resize(cam,", "m.named_modules(): if '.'.join((n, sub_n)) == layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break", "self.model(img_tensor) _, pred_label = outputs.max(1) # outputs shape = 1x2", "# outputs shape = 1x2 outputs[0][pred_label].backward() with torch.no_grad(): feature_maps =", "outputs.max(1) # outputs shape = 1x2 outputs[0][pred_label].backward() with torch.no_grad(): feature_maps", "if layer_name is None: layer_name = self.get_layer_name(model) if layer_name is", "specify 'layer_name'\" ) for n, m in model.named_children(): if close_some_grad:", "tuple with one item grad_weights = self.gradients[\"output\"][0] h, w =", "= np.uint8(255 * cm.get_cmap(\"jet\")(cam.squeeze())) if not isinstance(img, np.ndarray): img =", "nn from torch.nn import functional as F from PIL import", "grad_weights.size()[-2:] grad_weights = grad_weights.sum((2,3), True) / (h * w) cam", "= outputs.max(1) # outputs shape = 1x2 outputs[0][pred_label].backward() with torch.no_grad():", "m.requires_grad_(True) break model = model.to(device) self.model = model self.device =", "True) cam = cam / cam.max() * 255 cam =", "= cam.to(dtype=torch.uint8, device=\"cpu\") cam = cam.numpy().transpose(1,2,0) cam = cv.resize(cam, img.size[:2],", "img_size = img.shape[:2][::-1] # w, h overlay = np.uint8(0.6*img +", "is no global average pooling layer, plz specify 'layer_name'\" )", "= {} def get_heatmap(self, img, img_tensor): self.model.zero_grad() img_tensor = img_tensor.to(self.device)", "in model.named_children(): for sub_n, sub_m in m.named_modules(): if isinstance(sub_m, (nn.AdaptiveAvgPool2d,", "import numpy as np class GradCAM: \"\"\" #### Args: layer_name:", "overlay = np.uint8(0.6*img + 0.4 * cam[:,:,:3]) overlay = Image.fromarray(overlay)", "if overlay.size != img_size: overlay = overlay.resize(img_size, Image.BILINEAR) return outputs.detach(),", "= self.get_layer_name(model) if layer_name is None: raise ValueError( \"There is", "overlay = Image.fromarray(overlay) if overlay.size != img_size: overlay = overlay.resize(img_size,", "np.asarray(img) img_size = img.shape[:2][::-1] # w, h overlay = np.uint8(0.6*img", "sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break model = model.to(device) self.model = model self.device", "functional as F from PIL import Image import cv2 as", "pred_label = outputs.max(1) # outputs shape = 1x2 outputs[0][pred_label].backward() with", "* feature_maps).sum(1) F.relu(cam, True) cam = cam / cam.max() *", "sub_n)) return layer_name def forward_hook(self, module, x, y): #self.feature_maps[\"input\"] =", "the last layer before average pooling , default is None", "(grad_weights * feature_maps).sum(1) F.relu(cam, True) cam = cam / cam.max()", "cam = cv.resize(cam, img.size[:2], interpolation=4) cam = np.uint8(255 * cm.get_cmap(\"jet\")(cam.squeeze()))", "m in model.named_children(): for sub_n, sub_m in m.named_modules(): if isinstance(sub_m,", "layer before average pooling , default is None \"\"\" def", "with one item grad_weights = self.gradients[\"output\"][0] h, w = grad_weights.size()[-2:]", "/ (h * w) cam = (grad_weights * feature_maps).sum(1) F.relu(cam,", "feature_maps = self.feature_maps[\"output\"] # \"gradients\" is a tuple with one", "torch.nn as nn from torch.nn import functional as F from", "= img.shape[:2][::-1] # w, h overlay = np.uint8(0.6*img + 0.4", "# w, h overlay = np.uint8(0.6*img + 0.4 * cam[:,:,:3])", "outputs = self.model(img_tensor) _, pred_label = outputs.max(1) # outputs shape", "cam = np.uint8(255 * cm.get_cmap(\"jet\")(cam.squeeze())) if not isinstance(img, np.ndarray): img", "0.4 * cam[:,:,:3]) overlay = Image.fromarray(overlay) if overlay.size != img_size:", "in m.named_modules(): if isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name = tmp tmp", "if '.'.join((n, sub_n)) == layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break model", "= y def backward_hook(self, module, x, y): #self.gradients[\"input\"] = x", "img_tensor = img_tensor.to(self.device) outputs = self.model(img_tensor) _, pred_label = outputs.max(1)", "# \"gradients\" is a tuple with one item grad_weights =", "model self.device = device self.feature_maps = {} self.gradients = {}", "is a tuple with one item grad_weights = self.gradients[\"output\"][0] h,", "* cm.get_cmap(\"jet\")(cam.squeeze())) if not isinstance(img, np.ndarray): img = np.asarray(img) img_size", "ValueError( \"There is no global average pooling layer, plz specify", "GradCAM: \"\"\" #### Args: layer_name: module name (not child name),", "+ 0.4 * cam[:,:,:3]) overlay = Image.fromarray(overlay) if overlay.size !=", "interpolation=4) cam = np.uint8(255 * cm.get_cmap(\"jet\")(cam.squeeze())) if not isinstance(img, np.ndarray):", "average pooling layer, plz specify 'layer_name'\" ) for n, m", "F.relu(cam, True) cam = cam / cam.max() * 255 cam", "before average pooling , default is None \"\"\" def __init__(self,", "cv.resize(cam, img.size[:2], interpolation=4) cam = np.uint8(255 * cm.get_cmap(\"jet\")(cam.squeeze())) if not", "= self.feature_maps[\"output\"] # \"gradients\" is a tuple with one item", "name (not child name), if None, will use the last", "grad_weights.sum((2,3), True) / (h * w) cam = (grad_weights *", "np.uint8(255 * cm.get_cmap(\"jet\")(cam.squeeze())) if not isinstance(img, np.ndarray): img = np.asarray(img)", "= np.uint8(0.6*img + 0.4 * cam[:,:,:3]) overlay = Image.fromarray(overlay) if", "= Image.fromarray(overlay) if overlay.size != img_size: overlay = overlay.resize(img_size, Image.BILINEAR)", "get_layer_name(self, model): layer_name = None for n, m in model.named_children():", "as F from PIL import Image import cv2 as cv", "True) / (h * w) cam = (grad_weights * feature_maps).sum(1)", "self.feature_maps = {} self.gradients = {} def get_heatmap(self, img, img_tensor):", "def get_layer_name(self, model): layer_name = None for n, m in", "= cam / cam.max() * 255 cam = cam.to(dtype=torch.uint8, device=\"cpu\")", "cv from matplotlib import cm import numpy as np class", "pooling layer, plz specify 'layer_name'\" ) for n, m in", "close_some_grad: m.requires_grad_(False) for sub_n, sub_m in m.named_modules(): if '.'.join((n, sub_n))", "F from PIL import Image import cv2 as cv from", "= 1x2 outputs[0][pred_label].backward() with torch.no_grad(): feature_maps = self.feature_maps[\"output\"] # \"gradients\"", "sub_m in m.named_modules(): if '.'.join((n, sub_n)) == layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook)", "x, y): #self.gradients[\"input\"] = x self.gradients[\"output\"] = y self.gradients[\"output\"] =", "get_heatmap(self, img, img_tensor): self.model.zero_grad() img_tensor = img_tensor.to(self.device) outputs = self.model(img_tensor)", "isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name = tmp tmp = '.'.join((n, sub_n))", "cam / cam.max() * 255 cam = cam.to(dtype=torch.uint8, device=\"cpu\") cam", "tmp tmp = '.'.join((n, sub_n)) return layer_name def forward_hook(self, module,", "is None \"\"\" def __init__(self, model, device, layer_name=None, close_some_grad=True): if", "w = grad_weights.size()[-2:] grad_weights = grad_weights.sum((2,3), True) / (h *", "def forward_hook(self, module, x, y): #self.feature_maps[\"input\"] = x self.feature_maps[\"output\"] =", "'layer_name'\" ) for n, m in model.named_children(): if close_some_grad: m.requires_grad_(False)", "(nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name = tmp tmp = '.'.join((n, sub_n)) return", "cam[:,:,:3]) overlay = Image.fromarray(overlay) if overlay.size != img_size: overlay =", "feature_maps).sum(1) F.relu(cam, True) cam = cam / cam.max() * 255", "import Image import cv2 as cv from matplotlib import cm", "default is None \"\"\" def __init__(self, model, device, layer_name=None, close_some_grad=True):", "= self.model(img_tensor) _, pred_label = outputs.max(1) # outputs shape =", "cv2 as cv from matplotlib import cm import numpy as", "as nn from torch.nn import functional as F from PIL", "import torch.nn as nn from torch.nn import functional as F", "as np class GradCAM: \"\"\" #### Args: layer_name: module name", "if layer_name is None: raise ValueError( \"There is no global", "if close_some_grad: m.requires_grad_(False) for sub_n, sub_m in m.named_modules(): if '.'.join((n,", "= grad_weights.size()[-2:] grad_weights = grad_weights.sum((2,3), True) / (h * w)", "grad_weights = grad_weights.sum((2,3), True) / (h * w) cam =", "255 cam = cam.to(dtype=torch.uint8, device=\"cpu\") cam = cam.numpy().transpose(1,2,0) cam =", "sub_n)) == layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break model = model.to(device)", "x self.feature_maps[\"output\"] = y def backward_hook(self, module, x, y): #self.gradients[\"input\"]", "m in model.named_children(): if close_some_grad: m.requires_grad_(False) for sub_n, sub_m in", "'.'.join((n, sub_n)) return layer_name def forward_hook(self, module, x, y): #self.feature_maps[\"input\"]", "overlay.size != img_size: overlay = overlay.resize(img_size, Image.BILINEAR) return outputs.detach(), overlay", "n, m in model.named_children(): if close_some_grad: m.requires_grad_(False) for sub_n, sub_m", "def backward_hook(self, module, x, y): #self.gradients[\"input\"] = x self.gradients[\"output\"] =", "is None: raise ValueError( \"There is no global average pooling", "(h * w) cam = (grad_weights * feature_maps).sum(1) F.relu(cam, True)", "np class GradCAM: \"\"\" #### Args: layer_name: module name (not", "None: raise ValueError( \"There is no global average pooling layer,", "import functional as F from PIL import Image import cv2", "layer_name is None: raise ValueError( \"There is no global average", "self.model.zero_grad() img_tensor = img_tensor.to(self.device) outputs = self.model(img_tensor) _, pred_label =", "= grad_weights.sum((2,3), True) / (h * w) cam = (grad_weights", "sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break model = model.to(device) self.model = model", "= cam.numpy().transpose(1,2,0) cam = cv.resize(cam, img.size[:2], interpolation=4) cam = np.uint8(255", "sub_n, sub_m in m.named_modules(): if isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name =", "y): #self.feature_maps[\"input\"] = x self.feature_maps[\"output\"] = y def backward_hook(self, module,", "model.to(device) self.model = model self.device = device self.feature_maps = {}", "use the last layer before average pooling , default is", "item grad_weights = self.gradients[\"output\"][0] h, w = grad_weights.size()[-2:] grad_weights =", "layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break model = model.to(device) self.model =", "= self.gradients[\"output\"][0] h, w = grad_weights.size()[-2:] grad_weights = grad_weights.sum((2,3), True)", "* w) cam = (grad_weights * feature_maps).sum(1) F.relu(cam, True) cam", "img_tensor.to(self.device) outputs = self.model(img_tensor) _, pred_label = outputs.max(1) # outputs", "w, h overlay = np.uint8(0.6*img + 0.4 * cam[:,:,:3]) overlay", "cm import numpy as np class GradCAM: \"\"\" #### Args:", "None, will use the last layer before average pooling ,", "cam.max() * 255 cam = cam.to(dtype=torch.uint8, device=\"cpu\") cam = cam.numpy().transpose(1,2,0)", "Args: layer_name: module name (not child name), if None, will", "for n, m in model.named_children(): for sub_n, sub_m in m.named_modules():", "\"There is no global average pooling layer, plz specify 'layer_name'\"", "= np.asarray(img) img_size = img.shape[:2][::-1] # w, h overlay =", "for sub_n, sub_m in m.named_modules(): if '.'.join((n, sub_n)) == layer_name:", "'.'.join((n, sub_n)) == layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break model =", "if isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name = tmp tmp = '.'.join((n,", "class GradCAM: \"\"\" #### Args: layer_name: module name (not child", "import cv2 as cv from matplotlib import cm import numpy", "import torch import torch.nn as nn from torch.nn import functional", "self.model = model self.device = device self.feature_maps = {} self.gradients", "from torch.nn import functional as F from PIL import Image", "model): layer_name = None for n, m in model.named_children(): for", "for sub_n, sub_m in m.named_modules(): if isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name", "model = model.to(device) self.model = model self.device = device self.feature_maps", "module name (not child name), if None, will use the", "!= img_size: overlay = overlay.resize(img_size, Image.BILINEAR) return outputs.detach(), overlay def", "PIL import Image import cv2 as cv from matplotlib import", "layer_name def forward_hook(self, module, x, y): #self.feature_maps[\"input\"] = x self.feature_maps[\"output\"]", "outputs.detach(), overlay def get_layer_name(self, model): layer_name = None for n,", "no global average pooling layer, plz specify 'layer_name'\" ) for", "overlay def get_layer_name(self, model): layer_name = None for n, m", "grad_weights = self.gradients[\"output\"][0] h, w = grad_weights.size()[-2:] grad_weights = grad_weights.sum((2,3),", "as cv from matplotlib import cm import numpy as np", "if None, will use the last layer before average pooling", "h overlay = np.uint8(0.6*img + 0.4 * cam[:,:,:3]) overlay =", "pooling , default is None \"\"\" def __init__(self, model, device,", "img, img_tensor): self.model.zero_grad() img_tensor = img_tensor.to(self.device) outputs = self.model(img_tensor) _,", "h, w = grad_weights.size()[-2:] grad_weights = grad_weights.sum((2,3), True) / (h", "img = np.asarray(img) img_size = img.shape[:2][::-1] # w, h overlay", "Image.BILINEAR) return outputs.detach(), overlay def get_layer_name(self, model): layer_name = None", "def get_heatmap(self, img, img_tensor): self.model.zero_grad() img_tensor = img_tensor.to(self.device) outputs =", "layer_name: module name (not child name), if None, will use", "module, x, y): #self.feature_maps[\"input\"] = x self.feature_maps[\"output\"] = y def", "self.get_layer_name(model) if layer_name is None: raise ValueError( \"There is no", ") for n, m in model.named_children(): if close_some_grad: m.requires_grad_(False) for", "not isinstance(img, np.ndarray): img = np.asarray(img) img_size = img.shape[:2][::-1] #", "None: layer_name = self.get_layer_name(model) if layer_name is None: raise ValueError(", "self.device = device self.feature_maps = {} self.gradients = {} def", "self.gradients = {} def get_heatmap(self, img, img_tensor): self.model.zero_grad() img_tensor =", "cam = (grad_weights * feature_maps).sum(1) F.relu(cam, True) cam = cam", ", default is None \"\"\" def __init__(self, model, device, layer_name=None,", "np.ndarray): img = np.asarray(img) img_size = img.shape[:2][::-1] # w, h", "img_tensor): self.model.zero_grad() img_tensor = img_tensor.to(self.device) outputs = self.model(img_tensor) _, pred_label", "cam.numpy().transpose(1,2,0) cam = cv.resize(cam, img.size[:2], interpolation=4) cam = np.uint8(255 *", "= '.'.join((n, sub_n)) return layer_name def forward_hook(self, module, x, y):", "Image import cv2 as cv from matplotlib import cm import", "outputs shape = 1x2 outputs[0][pred_label].backward() with torch.no_grad(): feature_maps = self.feature_maps[\"output\"]", "Image.fromarray(overlay) if overlay.size != img_size: overlay = overlay.resize(img_size, Image.BILINEAR) return", "_, pred_label = outputs.max(1) # outputs shape = 1x2 outputs[0][pred_label].backward()", "cam = cam.numpy().transpose(1,2,0) cam = cv.resize(cam, img.size[:2], interpolation=4) cam =", "layer_name=None, close_some_grad=True): if layer_name is None: layer_name = self.get_layer_name(model) if", "device=\"cpu\") cam = cam.numpy().transpose(1,2,0) cam = cv.resize(cam, img.size[:2], interpolation=4) cam", "model.named_children(): for sub_n, sub_m in m.named_modules(): if isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)):", "layer_name is None: layer_name = self.get_layer_name(model) if layer_name is None:", "average pooling , default is None \"\"\" def __init__(self, model,", "global average pooling layer, plz specify 'layer_name'\" ) for n,", "with torch.no_grad(): feature_maps = self.feature_maps[\"output\"] # \"gradients\" is a tuple", "device self.feature_maps = {} self.gradients = {} def get_heatmap(self, img,", "img.size[:2], interpolation=4) cam = np.uint8(255 * cm.get_cmap(\"jet\")(cam.squeeze())) if not isinstance(img,", "one item grad_weights = self.gradients[\"output\"][0] h, w = grad_weights.size()[-2:] grad_weights", "n, m in model.named_children(): for sub_n, sub_m in m.named_modules(): if", "model, device, layer_name=None, close_some_grad=True): if layer_name is None: layer_name =", "== layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True) break model = model.to(device) self.model", "{} self.gradients = {} def get_heatmap(self, img, img_tensor): self.model.zero_grad() img_tensor", "/ cam.max() * 255 cam = cam.to(dtype=torch.uint8, device=\"cpu\") cam =", "layer_name = None for n, m in model.named_children(): for sub_n,", "numpy as np class GradCAM: \"\"\" #### Args: layer_name: module", "y): #self.gradients[\"input\"] = x self.gradients[\"output\"] = y self.gradients[\"output\"] = y", "child name), if None, will use the last layer before", "raise ValueError( \"There is no global average pooling layer, plz", "def __init__(self, model, device, layer_name=None, close_some_grad=True): if layer_name is None:", "= overlay.resize(img_size, Image.BILINEAR) return outputs.detach(), overlay def get_layer_name(self, model): layer_name", "last layer before average pooling , default is None \"\"\"", "{} def get_heatmap(self, img, img_tensor): self.model.zero_grad() img_tensor = img_tensor.to(self.device) outputs", "self.gradients[\"output\"][0] h, w = grad_weights.size()[-2:] grad_weights = grad_weights.sum((2,3), True) /", "img_size: overlay = overlay.resize(img_size, Image.BILINEAR) return outputs.detach(), overlay def get_layer_name(self,", "y def backward_hook(self, module, x, y): #self.gradients[\"input\"] = x self.gradients[\"output\"]", "backward_hook(self, module, x, y): #self.gradients[\"input\"] = x self.gradients[\"output\"] = y", "m.requires_grad_(False) for sub_n, sub_m in m.named_modules(): if '.'.join((n, sub_n)) ==", "is None: layer_name = self.get_layer_name(model) if layer_name is None: raise", "None for n, m in model.named_children(): for sub_n, sub_m in", "device, layer_name=None, close_some_grad=True): if layer_name is None: layer_name = self.get_layer_name(model)", "module, x, y): #self.gradients[\"input\"] = x self.gradients[\"output\"] = y self.gradients[\"output\"]", "tmp = '.'.join((n, sub_n)) return layer_name def forward_hook(self, module, x,", "outputs[0][pred_label].backward() with torch.no_grad(): feature_maps = self.feature_maps[\"output\"] # \"gradients\" is a", "torch.no_grad(): feature_maps = self.feature_maps[\"output\"] # \"gradients\" is a tuple with", "x, y): #self.feature_maps[\"input\"] = x self.feature_maps[\"output\"] = y def backward_hook(self,", "for n, m in model.named_children(): if close_some_grad: m.requires_grad_(False) for sub_n,", "= img_tensor.to(self.device) outputs = self.model(img_tensor) _, pred_label = outputs.max(1) #", "None \"\"\" def __init__(self, model, device, layer_name=None, close_some_grad=True): if layer_name", "(not child name), if None, will use the last layer", "* cam[:,:,:3]) overlay = Image.fromarray(overlay) if overlay.size != img_size: overlay", "= {} self.gradients = {} def get_heatmap(self, img, img_tensor): self.model.zero_grad()", "= x self.feature_maps[\"output\"] = y def backward_hook(self, module, x, y):", "= cv.resize(cam, img.size[:2], interpolation=4) cam = np.uint8(255 * cm.get_cmap(\"jet\")(cam.squeeze())) if", "overlay = overlay.resize(img_size, Image.BILINEAR) return outputs.detach(), overlay def get_layer_name(self, model):", "in m.named_modules(): if '.'.join((n, sub_n)) == layer_name: sub_m.register_forward_hook(self.forward_hook) sub_m.register_full_backward_hook(self.backward_hook) m.requires_grad_(True)", "cm.get_cmap(\"jet\")(cam.squeeze())) if not isinstance(img, np.ndarray): img = np.asarray(img) img_size =", "layer_name = self.get_layer_name(model) if layer_name is None: raise ValueError( \"There", "a tuple with one item grad_weights = self.gradients[\"output\"][0] h, w", "torch.nn import functional as F from PIL import Image import", "= (grad_weights * feature_maps).sum(1) F.relu(cam, True) cam = cam /", "sub_m in m.named_modules(): if isinstance(sub_m, (nn.AdaptiveAvgPool2d, nn.AvgPool2d)): layer_name = tmp", "forward_hook(self, module, x, y): #self.feature_maps[\"input\"] = x self.feature_maps[\"output\"] = y", "plz specify 'layer_name'\" ) for n, m in model.named_children(): if", "layer, plz specify 'layer_name'\" ) for n, m in model.named_children():", "nn.AvgPool2d)): layer_name = tmp tmp = '.'.join((n, sub_n)) return layer_name", "self.feature_maps[\"output\"] = y def backward_hook(self, module, x, y): #self.gradients[\"input\"] =", "matplotlib import cm import numpy as np class GradCAM: \"\"\"", "#### Args: layer_name: module name (not child name), if None,", "w) cam = (grad_weights * feature_maps).sum(1) F.relu(cam, True) cam =", "from PIL import Image import cv2 as cv from matplotlib", "cam = cam / cam.max() * 255 cam = cam.to(dtype=torch.uint8,", "img.shape[:2][::-1] # w, h overlay = np.uint8(0.6*img + 0.4 *", "model.named_children(): if close_some_grad: m.requires_grad_(False) for sub_n, sub_m in m.named_modules(): if", "__init__(self, model, device, layer_name=None, close_some_grad=True): if layer_name is None: layer_name", "return layer_name def forward_hook(self, module, x, y): #self.feature_maps[\"input\"] = x" ]
[ "intra_blob(sub_blob, rdn + 1 + 1 / blob.Ls, rng=rng, fig=1,", "S=L, Ly=1) new_stack.Py_.append(P) # Py_: vertical buffer of Ps new_stack.down_connect_cnt", "M if negative sign? if sub_blob.sign: if sub_blob.Dert['M'] - borrow", "dert__, # box of derts, each = i, idy, idx,", "vertical stacks of Ps stack_binder = AdjBinder(CDeepStack) if render: streamer", "and sub-clustering: der+: incremental derivation cross-comp in high-variation edge areas", "_x0 < xn and x0 < _xn: # x overlap", "down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) else: if len(up_connect_) ==", "iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) # initialize P params:", "AdjBinder(CDeepStack) if render: streamer = BlobStreamer(CDeepBlob, crit__, mask) if render:", "pad mask: top, btm, left, right. 1 or 0 at", "+ last_stack.Ly mask = np.ones((yn - y0, xn - x0),", "min(rY, yn + 1) x0e = max(0, x0 - 1)", "P next_stack_.append(new_stack) return next_stack_ def form_blob(stack, root_dert__, sub_blobs): # increment", "0: # check for overlaps in 8 directions, else a", "min(blob.box[1], x0) # extend box x0 blob.box[2] = max(blob.box[2], xn)", "= mask if ~_mask: # terminate and pack last P", "(intra_comp value borrow from flat blob) # comp_g fork: blob.sub_layers", "-vg triggers comp_r. Each adds a layer of sub_blobs per", "be different for comp_a? aveB = 50 # fixed cost", "visibility and next-fork rdn sub_layers = list # -------------------------------------------------------------------------------------------------------------- #", "xn = blob.box yn = last_stack.y0 + last_stack.Ly mask =", "Convert or merge every P into its stack of Ps,", "ext_mask) # -> g sub_blobs: if dert__[0].shape[0] > 2 and", "P_ = form_P_(zip(*dert_), crit__[y], mask[y], P_binder) # horizontal clustering, adds", "xn and x0 < _xn: # x overlap between loaded", "overlaps only: 4 directions, edge blobs are more selective if", "to blob in the first up_connect. stack.hid = blob.id blob.stack_.append(stack)", "= float rng = int Ls = int # for", "# no next-P overlap if stack.down_connect_cnt != 1: # terminate", "except IndexError: return P_ # the whole line is masked,", "masked, return an empty P I, iDy, iDx, G, Dy,", "x0 = 0, 0, 0, 0, 0, 0, 0, 0,", "== 1: # up_connect is not terminated form_blob(up_connect_[0], root_dert__, sub_blobs)", "initialize P params: (redundant) # I, iDy, iDx, G, Dy,", "# initialize P params: I, iDy, iDx, G, Dy, Dx,", "dx, m stack_[ stack_params, Py_ [(P_params, dert_)]]: refs down blob", "# fixed cost per intra_blob comp and clustering class CDeepP(ClusterStructure):", "cross-comparison and sub-clustering: der+: incremental derivation cross-comp in high-variation edge", "empty P I, iDy, iDx, G, Dy, Dx, M, L", "_P if P.sign == stack.sign: # sign match stack.down_connect_cnt +=", "> 0 x0 = 0 try: while mask_[x0]: # skip", "rdn, rng, fig, fcr, **kwargs): # recursive input rng+ |", "stack.down_connect_cnt != 1: # terminate stack, merge it into up_connects'", "clustering functions: # ------------------------------------------------------------------------------------------------------------------- def form_P_(dert_, crit_, mask_, binder): #", "Ly = int y0 = int Py_ = list blob", "P up_connect_ = [] # list of same-sign x-overlapping _Ps", "= int Dy = int Dx = int M =", "for two forks of extended internal cross-comparison and sub-clustering: der+:", "next run of scan_P_ up_connect_ = [] if P_: P", "iDx=iDx, S=L, Ly=1, y0=y, Py_=[P], blob=blob, down_connect_cnt=0, sign=s) new_stack.hid =", "blob) # comp_g fork: blob.sub_layers += intra_blob(sub_blob, rdn + 1", "iDy, iDx, S, Ly, y0, Py_, blob, down_connect_cnt, sign =", "-------------------------------------------------------------------------------------------------------------- # functions, ALL WORK-IN-PROGRESS: def intra_blob(blob, rdn, rng, fig,", "mode='constant', constant_values=True) return ext_dert__, mask def accum_Dert(Dert: dict, **params) ->", "form_stack_(P_, root_dert__, sub_blobs, y): # Convert or merge every P", "stack y0, x0, xn = blob.box yn = last_stack.y0 +", "int iDy = int iDx = int S = int", "= int iDx = int S = int Ly =", "its blob for up_connect in up_connect_[1:len(up_connect_)]: # merge blobs of", "(area), Ly (vertical dimension) # I: input, (iDy, iDx): angle", "evaluates each blob for two forks of extended internal cross-comparison", "initialized blob (all connected stacks): blob.open_stacks += down_connect_cnt - 1", "data about clusters of the same level P_ = form_P_(zip(*dert_),", "fork? fig, # flag input is gradient rdn, # redundancy", "left: terminate loop next_P_.append((P, up_connect_)) break while P_: # terminate", "not terminated form_blob(up_connect_[0], root_dert__, sub_blobs) # merge stack of 1st", "# sign match stack.down_connect_cnt += 1 up_connect_.append(stack) # buffer P-connected", "in der+ fork, i+m in rng+ fork? fig, # flag", "next_P_.append((P_.popleft(), [])) # no up_connect while stack_: form_blob(stack_.popleft(), root_dert__, sub_blobs)", "dert__ into shape [y, params, x] sub_blobs = [] #", "is not None: # stop rendering sub-blobs when blob is", "x0=x0, sign=_sign) P_.append(P) for _P, P in pairwise(P_): if _P.x0", "form_P_(zip(*dert_), crit__[y], mask[y], P_binder) # horizontal clustering, adds a row", "merged_blob.Dert.values() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S,", "P P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx,", "+ P.L mask[y, x_start:x_stop] = False fopen = 0 #", "1st layer of sub_blobs for sub_blob in sub_blobs: # evaluate", "from form_blob: stack_ = deque() # buffer of running vertical", "| der+ if kwargs.get('render', None) is not None: # stop", "cluster_derts(dert__, mask, ave * rdn, fcr, fig, **kwargs) # fork", "rng * 2, fig=fig, fcr=1, **kwargs) # else: comp_P_ elif", "clustering is always by m? root_dert__ = dert__ # derts", "stack of 1st up_connect into its blob for up_connect in", "up_connect_ refs def form_stack_(P_, root_dert__, sub_blobs, y): # Convert or", "-= 1 # overlap with merged blob. blob.box[1] = min(blob.box[1],", "input, (iDy, iDx): angle of input gradient, G: gradient, (Dy,", "NoneType class CDeepBlob(ClusterStructure): Dert = dict box = list stack_", "(x0 - x0e, xne - xn)), mode='constant', constant_values=True) return ext_dert__,", "x0 = P.x0 # first x in P xn =", "# comp range sub_layers # [sub_blobs ]: list of layers", "and False in mask: # min size in y and", "der+ cross-comp within blob # fig: flag input is g", "Dx, M, iDy, iDx, S, Ly = merged_blob.Dert.values() accum_Dert(blob.Dert, I=I,", "Dy, Dx, M, L = *next(dert_), 1 # initialize P", "class_bind import AdjBinder from frame_blobs_yx import assign_adjacents from intra_comp_g import", "ends, last-line stacks are merged into their blobs: form_blob(stack_.popleft(), root_dert__,", "input is gradient rdn, # redundancy to higher layers rng,", "= P.x0 - x0 x_stop = x_start + P.L mask[y,", "in rng else: # comp_g output crit__ = dert__[6] -", "# next fork: fcr, # flag comp rng, also clustering", "False spliced_layers = [] # to extend root_blob sub_layers ext_dert__,", "[spliced_layers + sub_layers for spliced_layers, sub_layers in zip_longest(spliced_layers, blob.sub_layers, fillvalue=[])]", "== 1: form_blob(up_connect, root_dert__, sub_blobs) if not up_connect.blob is blob:", "((y0 - y0e, yne - yn), (x0 - x0e, xne", "row have any Ps / _Ps left P = P_.popleft()", "for stack in blob.stack_: for y, P in enumerate(stack.Py_, start=stack.y0", "element is P + up_connect_ refs def form_stack_(P_, root_dert__, sub_blobs,", "-> g sub_blobs: if dert__[0].shape[0] > 2 and dert__[0].shape[1] >", "_P.x0 # first x in _P _xn = _x0 +", "Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) blob.open_stacks += merged_blob.open_stacks blob.box[0]", "= fig blob.rdn = rdn blob.rng = rng blob.Ls =", "in vertical (horizontal) order # next fork: fcr, # flag", "sub-blobs when blob is too small if blob.Dert['S'] < 100:", "check if Ps are adjacents binder.bind(_P, P) return P_ def", "in blob root: last_stack = stack y0, x0, xn =", "Ly=0), box=[y, x0, xn], stack_=[], sign=s, open_stacks=1) new_stack = CDeepStack(I=I,", "rdn: ave = 50 # fixed cost per dert, from", "clustering criterion: if fig: crit__ = dert__[0] + dert__[6] -", "from part of root_dert__ ext_dert__ = [derts[y0e:yne, x0e:xne] if derts", "add adj_blobs to each blob # sub_blobs = find_adjacent(sub_blobs) if", "sign # prior sign _mask = mask if ~_mask: #", "# check for overlaps in 8 directions, else a blob", "root_dert__ dert__ = [*zip(*dert__)] # transpose dert__ into shape [y,", "1: form_blob(up_connect, root_dert__, sub_blobs) if not up_connect.blob is blob: merged_blob", "iDx=iDx, L=L,x0=x0, sign=_sign) P_.append(P) # initialize P params: I, iDy,", "if fcr: dert__, mask = comp_r(ext_dert__, fig, fcr, ext_mask) #", "= AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder) # add adj_blobs to each blob", "in 8 directions, else a blob may leak through its", "fig, # flag input is gradient rdn, # redundancy to", "rdn, # redundancy to higher layers rng, # comp range", "aveB * rdn: # G + (intra_comp value borrow from", "= up_connect.blob I, G, Dy, Dx, M, iDy, iDx, S,", "crit__, mask) for y, dert_ in enumerate(dert__): # in height,", "deviation of negated -vg triggers comp_r. Each adds a layer", "mask bit per dert for x, (i, idy, idx, g,", "up_connect.blob = blob up_connect.hid = blob.id blob.stack_.append(up_connect) blob.open_stacks -= 1", "mask = comp_g(ext_dert__, ext_mask) # -> g sub_blobs: if dert__[0].shape[0]", "= [spliced_layers + sub_layers for spliced_layers, sub_layers in zip_longest(spliced_layers, blob.sub_layers,", "blob.id blob.stack_.append(up_connect) blob.open_stacks -= 1 # overlap with merged blob.", "params: (redundant) # I, iDy, iDx, G, Dy, Dx, M,", "= object dert__ = object mask = object adj_blobs =", "/ 2) # or adjacent M if negative sign? if", "sub_blobs, y) stack_binder.bind_from_lower(P_binder) while stack_: # frame ends, last-line stacks", "# merge P into higher-row stack of Ps with same", "next_stack_.append(new_stack) return next_stack_ def form_blob(stack, root_dert__, sub_blobs): # increment blob", "comp_r. Each adds a layer of sub_blobs per blob. Please", "while stack_: # frame ends, last-line stacks are merged into", "not up_connect.blob is blob: merged_blob = up_connect.blob I, G, Dy,", "in height, first and last row are discarded; print(f'Processing intra", "0, 0, 0, 0, 0, x # current dert is", "xne = min(rX, xn + 1) # e is for", "int x0 = int sign = NoneType class CDeepStack(ClusterStructure): I", "multiple forks: no single set of fork params? ''' from", "new_stack.blob else: # if > 1 up_connects, or 1 up_connect", "is the root_dert__ dert__ = [*zip(*dert__)] # transpose dert__ into", "fork: blob.sub_layers += intra_blob(sub_blob, rdn + 1 + 1 /", "stack = stack_.popleft() # higher-row stacks _P = stack.Py_[-1] #", "comp_P_ spliced_layers = [spliced_layers + sub_layers for spliced_layers, sub_layers in", "list sign = NoneType open_stacks = int root_dert__ = object", "iDx, G, Dy, Dx, M, L = *next(dert_), 1 #", "M=M, iDy=iDy, iDx=iDx, L=L,x0=x0, sign=_sign) P_.append(P) # initialize P params:", "if P_: P = P_.popleft() # load next P else:", "next-P overlap if stack.down_connect_cnt != 1: # terminate stack, merge", "-> None: Dert.update({param: Dert[param] + value for param, value in", "_mask = mask_[x0] # mask bit per dert for x,", "int M = int iDy = int iDx = int", "_Ps left P = P_.popleft() # load left-most (lowest-x) input-row", "may leak through its external blob if _x0 - 1", "root_dert__] blob.mask = mask blob.adj_blobs = [[], 0, 0] blob.fopen", "up_connect_[0] new_stack.accumulate(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1)", "max(blob.box[2], merged_blob.box[2]) # extend box xn for stack in merged_blob.stack_:", "blobs of all up_connects if up_connect_[0].down_connect_cnt == 1: # up_connect", "vertical and lateral Ds, M: match sign, box, # y0,", "if fcr: # comp_r output; form clustering criterion: if fig:", "# sign taken accounted next_P_.append((P, up_connect_)) # recycle _P for", "1st-level algorithm is a combination of frame_blobs, intra_blob, and comp_P:", "vertical clustering, adds up_connects per P and down_connect_cnt per stack", "next-fork rdn blob.sub_layers = [sub_blobs] # 1st layer of sub_blobs", "= int x0 = int sign = NoneType class CDeepStack(ClusterStructure):", "if P.sign == stack.sign: # sign match stack.down_connect_cnt += 1", "box=[y, x0, xn], stack_=[], sign=s, open_stacks=1) new_stack = CDeepStack(I=I, G=G,", "yn, x0, xn) blob.dert__ = [derts[y0:yn, x0:xn] for derts in", "Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) # terminated stack", "int sign = NoneType class CDeepStack(ClusterStructure): I = int G", "0 # reset down_connect_cnt blob = new_stack.blob else: # if", "params: I, iDy, iDx, G, Dy, Dx, M, L, x0", "P_: # terminate Ps and stacks that continue at row's", "der+: incremental derivation cross-comp in high-variation edge areas of +vg:", "= 0 # reset down_connect_cnt blob = new_stack.blob else: #", "= stack.Py_[-1] # last element of each stack is higher-row", "= [sub_blobs] # 1st layer of sub_blobs for sub_blob in", "is unmasked P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy,", "deque() # converted to stack_ in the next run of", "Ls = int # for visibility and next-fork rdn sub_layers", "== stack.sign: # sign match stack.down_connect_cnt += 1 up_connect_.append(stack) #", "blob root: last_stack = stack y0, x0, xn = blob.box", "stacks into P' up_connect_ else: binder.bind(_P, P) else: # -G,", "merged_blob.box[0]) # extend box y0 blob.box[1] = min(blob.box[1], merged_blob.box[1]) #", "= bool rdn = float rng = int Ls =", "== 0: # if number of incomplete stacks == 0", "up_connect.blob I, G, Dy, Dx, M, iDy, iDx, S, Ly", "1: # up_connect is not terminated form_blob(up_connect_[0], root_dert__, sub_blobs) #", "max(blob.box[2], xn) # extend box xn P.hid = new_stack.id #", "iDy=iDy, iDx=iDx, S=L, Ly=1) new_stack.Py_.append(P) # Py_: vertical buffer of", "from class_bind import AdjBinder from frame_blobs_yx import assign_adjacents from intra_comp_g", "crit__ = dert__[0] + dert__[6] - Ave # eval by", "g, dy, dx, m) in enumerate(dert_, start=x0+1): # loop left", "blob.stack_: for y, P in enumerate(stack.Py_, start=stack.y0 - y0): x_start", "import zip_longest from class_stream import BlobStreamer from utils import pairwise", "selective if _x0 < xn and x0 < _xn: #", "= x0 + P.L # first x beyond P _x0", "= int Ly = int y0 = int Py_ =", "x elif _mask: I, iDy, iDx, G, Dy, Dx, M,", "G, Dy, Dx, M, iDy, iDx, S, Ly, y0, Py_,", "of Ps new_stack.down_connect_cnt = 0 # reset down_connect_cnt blob =", "y): # Convert or merge every P into its stack", "CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1, y0=y,", "per P and down_connect_cnt per stack stack_ = form_stack_(P_, root_dert__,", "float rng = int Ls = int # for visibility", "a row if prior dert is unmasked P = CDeepP(I=I,", "recycle _P for the next run of scan_P_ up_connect_ =", "Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) #", "fig: crit__ = dert__[0] + dert__[6] - Ave # eval", "/ blob.Ls, rng=rng, fig=1, fcr=0, **kwargs) # else: comp_P_ spliced_layers", "value lend to edge blob) # comp_r fork: blob.sub_layers +=", "x0, xn dert__, # box of derts, each = i,", "form_blob: stack_ = deque() # buffer of running vertical stacks", "across sub_blob derivation tree # deeper layers are nested, multiple", "_mask = mask if ~_mask: # terminate and pack last", "edge blobs are more selective if _x0 < xn and", "= min(rX, xn + 1) # e is for extended", "box: rY, rX = blob.root_dert__[0].shape # higher dert size #", "sign=_sign) P_.append(P) # initialize P params: (redundant) # I, iDy,", "into their blobs: form_blob(stack_.popleft(), root_dert__, sub_blobs) blob_binder = AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder)", "forks: no single set of fork params? ''' from collections", "y0, xn - x0), dtype=bool) # mask box, then unmask", "- 1 # incomplete stack cnt + terminated stack down_connect_cnt", "whole line is masked, return an empty P I, iDy,", "gradient, (Dy, Dx): vertical and lateral Ds, M: match sign,", "sign = NoneType class CDeepStack(ClusterStructure): I = int G =", "+= dy Dx += dx M += m L +=", "stack, check for blob termination I, G, Dy, Dx, M,", "abs(adj_G) / 2) # or adjacent M if negative sign?", "of extended internal cross-comparison and sub-clustering: der+: incremental derivation cross-comp", "I += i iDy += idy iDx += idx G", "blob) # comp_r fork: blob.sub_layers += intra_blob(sub_blob, rdn + 1", "M, S (area), Ly (vertical dimension) # I: input, (iDy,", "int Dy = int Dx = int M = int", "that has > 1 down_connect_cnt: blob = up_connect_[0].blob # initialize", "x0 == 0 or xn == root_dert__[0].shape[1] or y0 ==", "sub_blob.Dert['M'] - borrow > aveB * rdn: # M -", "order P_ = deque() # row of Ps sign_ =", "iDx, G, Dy, Dx, M, S (area), Ly (vertical dimension)", "''' from collections import deque, defaultdict from class_cluster import ClusterStructure,", "class_stream import BlobStreamer from utils import pairwise import numpy as", "for stack in merged_blob.stack_: if not stack is up_connect: stack.blob", "BlobStreamer(CDeepBlob, crit__, mask) if render: streamer = BlobStreamer(CDeepBlob, crit__, mask)", "mask box, then unmask Ps: for stack in blob.stack_: for", "up_connect_[1:len(up_connect_)]: # merge blobs of other up_connects into blob of", "form_blob(stack, root_dert__, sub_blobs) break else: # no next-P overlap if", "frame ends, last-line stacks are merged into their blobs: form_blob(stack_.popleft(),", "references to blob in the first up_connect. stack.hid = blob.id", "1 + 1 / blob.Ls, rng * 2, fig=fig, fcr=1,", "load next P else: # terminate loop if stack.down_connect_cnt !=", "sub_blob derivation tree # deeper layers are nested, multiple forks:", "None: Dert.update({param: Dert[param] + value for param, value in params.items()})", "BlobStreamer from utils import pairwise import numpy as np #", "functions: # ------------------------------------------------------------------------------------------------------------------- def form_P_(dert_, crit_, mask_, binder): # segment", "single set of fork params? ''' from collections import deque,", "rendering mode after blob conversion streamer.end_blob_conversion(y) return sub_blobs # clustering", "fcr: flag comp over rng+ | der+ if kwargs.get('render', None)", "_sign = sign_[x0] _mask = mask_[x0] # mask bit per", "_Ps per P while True: # while both P_ and", "blob = new_stack.blob else: # if > 1 up_connects, or", "True: # while both P_ and stack_ are not empty", "in low-variation flat areas of +v--vg: positive deviation of negated", "= deque() # buffer of running vertical stacks of Ps", "= crit_ > 0 x0 = 0 try: while mask_[x0]:", "a combination of frame_blobs, intra_blob, and comp_P: optional raster-to-vector conversion.", "rng+ | der+ if kwargs.get('render', None) is not None: #", "I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) blob.open_stacks", "mask) if render: streamer = BlobStreamer(CDeepBlob, crit__, mask) for y,", "down_connect_cnt - 1: stack itself # open stacks contain Ps", "stack.blob = blob # blobs in other up_connects are references", "enumerate(stack.Py_, start=stack.y0 - y0): x_start = P.x0 - x0 x_stop", "0, 0, 0, 0, 0, x elif _mask: I, iDy,", "into blob of 1st up_connect if up_connect.down_connect_cnt == 1: form_blob(up_connect,", "_P _xn = _x0 + _P.L # first x beyond", "P-connected higher-row stacks into P' up_connect_ else: binder.bind(_P, P) else:", "AdjBinder(CDeepP) # binder needs data about clusters of the same", "y0e = max(0, y0 - 1) yne = min(rY, yn", "xn P.hid = new_stack.id # assign higher cluster id for", "1) x0e = max(0, x0 - 1) xne = min(rX,", "extend box xn P.hid = new_stack.id # assign higher cluster", "higher-row stacks _P = stack.Py_[-1] # last element of each", "binder.bind(_P, P) if (xn < _xn or # _P overlaps", "blob.adj_blobs = [[], 0, 0] blob.fopen = fopen sub_blobs.append(blob) def", "import AdjBinder from frame_blobs_yx import assign_adjacents from intra_comp_g import comp_g,", "elif _mask: I, iDy, iDx, G, Dy, Dx, M, L,", "if > 1 up_connects, or 1 up_connect that has >", "derts after the comps operation, which is the root_dert__ dert__", "# -G, check for orthogonal overlaps only: 4 directions, edge", "= blob.Dert['G']; adj_G = blob.adj_blobs[2] borrow = min(abs(G), abs(adj_G) /", "= list stack_ = list sign = NoneType open_stacks =", "fig = bool rdn = float rng = int Ls", "# add adj_blobs to each blob # sub_blobs = find_adjacent(sub_blobs)", "1st up_connect if up_connect.down_connect_cnt == 1: form_blob(up_connect, root_dert__, sub_blobs) if", "x beyond P _x0 = _P.x0 # first x in", "sub_layers for spliced_layers, sub_layers in zip_longest(spliced_layers, blob.sub_layers, fillvalue=[])] return spliced_layers", "# I: input, (iDy, iDx): angle of input gradient, G:", "terminated stack, check for blob termination I, G, Dy, Dx,", "root_dert__ = dert__ # derts after the comps operation, which", "or clustering is always by m? root_dert__ = dert__ #", "# flag comp rng, also clustering criterion in dert and", "_xn + 1: # x overlap between loaded P and", "fopen sub_blobs.append(blob) def extend_dert(blob): # extend dert borders (+1 dert", "1) xne = min(rX, xn + 1) # e is", "x0, s = P.unpack() xn = x0 + L #", "1 # overlap with merged blob. blob.box[1] = min(blob.box[1], x0)", "class CDeepStack(ClusterStructure): I = int G = int Dy =", "+ (intra_comp value borrow from flat blob) # comp_g fork:", "g Dy += dy Dx += dx M += m", "not None else None for derts in blob.root_dert__] # pad", "= root_dert__ blob.box = (y0, yn, x0, xn) blob.dert__ =", "P in pairwise(P_): if _P.x0 + _P.L == P.x0: #", "+= 1 up_connect_.append(stack) # buffer P-connected higher-row stacks into P'", "assign_adjacents(blob_binder) # add adj_blobs to each blob # sub_blobs =", "buffer of running vertical stacks of Ps stack_binder = AdjBinder(CDeepStack)", "# transpose dert__ into shape [y, params, x] sub_blobs =", "y0 - 1) yne = min(rY, yn + 1) x0e", "int Ls = int # for visibility and next-fork rdn", "in horizontal ) vertical order P_ = deque() # row", "mask[y], P_binder) # horizontal clustering, adds a row of Ps", "Ps / _Ps left P = P_.popleft() # load left-most", "int S = int Ly = int y0 = int", "blob in the first up_connect. stack.hid = blob.id blob.stack_.append(stack) #", "------------------------------------------------------------------------------------------------------------------- def form_P_(dert_, crit_, mask_, binder): # segment dert__ into", "# current dert is not masked sign = sign_[x] if", "up_connect_ = [] if P_: P = P_.popleft() # load", "after the comps operation, which is the root_dert__ dert__ =", "blob.mask = mask blob.adj_blobs = [[], 0, 0] blob.fopen =", "borrow = min(abs(G), abs(adj_G) / 2) # or adjacent M", "higher cluster id for P next_stack_.append(new_stack) return next_stack_ def form_blob(stack,", "constant_values=True) return ext_dert__, mask def accum_Dert(Dert: dict, **params) -> None:", "= np.pad(blob.mask, ((y0 - y0e, yne - yn), (x0 -", "= last_stack.y0 + last_stack.Ly mask = np.ones((yn - y0, xn", "blob.fcr = fcr blob.fig = fig blob.rdn = rdn blob.rng", "int iDy = int iDx = int L = int", "L, x0 = 0, 0, 0, 0, 0, 0, 0,", "comps operation, which is the root_dert__ dert__ = [*zip(*dert__)] #", "m sub_blobs else: dert__, mask = comp_g(ext_dert__, ext_mask) # ->", "layer of sub_blobs for sub_blob in sub_blobs: # evaluate for", "and stacks that continue at row's end next_P_.append((P_.popleft(), [])) #", "and that up_connect has one down_connect=P: merge P into up_connect", "same level P_ = form_P_(zip(*dert_), crit__[y], mask[y], P_binder) # horizontal", "last_stack = stack y0, x0, xn = blob.box yn =", "1 / blob.Ls, rng * 2, fig=fig, fcr=1, **kwargs) #", "# pack P P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M,", "beyond P _x0 = _P.x0 # first x in _P", "not empty x0 = P.x0 # first x in P", "P.sign == stack.sign: # sign match stack.down_connect_cnt += 1 up_connect_.append(stack)", "stack in blob.stack_: for y, P in enumerate(stack.Py_, start=stack.y0 -", "from class_stream import BlobStreamer from utils import pairwise import numpy", "# first x beyond P _x0 = _P.x0 # first", "merge it into up_connects' blobs form_blob(stack, root_dert__, sub_blobs) if stack_:", "0 try: while mask_[x0]: # skip until not masked next(dert_)", "# recycle _P for the next run of scan_P_ up_connect_", "IndexError: return P_ # the whole line is masked, return", "into its stack of Ps, merge blobs next_stack_ = deque()", "[derts[y0:yn, x0:xn] for derts in root_dert__] blob.mask = mask blob.adj_blobs", "a layer of sub_blobs per blob. Please see diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png", "root_dert__, sub_blobs) # down_connect_cnt always == 0 return next_P_ #", "G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P)", "* rdn: # M - (intra_comp value lend to edge", "is g | p, fcr: flag comp over rng+ |", "first and last row are discarded; print(f'Processing intra line {y}...')", "start=x0+1): # loop left to right in each row of", "m? root_dert__ = dert__ # derts after the comps operation,", "blob.root_dert__ = root_dert__ blob.box = (y0, yn, x0, xn) blob.dert__", "stacks == 0 # blob is terminated and packed in", "prior dert is unmasked P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx,", "> 1: # merge blobs of all up_connects if up_connect_[0].down_connect_cnt", "y0): x_start = P.x0 - x0 x_stop = x_start +", "algorithm is a combination of frame_blobs, intra_blob, and comp_P: optional", "adds a row of Ps if render: render = streamer.update_blob_conversion(y,", "= 0 # flag: blob on frame boundary if x0", "< 100: kwargs['render'] = False spliced_layers = [] # to", "in other up_connects are references to blob in the first", "dert__[6] - Ave # comp_g output eval by m, or", "from flat blob) # comp_g fork: blob.sub_layers += intra_blob(sub_blob, rdn", "- yn), (x0 - x0e, xne - xn)), mode='constant', constant_values=True)", "2 and dert__[0].shape[1] > 2 and False in mask: #", "terminated and packed in blob root: last_stack = stack y0,", "terminated stack down_connect_cnt - 1: stack itself # open stacks", "P_binder = AdjBinder(CDeepP) # binder needs data about clusters of", "xn == _xn and stack.sign): # sign taken accounted next_P_.append((P,", "collections import deque, defaultdict from class_cluster import ClusterStructure, NoneType from", "for sub_blob in sub_blobs: # evaluate for intra_blob comp_g |", "and sign changed # pack P P = CDeepP(I=I, G=G,", "in blob.root_dert__] # pad mask: top, btm, left, right. 1", "# fig: flag input is g | p, fcr: flag", "blob.root_dert__[0].shape # higher dert size # determine pad size y0e", "= int Py_ = list blob = object down_connect_cnt =", "p, fcr: flag comp over rng+ | der+ if kwargs.get('render',", "rdn, fcr, fig, **kwargs) # fork params: blob.fcr = fcr", "= x0 + L # next-P x0 if not up_connect_:", "up_connect_[0].down_connect_cnt == 1: # P has one up_connect and that", "P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L,x0=x0,", "list fcr = bool fig = bool rdn = float", "P_.popleft() I, G, Dy, Dx, M, iDy, iDx, L, x0,", "scanning _P, will be converted into next_stack_ if P_ and", "blob.sub_layers, fillvalue=[])] return spliced_layers def cluster_derts(dert__, mask, Ave, fcr, fig,", "stack_params, Py_ [(P_params, dert_)]]: refs down blob formation tree, in", "Dy += dy Dx += dx M += m L", "root_dert__, Dert = I, iDy, iDx, G, Dy, Dx, M,", "= P.x0 # first x in P xn = x0", "blob for up_connect in up_connect_[1:len(up_connect_)]: # merge blobs of other", "tree # deeper layers are nested, multiple forks: no single", "Ly, y0, Py_, blob, down_connect_cnt, sign = stack.unpack() accum_Dert(blob.Dert, I=I,", "root_dert__, sub_blobs) break else: # no next-P overlap if stack.down_connect_cnt", "# mask bit per dert for x, (i, idy, idx,", "mode after blob conversion streamer.end_blob_conversion(y) return sub_blobs # clustering functions:", "fcr, fig, **kwargs) # fork params: blob.fcr = fcr blob.fig", "blob. blob.box[1] = min(blob.box[1], x0) # extend box x0 blob.box[2]", "merge it into up_connects' blobs form_blob(stack, root_dert__, sub_blobs) break else:", "- xn)), mode='constant', constant_values=True) return ext_dert__, mask def accum_Dert(Dert: dict,", "rdn blob.sub_layers = [sub_blobs] # 1st layer of sub_blobs for", "if render: # rendering mode after blob conversion streamer.end_blob_conversion(y) return", "deeper layers are nested, multiple forks: no single set of", "last_stack.y0 + last_stack.Ly mask = np.ones((yn - y0, xn -", "# terminate loop if stack.down_connect_cnt != 1: # terminate stack,", "needs data about clusters of the same level P_ =", "# list of same-sign x-overlapping _Ps per P while True:", "Ps and stacks that continue at row's end next_P_.append((P_.popleft(), []))", "other up_connects into blob of 1st up_connect if up_connect.down_connect_cnt ==", "object down_connect_cnt = int sign = NoneType class CDeepBlob(ClusterStructure): Dert", "nested, multiple forks: no single set of fork params? '''", "stacks): blob.open_stacks += down_connect_cnt - 1 # incomplete stack cnt", "of same-sign x-overlapping _Ps per P while True: # while", "# if both input row and higher row have any", "bool fig = bool rdn = float rng = int", "# fixed cost per dert, from average m, reflects blob", "# flag input is gradient rdn, # redundancy to higher", "xn for stack in merged_blob.stack_: if not stack is up_connect:", "of gradient triggers comp_g, rng+: incremental range cross-comp in low-variation", "sub_blobs for sub_blob in sub_blobs: # evaluate for intra_blob comp_g", "x_start + P.L mask[y, x_start:x_stop] = False fopen = 0", "mask = mask_[x] if ~mask: # current dert is not", "Dert = dict box = list stack_ = list sign", "left to right in each row of derts mask =", "edge areas of +vg: positive deviation of gradient triggers comp_g,", "cost per dert, from average m, reflects blob definition cost,", "xn == root_dert__[0].shape[1] or y0 == 0 or yn ==", "S=S, Ly=Ly) blob.open_stacks += merged_blob.open_stacks blob.box[0] = min(blob.box[0], merged_blob.box[0]) #", "left, right. 1 or 0 at boundaries mask = np.pad(blob.mask,", "kwargs.get('render', None) is not None: # stop rendering sub-blobs when", "incremental derivation cross-comp in high-variation edge areas of +vg: positive", "xn dert__, # box of derts, each = i, idy,", "iDx += idx G += g Dy += dy Dx", "== 0 return next_P_ # each element is P +", "down_connect_cnt: blob = up_connect_[0].blob # initialize new_stack with up_connect blob:", "list stack_ = list sign = NoneType open_stacks = int", "NoneType from class_bind import AdjBinder from frame_blobs_yx import assign_adjacents from", "= extend_dert(blob) if fcr: dert__, mask = comp_r(ext_dert__, fig, fcr,", "for P next_stack_.append(new_stack) return next_stack_ def form_blob(stack, root_dert__, sub_blobs): #", "# terminate Ps and stacks that continue at row's end", "box y0 blob.box[1] = min(blob.box[1], merged_blob.box[1]) # extend box x0", "np # from comp_P_draft import comp_P_blob # filters, All *=", "= dert__ # derts after the comps operation, which is", "**kwargs) # else: comp_P_ spliced_layers = [spliced_layers + sub_layers for", "prior dert is not masked # pack P P =", "root_dert__[0].shape[0]: fopen = 1 blob.root_dert__ = root_dert__ blob.box = (y0,", "is for extended # take ext_dert__ from part of root_dert__", "P + up_connect_ refs def form_stack_(P_, root_dert__, sub_blobs, y): #", "- (intra_comp value lend to edge blob) # comp_r fork:", "down_connect_cnt - 1 # incomplete stack cnt + terminated stack", "CDeepP(ClusterStructure): I = int G = int Dy = int", "fork params: blob.fcr = fcr blob.fig = fig blob.rdn =", "if x0 == 0 or xn == root_dert__[0].shape[1] or y0", "m, accum in rng; dert__[:,:,0] if not transposed else: crit__", "internal cross-comparison and sub-clustering: der+: incremental derivation cross-comp in high-variation", "= blob.root_dert__[0].shape # higher dert size # determine pad size", "fcr=1, **kwargs) # else: comp_P_ elif sub_blob.Dert['G'] + borrow >", "= int iDx = int L = int x0 =", "cluster_derts(dert__, mask, Ave, fcr, fig, render=False): # similar to frame_to_blobs", "False, stop rendering P_ = scan_P_(P_, stack_, root_dert__, sub_blobs, P_binder)", "stack cnt + terminated stack down_connect_cnt - 1: stack itself", "x0:xn] for derts in root_dert__] blob.mask = mask blob.adj_blobs =", "are more selective if _x0 < xn and x0 <", "= comp_g(ext_dert__, ext_mask) # -> g sub_blobs: if dert__[0].shape[0] >", "form_P_(dert_, crit_, mask_, binder): # segment dert__ into P__, in", "xn) # extend box xn P.hid = new_stack.id # assign", "P = P_.popleft() # load left-most (lowest-x) input-row P stack", "P.x0 # first x in P xn = x0 +", "blob.sub_layers = [sub_blobs] # 1st layer of sub_blobs for sub_blob", "0, 0, 0, x # current dert is masked elif", "= list fcr = bool fig = bool rdn =", "y0 = int Py_ = list blob = object down_connect_cnt", "mask blob.adj_blobs = [[], 0, 0] blob.fopen = fopen sub_blobs.append(blob)", "sub_blobs # clustering functions: # ------------------------------------------------------------------------------------------------------------------- def form_P_(dert_, crit_, mask_,", "new_stack = up_connect_[0] new_stack.accumulate(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx,", "AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder) # add adj_blobs to each blob #", "4 directions, edge blobs are more selective if _x0 <", "mask, ave * rdn, fcr, fig, **kwargs) # fork params:", "x-overlapping Ps in next run of scan_P_ if blob.open_stacks ==", "it into up_connects' blobs form_blob(stack, root_dert__, sub_blobs) if stack_: #", "for intra_blob comp_g | comp_r: G = blob.Dert['G']; adj_G =", "and pack last P in a row if prior dert", "termination I, G, Dy, Dx, M, iDy, iDx, S, Ly,", "defaultdict from class_cluster import ClusterStructure, NoneType from class_bind import AdjBinder", "up_connect_ that finished scanning _P, will be converted into next_stack_", "Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L,x0=x0, sign=_sign) P_.append(P) # initialize P", "x0) # extend box x0 blob.box[2] = max(blob.box[2], xn) #", "fcr, # flag comp rng, also clustering criterion in dert", "int Py_ = list blob = object down_connect_cnt = int", "that up_connect has one down_connect=P: merge P into up_connect stack:", "by i + m, accum in rng; dert__[:,:,0] if not", "= CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L,x0=x0, sign=_sign)", "- x0 x_stop = x_start + P.L mask[y, x_start:x_stop] =", "sub_blobs): # increment blob with terminated stack, check for blob", "the same level P_ = form_P_(zip(*dert_), crit__[y], mask[y], P_binder) #", "blob.stack_.append(up_connect) blob.open_stacks -= 1 # overlap with merged blob. blob.box[1]", "# merge blobs of other up_connects into blob of 1st", "higher row: blob = CDeepBlob(Dert=dict(I=0, G=0, Dy=0, Dx=0, M=0, iDy=0,", "# if False in mask[i]: # [y,x,params], there is at", "# the whole line is masked, return an empty P", "run of scan_P_ up_connect_ = [] if P_: P =", "box of derts, each = i, idy, idx, g, dy,", "P params: I += i iDy += idy iDx +=", "xn - x0), dtype=bool) # mask box, then unmask Ps:", "None: # stop rendering sub-blobs when blob is too small", "loop left to right in each row of derts mask", "sub_blobs: if dert__[0].shape[0] > 2 and dert__[0].shape[1] > 2 and", "y) stack_binder.bind_from_lower(P_binder) while stack_: # frame ends, last-line stacks are", "least one dert in dert__ sub_blobs = cluster_derts(dert__, mask, ave", "0, x + 1 if ~mask: # accumulate P params:", "root: last_stack = stack y0, x0, xn = blob.box yn", "M - (intra_comp value lend to edge blob) # comp_r", "y0e, yne - yn), (x0 - x0e, xne - xn)),", "mask, Ave, fcr, fig, render=False): # similar to frame_to_blobs if", "iDy, iDx, L, x0, s = P.unpack() xn = x0", "**kwargs) # else: comp_P_ elif sub_blob.Dert['G'] + borrow > aveB", "list of same-sign x-overlapping _Ps per P while True: #", "frame_to_blobs if fcr: # comp_r output; form clustering criterion: if", "check for overlaps in 8 directions, else a blob may", "if _x0 - 1 < xn and x0 < _xn", "blob = CDeepBlob(Dert=dict(I=0, G=0, Dy=0, Dx=0, M=0, iDy=0, iDx=0, S=0,", "unmask Ps: for stack in blob.stack_: for y, P in", "blob is too small if blob.Dert['S'] < 100: kwargs['render'] =", "input rng+ | der+ cross-comp within blob # fig: flag", "P in a row if prior dert is unmasked P", "== 0 or yn == root_dert__[0].shape[0]: fopen = 1 blob.root_dert__", "accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly)", "P_.append(P) # initialize P params: (redundant) # I, iDy, iDx,", "directions, else a blob may leak through its external blob", "of layers across sub_blob derivation tree # deeper layers are", "incomplete stacks == 0 # blob is terminated and packed", "P_ = scan_P_(P_, stack_, root_dert__, sub_blobs, P_binder) # vertical clustering,", "print(f'Processing intra line {y}...') # if False in mask[i]: #", "of fork params? ''' from collections import deque, defaultdict from", "# last element of each stack is higher-row P up_connect_", "down_connect_cnt blob = new_stack.blob else: # if > 1 up_connects,", "# stop rendering sub-blobs when blob is too small if", "up_connect_: # initialize new stack for each input-row P that", "P_.popleft() # load next P else: # terminate loop if", "M=M, iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) for _P, P", "next_P_ # each element is P + up_connect_ refs def", "blob with terminated stack, check for blob termination I, G,", "/ _Ps left P = P_.popleft() # load left-most (lowest-x)", "value borrow from flat blob) # comp_g fork: blob.sub_layers +=", "(all connected stacks): blob.open_stacks += down_connect_cnt - 1 # incomplete", "adjacents binder.bind(_P, P) return P_ def scan_P_(P_, stack_, root_dert__, sub_blobs,", "+= merged_blob.open_stacks blob.box[0] = min(blob.box[0], merged_blob.box[0]) # extend box y0", "if _P.x0 + _P.L == P.x0: # check if Ps", "~_mask: # prior dert is not masked # pack P", "M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) blob.open_stacks += merged_blob.open_stacks blob.box[0] =", "right. 1 or 0 at boundaries mask = np.pad(blob.mask, ((y0", "xn and x0 < _xn + 1: # x overlap", "P that has no connections in higher row: blob =", "cnt + terminated stack down_connect_cnt - 1: stack itself #", "in rng; dert__[:,:,0] if not transposed else: crit__ = Ave", "iDx, S, Ly, y0, Py_, blob, down_connect_cnt, sign = stack.unpack()", "P else: # terminate loop if stack.down_connect_cnt != 1: #", "row's end next_P_.append((P_.popleft(), [])) # no up_connect while stack_: form_blob(stack_.popleft(),", "sub_blobs) if not up_connect.blob is blob: merged_blob = up_connect.blob I,", "per dert, from average m, reflects blob definition cost, may", "blob.id blob.stack_.append(new_stack) if len(up_connect_) > 1: # merge blobs of", "of merged root stacks. up_connect.blob = blob up_connect.hid = blob.id", "int Ly = int y0 = int Py_ = list", "down_connect_cnt per stack stack_ = form_stack_(P_, root_dert__, sub_blobs, y) stack_binder.bind_from_lower(P_binder)", "initialize new stack for each input-row P that has no", "in P xn = x0 + P.L # first x", "Blob structure, for all layers of blob hierarchy: root_dert__, Dert", "next_stack_ = deque() # converted to stack_ in the next", "level P_ = form_P_(zip(*dert_), crit__[y], mask[y], P_binder) # horizontal clustering,", "iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) for _P, P in pairwise(P_):", "of 1st up_connect into its blob for up_connect in up_connect_[1:len(up_connect_)]:", "blob # fig: flag input is g | p, fcr:", "# load left-most (lowest-x) input-row P stack = stack_.popleft() #", "up_connects are references to blob in the first up_connect. stack.hid", "bool margin = list fcr = bool fig = bool", "if not stack is up_connect: stack.blob = blob # blobs", "load left-most (lowest-x) input-row P stack = stack_.popleft() # higher-row", "terminated stack is merged into continued or initialized blob (all", "2D version of 1st-level algorithm is a combination of frame_blobs,", "# fork params: blob.fcr = fcr blob.fig = fig blob.rdn", "return P_ def scan_P_(P_, stack_, root_dert__, sub_blobs, binder): # merge", "stack = stack_.popleft() _P = stack.Py_[-1] else: # no stack", "comp rng, also clustering criterion in dert and Dert: g", "rng+ fork? fig, # flag input is gradient rdn, #", "= int Ls = int # for visibility and next-fork", "for y, dert_ in enumerate(dert__): # in height, first and", "root_dert__, sub_blobs) blob_binder = AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder) # add adj_blobs", "comp_r fork: blob.sub_layers += intra_blob(sub_blob, rdn + 1 + 1", "into P' up_connect_ else: binder.bind(_P, P) if (xn < _xn", "blob if _x0 - 1 < xn and x0 <", "int iDx = int L = int x0 = int", "higher row have any Ps / _Ps left P =", "0 # blob is terminated and packed in blob root:", "refs down blob formation tree, in vertical (horizontal) order #", "down_connect_cnt always == 0 return next_P_ # each element is", "and higher row have any Ps / _Ps left P", "# I, iDy, iDx, G, Dy, Dx, M, L, x0", "# open stacks contain Ps of a current row and", "BlobStreamer(CDeepBlob, crit__, mask) for y, dert_ in enumerate(dert__): # in", "reflects blob definition cost, may be different for comp_a? aveB", "# increment blob with terminated stack, check for blob termination", "and x, least one dert in dert__ sub_blobs = cluster_derts(dert__,", "negated -vg triggers comp_r. Each adds a layer of sub_blobs", "# for visibility and next-fork rdn blob.sub_layers = [sub_blobs] #", "+vg: positive deviation of gradient triggers comp_g, rng+: incremental range", "~_mask: # terminate and pack last P in a row", "M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) # terminated stack is merged", "frame_blobs_yx import assign_adjacents from intra_comp_g import comp_g, comp_r from itertools", "up_connect_ = P_.popleft() I, G, Dy, Dx, M, iDy, iDx,", "= cluster_derts(dert__, mask, ave * rdn, fcr, fig, **kwargs) #", "stop rendering sub-blobs when blob is too small if blob.Dert['S']", "G = blob.Dert['G']; adj_G = blob.adj_blobs[2] borrow = min(abs(G), abs(adj_G)", "of running vertical stacks of Ps stack_binder = AdjBinder(CDeepStack) if", "gradient triggers comp_g, rng+: incremental range cross-comp in low-variation flat", "adds a layer of sub_blobs per blob. Please see diagram:", "sub_blobs) if stack_: # load stack with next _P stack", "first x beyond _P if stack.G > 0: # check", "P and _P if P.sign == stack.sign: # sign match", "+= 1 except IndexError: return P_ # the whole line", "by m? root_dert__ = dert__ # derts after the comps", "x0 - 1) xne = min(rX, xn + 1) #", "for _P, P in pairwise(P_): if _P.x0 + _P.L ==", "stack is merged into continued or initialized blob (all connected", "+= idx G += g Dy += dy Dx +=", "x] sub_blobs = [] # from form_blob: stack_ = deque()", "# from form_blob: stack_ = deque() # buffer of running", "else: comp_P_ spliced_layers = [spliced_layers + sub_layers for spliced_layers, sub_layers", "i iDy += idy iDx += idx G += g", "x0 blob.box[2] = max(blob.box[2], merged_blob.box[2]) # extend box xn for", "blobs: form_blob(stack_.popleft(), root_dert__, sub_blobs) blob_binder = AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder) #", "of Ps, merge blobs next_stack_ = deque() # converted to", "~mask: # accumulate P params: I += i iDy +=", "extended # take ext_dert__ from part of root_dert__ ext_dert__ =", "params _sign = sign_[x0] _mask = mask_[x0] # mask bit", "may be extended with new x-overlapping Ps in next run", "if up_connect_[0].down_connect_cnt == 1: # up_connect is not terminated form_blob(up_connect_[0],", "up_connects if up_connect_[0].down_connect_cnt == 1: # up_connect is not terminated", "0: # if number of incomplete stacks == 0 #", "up_connect.blob is blob: merged_blob = up_connect.blob I, G, Dy, Dx,", "= comp_r(ext_dert__, fig, fcr, ext_mask) # -> m sub_blobs else:", "clustering, adds up_connects per P and down_connect_cnt per stack stack_", "S = int Ly = int y0 = int Py_", "stack, merge it into up_connects' blobs form_blob(stack, root_dert__, sub_blobs) if", "Ave - dert__[3] # eval by -g, accum in rng", "-g, accum in rng else: # comp_g output crit__ =", "# M - (intra_comp value lend to edge blob) #", "# buffer of merged root stacks. up_connect.blob = blob up_connect.hid", "merged into their blobs: form_blob(stack_.popleft(), root_dert__, sub_blobs) blob_binder = AdjBinder(CDeepBlob)", "Dy, Dx, M, S (area), Ly (vertical dimension) # I:", "i, idy, idx, g, dy, dx, m stack_[ stack_params, Py_", "i + m, accum in rng; dert__[:,:,0] if not transposed", "is P + up_connect_ refs def form_stack_(P_, root_dert__, sub_blobs, y):", "1 up_connects, or 1 up_connect that has > 1 down_connect_cnt:", "# e is for extended # take ext_dert__ from part", "L = int x0 = int sign = NoneType class", "stacks of Ps stack_binder = AdjBinder(CDeepStack) if render: streamer =", "= [] # from form_blob: stack_ = deque() # buffer", "intra_blob comp and clustering class CDeepP(ClusterStructure): I = int G", "> 2 and False in mask: # min size in", "next run of scan_P_ while P_: P, up_connect_ = P_.popleft()", "{y}...') # if False in mask[i]: # [y,x,params], there is", "stack of Ps with same sign and x_coord overlap next_P_", "are not empty x0 = P.x0 # first x in", "one dert in dert__ sub_blobs = cluster_derts(dert__, mask, ave *", "fopen = 1 blob.root_dert__ = root_dert__ blob.box = (y0, yn,", "if derts is not None else None for derts in", "higher-row P up_connect_ = [] # list of same-sign x-overlapping", "row and may be extended with new x-overlapping Ps in", "S, Ly, y0, Py_, blob, down_connect_cnt, sign = stack.unpack() accum_Dert(blob.Dert,", "min(abs(G), abs(adj_G) / 2) # or adjacent M if negative", "= AdjBinder(CDeepStack) if render: streamer = BlobStreamer(CDeepBlob, crit__, mask) if", "_P, will be converted into next_stack_ if P_ and stack_:", "int y0 = int Py_ = list blob = object", "blob for two forks of extended internal cross-comparison and sub-clustering:", "return ext_dert__, mask def accum_Dert(Dert: dict, **params) -> None: Dert.update({param:", "x, least one dert in dert__ sub_blobs = cluster_derts(dert__, mask,", "= rdn blob.rng = rng blob.Ls = len(sub_blobs) # for", "y0=y, Py_=[P], blob=blob, down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) else:", "root_dert__, sub_blobs) if stack_: # load stack with next _P", "if return False, stop rendering P_ = scan_P_(P_, stack_, root_dert__,", "fcr, **kwargs): # recursive input rng+ | der+ cross-comp within", "form_blob(up_connect, root_dert__, sub_blobs) if not up_connect.blob is blob: merged_blob =", "blob.rng = rng blob.Ls = len(sub_blobs) # for visibility and", "if not transposed else: crit__ = Ave - dert__[3] #", "are adjacents binder.bind(_P, P) return P_ def scan_P_(P_, stack_, root_dert__,", "boundaries) y0, yn, x0, xn = blob.box # extend dert", "sub_blobs = find_adjacent(sub_blobs) if render: # rendering mode after blob", "left P = P_.popleft() # load left-most (lowest-x) input-row P", "if blob.open_stacks == 0: # if number of incomplete stacks", "< _xn or # _P overlaps next P in P_", "in up_connect_[1:len(up_connect_)]: # merge blobs of other up_connects into blob", "no single set of fork params? ''' from collections import", "packed in blob root: last_stack = stack y0, x0, xn", "comp_g | comp_r: G = blob.Dert['G']; adj_G = blob.adj_blobs[2] borrow", "check for blob termination I, G, Dy, Dx, M, iDy,", "iDy, iDx, S, Ly = merged_blob.Dert.values() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy,", "blob # sub_blobs = find_adjacent(sub_blobs) if render: # rendering mode", "elif ~_mask: # prior dert is not masked # pack", "blob.box[0] = min(blob.box[0], merged_blob.box[0]) # extend box y0 blob.box[1] =", "layers are nested, multiple forks: no single set of fork", "# initialize new_stack with up_connect blob: new_stack = CDeepStack(I=I, G=G,", "mask = np.pad(blob.mask, ((y0 - y0e, yne - yn), (x0", "params: blob.fcr = fcr blob.fig = fig blob.rdn = rdn", "params: I += i iDy += idy iDx += idx", "merge P into higher-row stack of Ps with same sign", "overlap between loaded P and _P if P.sign == stack.sign:", "= object down_connect_cnt = int sign = NoneType class CDeepBlob(ClusterStructure):", "new x-overlapping Ps in next run of scan_P_ if blob.open_stacks", "iDx=iDx, S=L, Ly=1) new_stack.Py_.append(P) # Py_: vertical buffer of Ps", "blob. Please see diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob structure, for all layers", "merged_blob.box[1]) # extend box x0 blob.box[2] = max(blob.box[2], merged_blob.box[2]) #", "blobs form_blob(stack, root_dert__, sub_blobs) if stack_: # load stack with", "that has no connections in higher row: blob = CDeepBlob(Dert=dict(I=0,", "> aveB * rdn: # M - (intra_comp value lend", "per dert for x, (i, idy, idx, g, dy, dx,", "if render: streamer = BlobStreamer(CDeepBlob, crit__, mask) for y, dert_", "P_: P = P_.popleft() # load next P else: #", "_P, P in pairwise(P_): if _P.x0 + _P.L == P.x0:", "output eval by m, or clustering is always by m?", "# blob is terminated and packed in blob root: last_stack", "x0, xn = blob.box yn = last_stack.y0 + last_stack.Ly mask", "in sub_blobs: # evaluate for intra_blob comp_g | comp_r: G", "G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L,x0=x0, sign=_sign) P_.append(P) #", "P' up_connect_ else: binder.bind(_P, P) else: # -G, check for", "yn), (x0 - x0e, xne - xn)), mode='constant', constant_values=True) return", "assign higher cluster id for P next_stack_.append(new_stack) return next_stack_ def", "of 1st-level algorithm is a combination of frame_blobs, intra_blob, and", "in a row if prior dert is unmasked P =", "buffer P-connected higher-row stacks into P' up_connect_ else: binder.bind(_P, P)", "load stack with next _P stack = stack_.popleft() _P =", "(intra_comp value lend to edge blob) # comp_r fork: blob.sub_layers", "CDeepStack(ClusterStructure): I = int G = int Dy = int", "= blob.box # extend dert box: rY, rX = blob.root_dert__[0].shape", "fig, **kwargs) # fork params: blob.fcr = fcr blob.fig =", "G, Dy, Dx, M, iDy, iDx, L, x0, s =", "= max(0, y0 - 1) yne = min(rY, yn +", "and packed in blob root: last_stack = stack y0, x0,", "derts, each = i, idy, idx, g, dy, dx, m", "after blob conversion streamer.end_blob_conversion(y) return sub_blobs # clustering functions: #", "= blob # blobs in other up_connects are references to", "binder.bind(_P, P) else: # -G, check for orthogonal overlaps only:", "with next _P stack = stack_.popleft() _P = stack.Py_[-1] else:", "# else: comp_P_ elif sub_blob.Dert['G'] + borrow > aveB *", "root_dert__ = object dert__ = object mask = object adj_blobs", "up_connect_ = [] # list of same-sign x-overlapping _Ps per", "to stack_ in the next run of scan_P_ while P_:", "box xn P.hid = new_stack.id # assign higher cluster id", "horizontal ) vertical order P_ = deque() # row of", "of derts mask = mask_[x] if ~mask: # current dert", "0, 0, 0, 0, 0, 0, x + 1 if", "not masked # pack P P = CDeepP(I=I, G=G, Dy=Dy,", "+ _P.L == P.x0: # check if Ps are adjacents", "up_connect.hid = blob.id blob.stack_.append(up_connect) blob.open_stacks -= 1 # overlap with", "= blob.adj_blobs[2] borrow = min(abs(G), abs(adj_G) / 2) # or", "and stack_: # if both input row and higher row", "1: # terminate stack, merge it into up_connects' blobs form_blob(stack,", "size in y and x, least one dert in dert__", "blob termination I, G, Dy, Dx, M, iDy, iDx, S,", "P-connected higher-row stacks into P' up_connect_ else: binder.bind(_P, P) if", "blobs of other up_connects into blob of 1st up_connect if", "[sub_blobs ]: list of layers across sub_blob derivation tree #", "dert, from average m, reflects blob definition cost, may be", "intra_blob comp_g | comp_r: G = blob.Dert['G']; adj_G = blob.adj_blobs[2]", "dert__, mask = comp_r(ext_dert__, fig, fcr, ext_mask) # -> m", "iDy=iDy, iDx=iDx, S=S, Ly=Ly) # terminated stack is merged into", "2, fig=fig, fcr=1, **kwargs) # else: comp_P_ elif sub_blob.Dert['G'] +", "# Py_: vertical buffer of Ps new_stack.down_connect_cnt = 0 #", "sub_blobs) # merge stack of 1st up_connect into its blob", "masked next(dert_) x0 += 1 except IndexError: return P_ #", "gradient rdn, # redundancy to higher layers rng, # comp", "diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob structure, for all layers of blob hierarchy:", "enumerate(dert__): # in height, first and last row are discarded;", "if P_ and stack_: # if both input row and", "frame boundary if x0 == 0 or xn == root_dert__[0].shape[1]", "dert to boundaries) y0, yn, x0, xn = blob.box #", "higher layers rng, # comp range sub_layers # [sub_blobs ]:", "fopen = 0 # flag: blob on frame boundary if", "or # _P overlaps next P in P_ xn ==", "* rdn, fcr, fig, **kwargs) # fork params: blob.fcr =", "new_stack.hid = blob.id blob.stack_.append(new_stack) if len(up_connect_) > 1: # merge", "more selective if _x0 < xn and x0 < _xn:", "= int sign = NoneType class CDeepStack(ClusterStructure): I = int", "mask) for y, dert_ in enumerate(dert__): # in height, first", "fcr blob.fig = fig blob.rdn = rdn blob.rng = rng", "M=M, iDy=iDy, iDx=iDx, S=L, Ly=1, y0=y, Py_=[P], blob=blob, down_connect_cnt=0, sign=s)", "| p, fcr: flag comp over rng+ | der+ if", "dert is not masked sign = sign_[x] if ~_mask and", "at boundaries mask = np.pad(blob.mask, ((y0 - y0e, yne -", "blob, down_connect_cnt, sign = stack.unpack() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx,", "| der+ cross-comp within blob # fig: flag input is", "return an empty P I, iDy, iDx, G, Dy, Dx,", "start=stack.y0 - y0): x_start = P.x0 - x0 x_stop =", "discarded; print(f'Processing intra line {y}...') # if False in mask[i]:", "x_stop = x_start + P.L mask[y, x_start:x_stop] = False fopen", "(redundant) # I, iDy, iDx, G, Dy, Dx, M, L,", "form_blob(stack, root_dert__, sub_blobs): # increment blob with terminated stack, check", "iDx, G, Dy, Dx, M, L, x0 = 0, 0,", "of +v--vg: positive deviation of negated -vg triggers comp_r. Each", "_x0 = _P.x0 # first x in _P _xn =", "def scan_P_(P_, stack_, root_dert__, sub_blobs, binder): # merge P into", "if len(up_connect_) > 1: # merge blobs of all up_connects", "forks of extended internal cross-comparison and sub-clustering: der+: incremental derivation", "= list sign = NoneType open_stacks = int root_dert__ =", "horizontal clustering, adds a row of Ps if render: render", "rng, fig, fcr, **kwargs): # recursive input rng+ | der+", "S=L, Ly=1, y0=y, Py_=[P], blob=blob, down_connect_cnt=0, sign=s) new_stack.hid = blob.id", "sub_blobs per blob. Please see diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob structure, for", "# flag: blob on frame boundary if x0 == 0", "itertools import zip_longest from class_stream import BlobStreamer from utils import", "object adj_blobs = list fopen = bool margin = list", "else: # terminate loop if stack.down_connect_cnt != 1: # terminate", "next _P stack = stack_.popleft() _P = stack.Py_[-1] else: #", "line P_binder = AdjBinder(CDeepP) # binder needs data about clusters", "cross-comp in low-variation flat areas of +v--vg: positive deviation of", "any Ps / _Ps left P = P_.popleft() # load", "= I, iDy, iDx, G, Dy, Dx, M, S (area),", "of root_dert__ ext_dert__ = [derts[y0e:yne, x0e:xne] if derts is not", "m, or clustering is always by m? root_dert__ = dert__", "0 or yn == root_dert__[0].shape[0]: fopen = 1 blob.root_dert__ =", "L += 1 _sign = sign # prior sign _mask", "2) # or adjacent M if negative sign? if sub_blob.sign:", "comp_g output crit__ = dert__[6] - Ave # comp_g output", "redundancy to higher layers rng, # comp range sub_layers #", "comp_a? aveB = 50 # fixed cost per intra_blob comp", "if _x0 < xn and x0 < _xn: # x", "and clustering class CDeepP(ClusterStructure): I = int G = int", "# recursive input rng+ | der+ cross-comp within blob #", "line {y}...') # if False in mask[i]: # [y,x,params], there", "flag comp over rng+ | der+ if kwargs.get('render', None) is", "iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) # initialize P params: (redundant)", "= mask_[x] if ~mask: # current dert is not masked", "merge every P into its stack of Ps, merge blobs", "= *next(dert_), 1 # initialize P params _sign = sign_[x0]", "Dert: g in der+ fork, i+m in rng+ fork? fig,", "box x0 blob.box[2] = max(blob.box[2], xn) # extend box xn", "+ up_connect_ that finished scanning _P, will be converted into", "# from comp_P_draft import comp_P_blob # filters, All *= rdn:", "stack_, root_dert__, sub_blobs, binder): # merge P into higher-row stack", "else: binder.bind(_P, P) else: # -G, check for orthogonal overlaps", "# no up_connect while stack_: form_blob(stack_.popleft(), root_dert__, sub_blobs) # down_connect_cnt", "have any Ps / _Ps left P = P_.popleft() #", "int sign = NoneType class CDeepBlob(ClusterStructure): Dert = dict box", "dert and Dert: g in der+ fork, i+m in rng+", "= blob.id blob.stack_.append(up_connect) blob.open_stacks -= 1 # overlap with merged", "crit_, mask_, binder): # segment dert__ into P__, in horizontal", "a current row and may be extended with new x-overlapping", "dert box: rY, rX = blob.root_dert__[0].shape # higher dert size", "None else None for derts in blob.root_dert__] # pad mask:", "to higher layers rng, # comp range sub_layers # [sub_blobs", "in root_dert__] blob.mask = mask blob.adj_blobs = [[], 0, 0]", "stack_: # load stack with next _P stack = stack_.popleft()", "P.L mask[y, x_start:x_stop] = False fopen = 0 # flag:", "y0 blob.box[1] = min(blob.box[1], merged_blob.box[1]) # extend box x0 blob.box[2]", "is terminated and packed in blob root: last_stack = stack", "rdn + 1 + 1 / blob.Ls, rng=rng, fig=1, fcr=0,", "return next_P_ # each element is P + up_connect_ refs", "iDy=iDy, iDx=iDx, S=S, Ly=Ly) blob.open_stacks += merged_blob.open_stacks blob.box[0] = min(blob.box[0],", "of incomplete stacks == 0 # blob is terminated and", "int L = int x0 = int sign = NoneType", "run of scan_P_ while P_: P, up_connect_ = P_.popleft() I,", "== 0 or xn == root_dert__[0].shape[1] or y0 == 0", "- dert__[3] # eval by -g, accum in rng else:", "- x0), dtype=bool) # mask box, then unmask Ps: for", "else: # no next-P overlap if stack.down_connect_cnt != 1: #", "0, 0, 0, x elif _mask: I, iDy, iDx, G,", "stack_[ stack_params, Py_ [(P_params, dert_)]]: refs down blob formation tree,", "xne - xn)), mode='constant', constant_values=True) return ext_dert__, mask def accum_Dert(Dert:", "# check if Ps are adjacents binder.bind(_P, P) return P_", "overlap next_P_ = deque() # to recycle P + up_connect_", "ext_dert__, mask def accum_Dert(Dert: dict, **params) -> None: Dert.update({param: Dert[param]", "blobs form_blob(stack, root_dert__, sub_blobs) break else: # no next-P overlap", "extend box xn for stack in merged_blob.stack_: if not stack", "x0 += 1 except IndexError: return P_ # the whole", "P params _sign = sign_[x0] _mask = mask_[x0] # mask", "conversion. intra_blob recursively evaluates each blob for two forks of", "False in mask[i]: # [y,x,params], there is at least one", "sub_blobs, y): # Convert or merge every P into its", "x0 blob.box[2] = max(blob.box[2], xn) # extend box xn P.hid", "x0 < _xn: # x overlap between loaded P and", "dimension) # I: input, (iDy, iDx): angle of input gradient,", "evaluate for intra_blob comp_g | comp_r: G = blob.Dert['G']; adj_G", "+= idy iDx += idx G += g Dy +=", "= bool fig = bool rdn = float rng =", "vertical (horizontal) order # next fork: fcr, # flag comp", "# x overlap between loaded P and _P if P.sign", "Py_=[P], blob=blob, down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) if len(up_connect_)", "dert is not masked # pack P P = CDeepP(I=I,", "no next-P overlap if stack.down_connect_cnt != 1: # terminate stack,", "merged into continued or initialized blob (all connected stacks): blob.open_stacks", "L=L, x0=x0, sign=_sign) P_.append(P) # initialize P params: (redundant) #", "+ up_connect_ refs def form_stack_(P_, root_dert__, sub_blobs, y): # Convert", "1: # merge blobs of all up_connects if up_connect_[0].down_connect_cnt ==", "Dy = int Dx = int M = int iDy", "into P' up_connect_ else: binder.bind(_P, P) else: # -G, check", "Each adds a layer of sub_blobs per blob. Please see", "and next-fork rdn sub_layers = list # -------------------------------------------------------------------------------------------------------------- # functions,", "comp_g(ext_dert__, ext_mask) # -> g sub_blobs: if dert__[0].shape[0] > 2", "sub-clustering: der+: incremental derivation cross-comp in high-variation edge areas of", ") vertical order P_ = deque() # row of Ps", "refs def form_stack_(P_, root_dert__, sub_blobs, y): # Convert or merge", "!= 1: # terminate stack, merge it into up_connects' blobs", "functions, ALL WORK-IN-PROGRESS: def intra_blob(blob, rdn, rng, fig, fcr, **kwargs):", "y0, yn, x0, xn dert__, # box of derts, each", "[y, params, x] sub_blobs = [] # from form_blob: stack_", "and Dert: g in der+ fork, i+m in rng+ fork?", "deviation of gradient triggers comp_g, rng+: incremental range cross-comp in", "both P_ and stack_ are not empty x0 = P.x0", "= stack_.popleft() _P = stack.Py_[-1] else: # no stack left:", "combination of frame_blobs, intra_blob, and comp_P: optional raster-to-vector conversion. intra_blob", "borrow from flat blob) # comp_g fork: blob.sub_layers += intra_blob(sub_blob,", "size y0e = max(0, y0 - 1) yne = min(rY,", "# converted to stack_ in the next run of scan_P_", "min(blob.box[0], merged_blob.box[0]) # extend box y0 blob.box[1] = min(blob.box[1], merged_blob.box[1])", "open_stacks = int root_dert__ = object dert__ = object mask", "dy, dx, m stack_[ stack_params, Py_ [(P_params, dert_)]]: refs down", "into up_connects' blobs form_blob(stack, root_dert__, sub_blobs) break else: # no", "1 up_connect that has > 1 down_connect_cnt: blob = up_connect_[0].blob", "P in P_ xn == _xn and stack.sign): # sign", "stack.Py_[-1] else: # no stack left: terminate loop next_P_.append((P, up_connect_))", "P_ # the whole line is masked, return an empty", "= scan_P_(P_, stack_, root_dert__, sub_blobs, P_binder) # vertical clustering, adds", "incomplete stack cnt + terminated stack down_connect_cnt - 1: stack", "terminate and pack last P in a row if prior", "x0, xn) blob.dert__ = [derts[y0:yn, x0:xn] for derts in root_dert__]", "and lateral Ds, M: match sign, box, # y0, yn,", "sub_blobs, P_binder) # vertical clustering, adds up_connects per P and", "top, btm, left, right. 1 or 0 at boundaries mask", "= Ave - dert__[3] # eval by -g, accum in", "def form_blob(stack, root_dert__, sub_blobs): # increment blob with terminated stack,", "mask_, binder): # segment dert__ into P__, in horizontal )", "adjacent M if negative sign? if sub_blob.sign: if sub_blob.Dert['M'] -", "# down_connect_cnt always == 0 return next_P_ # each element", "stack for each input-row P that has no connections in", "extend dert box: rY, rX = blob.root_dert__[0].shape # higher dert", "into next_stack_ if P_ and stack_: # if both input", "down blob formation tree, in vertical (horizontal) order # next", "stack_binder = AdjBinder(CDeepStack) if render: streamer = BlobStreamer(CDeepBlob, crit__, mask)", "eval by -g, accum in rng else: # comp_g output", "+= 1 _sign = sign # prior sign _mask =", "= int sign = NoneType class CDeepBlob(ClusterStructure): Dert = dict", "x0 = 0 try: while mask_[x0]: # skip until not", "# sub_blobs = find_adjacent(sub_blobs) if render: # rendering mode after", "a row of Ps if render: render = streamer.update_blob_conversion(y, P_)", "stack_, root_dert__, sub_blobs, P_binder) # vertical clustering, adds up_connects per", "fcr, fig, render=False): # similar to frame_to_blobs if fcr: #", "blob.Ls, rng=rng, fig=1, fcr=0, **kwargs) # else: comp_P_ spliced_layers =", "into shape [y, params, x] sub_blobs = [] # from", "render: streamer = BlobStreamer(CDeepBlob, crit__, mask) if render: streamer =", "up_connect_[0].down_connect_cnt == 1: # up_connect is not terminated form_blob(up_connect_[0], root_dert__,", "idy iDx += idx G += g Dy += dy", "external blob if _x0 - 1 < xn and x0", "-G, check for orthogonal overlaps only: 4 directions, edge blobs", "while stack_: form_blob(stack_.popleft(), root_dert__, sub_blobs) # down_connect_cnt always == 0", "iDx, L, x0, s = P.unpack() xn = x0 +", "yn, x0, xn = blob.box # extend dert box: rY,", "is not None else None for derts in blob.root_dert__] #", "P params: I, iDy, iDx, G, Dy, Dx, M, L,", "_xn: # x overlap between loaded P and _P if", "len(up_connect_) == 1 and up_connect_[0].down_connect_cnt == 1: # P has", "= dert__[0] + dert__[6] - Ave # eval by i", "_P.x0 + _P.L == P.x0: # check if Ps are", "there is at least one dert in line P_binder =", "both input row and higher row have any Ps /", "None for derts in blob.root_dert__] # pad mask: top, btm,", "I, iDy, iDx, G, Dy, Dx, M, L, x0 =", "finished scanning _P, will be converted into next_stack_ if P_", "and sign != _sign: # prior dert is not masked", "streamer = BlobStreamer(CDeepBlob, crit__, mask) for y, dert_ in enumerate(dert__):", "stacks. up_connect.blob = blob up_connect.hid = blob.id blob.stack_.append(up_connect) blob.open_stacks -=", "next run of scan_P_ if blob.open_stacks == 0: # if", "sign=_sign) P_.append(P) for _P, P in pairwise(P_): if _P.x0 +", "dert__ = [*zip(*dert__)] # transpose dert__ into shape [y, params,", "_sign = sign # prior sign _mask = mask if", "down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) if len(up_connect_) > 1:", "= CDeepBlob(Dert=dict(I=0, G=0, Dy=0, Dx=0, M=0, iDy=0, iDx=0, S=0, Ly=0),", "of each stack is higher-row P up_connect_ = [] #", "while mask_[x0]: # skip until not masked next(dert_) x0 +=", "scan_P_ if blob.open_stacks == 0: # if number of incomplete", "sub_layers = list # -------------------------------------------------------------------------------------------------------------- # functions, ALL WORK-IN-PROGRESS: def", "= [] # list of same-sign x-overlapping _Ps per P", "M = int iDy = int iDx = int L", "buffer of Ps new_stack.down_connect_cnt = 0 # reset down_connect_cnt blob", "min size in y and x, least one dert in", "also clustering criterion in dert and Dert: g in der+", "# mask box, then unmask Ps: for stack in blob.stack_:", "iDx = int S = int Ly = int y0", "# extend box x0 blob.box[2] = max(blob.box[2], merged_blob.box[2]) # extend", "binder.bind(_P, P) return P_ def scan_P_(P_, stack_, root_dert__, sub_blobs, binder):", "class_cluster import ClusterStructure, NoneType from class_bind import AdjBinder from frame_blobs_yx", "I, iDy, iDx, G, Dy, Dx, M, S (area), Ly", "higher-row stack of Ps with same sign and x_coord overlap", "form_blob(up_connect_[0], root_dert__, sub_blobs) # merge stack of 1st up_connect into", "G, Dy, Dx, M, iDy, iDx, S, Ly = merged_blob.Dert.values()", "row: blob = CDeepBlob(Dert=dict(I=0, G=0, Dy=0, Dx=0, M=0, iDy=0, iDx=0,", "mask = np.ones((yn - y0, xn - x0), dtype=bool) #", "yn = last_stack.y0 + last_stack.Ly mask = np.ones((yn - y0,", "and x0 < _xn: # x overlap between loaded P", "= list # -------------------------------------------------------------------------------------------------------------- # functions, ALL WORK-IN-PROGRESS: def intra_blob(blob,", "dert__ sub_blobs = cluster_derts(dert__, mask, ave * rdn, fcr, fig,", "iDx, S, Ly = merged_blob.Dert.values() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx,", "of Ps sign_ = crit_ > 0 x0 = 0", "is at least one dert in line P_binder = AdjBinder(CDeepP)", "# similar to frame_to_blobs if fcr: # comp_r output; form", "mask if ~_mask: # terminate and pack last P in", "blob.Dert['S'] < 100: kwargs['render'] = False spliced_layers = [] #", "layers rng, # comp range sub_layers # [sub_blobs ]: list", "fig, render=False): # similar to frame_to_blobs if fcr: # comp_r", "G += g Dy += dy Dx += dx M", "Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) # terminated stack is", "- y0e, yne - yn), (x0 - x0e, xne -", "in P_ xn == _xn and stack.sign): # sign taken", "accum in rng else: # comp_g output crit__ = dert__[6]", "Dx, M, iDy, iDx, S, Ly, y0, Py_, blob, down_connect_cnt,", "comp and clustering class CDeepP(ClusterStructure): I = int G =", "continued or initialized blob (all connected stacks): blob.open_stacks += down_connect_cnt", "of Ps with same sign and x_coord overlap next_P_ =", "dert borders (+1 dert to boundaries) y0, yn, x0, xn", "# first x in P xn = x0 + P.L", "stack is higher-row P up_connect_ = [] # list of", "= int iDy = int iDx = int S =", "NoneType class CDeepStack(ClusterStructure): I = int G = int Dy", "= merged_blob.Dert.values() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx,", "next_P_ = deque() # to recycle P + up_connect_ that", "= min(blob.box[0], merged_blob.box[0]) # extend box y0 blob.box[1] = min(blob.box[1],", "break while P_: # terminate Ps and stacks that continue", "= P.unpack() xn = x0 + L # next-P x0", "if ~mask: # accumulate P params: I += i iDy", "Py_, blob, down_connect_cnt, sign = stack.unpack() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy,", "_P overlaps next P in P_ xn == _xn and", "transpose dert__ into shape [y, params, x] sub_blobs = []", "enumerate(dert_, start=x0+1): # loop left to right in each row", "up_connect and that up_connect has one down_connect=P: merge P into", "render: render = streamer.update_blob_conversion(y, P_) # if return False, stop", "with up_connect blob: new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M,", "[] # from form_blob: stack_ = deque() # buffer of", "Dx, M, iDy, iDx, L, x0, s = P.unpack() xn", "g, dy, dx, m stack_[ stack_params, Py_ [(P_params, dert_)]]: refs", "form_blob(stack_.popleft(), root_dert__, sub_blobs) blob_binder = AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder) # add", "dx, m) in enumerate(dert_, start=x0+1): # loop left to right", "return next_stack_ def form_blob(stack, root_dert__, sub_blobs): # increment blob with", "+ terminated stack down_connect_cnt - 1: stack itself # open", "in enumerate(stack.Py_, start=stack.y0 - y0): x_start = P.x0 - x0", "blob definition cost, may be different for comp_a? aveB =", "= max(blob.box[2], xn) # extend box xn P.hid = new_stack.id", "None) is not None: # stop rendering sub-blobs when blob", "# buffer of running vertical stacks of Ps stack_binder =", "x overlap between loaded P and _P if P.sign ==", "rng; dert__[:,:,0] if not transposed else: crit__ = Ave -", "merge blobs of all up_connects if up_connect_[0].down_connect_cnt == 1: #", "_xn or # _P overlaps next P in P_ xn", "higher-row stacks into P' up_connect_ else: binder.bind(_P, P) else: #", "_P stack = stack_.popleft() _P = stack.Py_[-1] else: # no", "# rendering mode after blob conversion streamer.end_blob_conversion(y) return sub_blobs #", "a blob may leak through its external blob if _x0", "fixed cost per dert, from average m, reflects blob definition", "+ sub_layers for spliced_layers, sub_layers in zip_longest(spliced_layers, blob.sub_layers, fillvalue=[])] return", "sub_blobs = [] # from form_blob: stack_ = deque() #", "x-overlapping _Ps per P while True: # while both P_", "1: # x overlap between loaded P and _P if", "if kwargs.get('render', None) is not None: # stop rendering sub-blobs", "sub_blobs: # evaluate for intra_blob comp_g | comp_r: G =", "= 50 # fixed cost per dert, from average m,", "Dy=0, Dx=0, M=0, iDy=0, iDx=0, S=0, Ly=0), box=[y, x0, xn],", "higher dert size # determine pad size y0e = max(0,", "and may be extended with new x-overlapping Ps in next", "= min(blob.box[1], merged_blob.box[1]) # extend box x0 blob.box[2] = max(blob.box[2],", "sub_blobs.append(blob) def extend_dert(blob): # extend dert borders (+1 dert to", "comp_g, rng+: incremental range cross-comp in low-variation flat areas of", "recursive input rng+ | der+ cross-comp within blob # fig:", "M, L = *next(dert_), 1 # initialize P params _sign", "merge stack of 1st up_connect into its blob for up_connect", "# prior sign _mask = mask if ~_mask: # terminate", "sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) if len(up_connect_) > 1: #", "# reset down_connect_cnt blob = new_stack.blob else: # if >", "root_dert__, sub_blobs, binder): # merge P into higher-row stack of", "root_dert__, sub_blobs, y) stack_binder.bind_from_lower(P_binder) while stack_: # frame ends, last-line", "masked # pack P P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx,", "for orthogonal overlaps only: 4 directions, edge blobs are more", "fig blob.rdn = rdn blob.rng = rng blob.Ls = len(sub_blobs)", "in mask[i]: # [y,x,params], there is at least one dert", "if both input row and higher row have any Ps", "blob up_connect.hid = blob.id blob.stack_.append(up_connect) blob.open_stacks -= 1 # overlap", "initialize P params: I, iDy, iDx, G, Dy, Dx, M,", "= find_adjacent(sub_blobs) if render: # rendering mode after blob conversion", "P.x0: # check if Ps are adjacents binder.bind(_P, P) return", "up_connect has one down_connect=P: merge P into up_connect stack: new_stack", "dert__[3] # eval by -g, accum in rng else: #", "in blob.stack_: for y, P in enumerate(stack.Py_, start=stack.y0 - y0):", "spliced_layers def cluster_derts(dert__, mask, Ave, fcr, fig, render=False): # similar", "y0=y, Py_=[P], blob=blob, down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) if", "max(0, y0 - 1) yne = min(rY, yn + 1)", "# -------------------------------------------------------------------------------------------------------------- # functions, ALL WORK-IN-PROGRESS: def intra_blob(blob, rdn, rng,", "open_stacks=1) new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M, iDy=iDy, iDx=iDx,", "G=0, Dy=0, Dx=0, M=0, iDy=0, iDx=0, S=0, Ly=0), box=[y, x0,", "= up_connect_[0] new_stack.accumulate(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L,", "= int y0 = int Py_ = list blob =", "sign and x_coord overlap next_P_ = deque() # to recycle", "in next run of scan_P_ if blob.open_stacks == 0: #", "mask: top, btm, left, right. 1 or 0 at boundaries", "sign? if sub_blob.sign: if sub_blob.Dert['M'] - borrow > aveB *", "Ps if render: render = streamer.update_blob_conversion(y, P_) # if return", "P) return P_ def scan_P_(P_, stack_, root_dert__, sub_blobs, binder): #", "rng blob.Ls = len(sub_blobs) # for visibility and next-fork rdn", "borrow > aveB * rdn: # M - (intra_comp value", "m, reflects blob definition cost, may be different for comp_a?", "clusters of the same level P_ = form_P_(zip(*dert_), crit__[y], mask[y],", "> 1 up_connects, or 1 up_connect that has > 1", "0] blob.fopen = fopen sub_blobs.append(blob) def extend_dert(blob): # extend dert", "mask_[x0]: # skip until not masked next(dert_) x0 += 1", "raster-to-vector conversion. intra_blob recursively evaluates each blob for two forks", "from class_cluster import ClusterStructure, NoneType from class_bind import AdjBinder from", "stack with next _P stack = stack_.popleft() _P = stack.Py_[-1]", "== 1 and up_connect_[0].down_connect_cnt == 1: # P has one", "def extend_dert(blob): # extend dert borders (+1 dert to boundaries)", "I, G, Dy, Dx, M, iDy, iDx, S, Ly, y0,", "+ 1) x0e = max(0, x0 - 1) xne =", "in the first up_connect. stack.hid = blob.id blob.stack_.append(stack) # buffer", "input gradient, G: gradient, (Dy, Dx): vertical and lateral Ds,", "is not masked # pack P P = CDeepP(I=I, G=G,", "is too small if blob.Dert['S'] < 100: kwargs['render'] = False", "crit__, mask) if render: streamer = BlobStreamer(CDeepBlob, crit__, mask) for", "of blob hierarchy: root_dert__, Dert = I, iDy, iDx, G,", "+= dx M += m L += 1 _sign =", "leak through its external blob if _x0 - 1 <", "8 directions, else a blob may leak through its external", "https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob structure, for all layers of blob hierarchy: root_dert__,", "(horizontal) order # next fork: fcr, # flag comp rng,", "always by m? root_dert__ = dert__ # derts after the", "# clustering functions: # ------------------------------------------------------------------------------------------------------------------- def form_P_(dert_, crit_, mask_, binder):", "binder needs data about clusters of the same level P_", "x0), dtype=bool) # mask box, then unmask Ps: for stack", "of a current row and may be extended with new", "* rdn: # G + (intra_comp value borrow from flat", "with merged blob. blob.box[1] = min(blob.box[1], x0) # extend box", "# comp_g output eval by m, or clustering is always", "to each blob # sub_blobs = find_adjacent(sub_blobs) if render: #", "margin = list fcr = bool fig = bool rdn", "# min size in y and x, least one dert", "are nested, multiple forks: no single set of fork params?", "form clustering criterion: if fig: crit__ = dert__[0] + dert__[6]", "of +vg: positive deviation of gradient triggers comp_g, rng+: incremental", "= int L = int x0 = int sign =", "# if return False, stop rendering P_ = scan_P_(P_, stack_,", "up_connect_ else: binder.bind(_P, P) if (xn < _xn or #", "_xn = _x0 + _P.L # first x beyond _P", "blob.Ls, rng * 2, fig=fig, fcr=1, **kwargs) # else: comp_P_", "import pairwise import numpy as np # from comp_P_draft import", "= [*zip(*dert__)] # transpose dert__ into shape [y, params, x]", "sign taken accounted next_P_.append((P, up_connect_)) # recycle _P for the", "class CDeepP(ClusterStructure): I = int G = int Dy =", "= BlobStreamer(CDeepBlob, crit__, mask) if render: streamer = BlobStreamer(CDeepBlob, crit__,", "Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1) new_stack.Py_.append(P) # Py_: vertical", "P params: (redundant) # I, iDy, iDx, G, Dy, Dx,", "# higher-row stacks _P = stack.Py_[-1] # last element of", "= int root_dert__ = object dert__ = object mask =", "Dx = int M = int iDy = int iDx", "vertical buffer of Ps new_stack.down_connect_cnt = 0 # reset down_connect_cnt", "xn], stack_=[], sign=s, open_stacks=1) new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx,", "stack.unpack() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S,", "x0 + L # next-P x0 if not up_connect_: #", "not masked next(dert_) x0 += 1 except IndexError: return P_", "s = P.unpack() xn = x0 + L # next-P", "if not up_connect.blob is blob: merged_blob = up_connect.blob I, G,", "clustering criterion in dert and Dert: g in der+ fork,", "yne - yn), (x0 - x0e, xne - xn)), mode='constant',", "1st up_connect into its blob for up_connect in up_connect_[1:len(up_connect_)]: #", "edge blob) # comp_r fork: blob.sub_layers += intra_blob(sub_blob, rdn +", "up_connect while stack_: form_blob(stack_.popleft(), root_dert__, sub_blobs) # down_connect_cnt always ==", "has one up_connect and that up_connect has one down_connect=P: merge", "up_connect into its blob for up_connect in up_connect_[1:len(up_connect_)]: # merge", "1: # P has one up_connect and that up_connect has", "Ly=Ly) blob.open_stacks += merged_blob.open_stacks blob.box[0] = min(blob.box[0], merged_blob.box[0]) # extend", "only: 4 directions, edge blobs are more selective if _x0", "order # next fork: fcr, # flag comp rng, also", "0, 0, 0, 0, 0, 0, x elif _mask: I,", "prior dert is not masked and sign changed # pack", "running vertical stacks of Ps stack_binder = AdjBinder(CDeepStack) if render:", "fopen = bool margin = list fcr = bool fig", "I, G, Dy, Dx, M, iDy, iDx, S, Ly =", "yne = min(rY, yn + 1) x0e = max(0, x0", "1 or 0 at boundaries mask = np.pad(blob.mask, ((y0 -", "operation, which is the root_dert__ dert__ = [*zip(*dert__)] # transpose", "blob (all connected stacks): blob.open_stacks += down_connect_cnt - 1 #", "gradient, G: gradient, (Dy, Dx): vertical and lateral Ds, M:", "up_connects per P and down_connect_cnt per stack stack_ = form_stack_(P_,", "+v--vg: positive deviation of negated -vg triggers comp_r. Each adds", "= sign_[x0] _mask = mask_[x0] # mask bit per dert", "first up_connect. stack.hid = blob.id blob.stack_.append(stack) # buffer of merged", "def form_P_(dert_, crit_, mask_, binder): # segment dert__ into P__,", "up_connect_[0].blob # initialize new_stack with up_connect blob: new_stack = CDeepStack(I=I,", "blob.box[2] = max(blob.box[2], merged_blob.box[2]) # extend box xn for stack", "y0, Py_, blob, down_connect_cnt, sign = stack.unpack() accum_Dert(blob.Dert, I=I, G=G,", "conversion streamer.end_blob_conversion(y) return sub_blobs # clustering functions: # ------------------------------------------------------------------------------------------------------------------- def", "masked and sign changed # pack P P = CDeepP(I=I,", "e is for extended # take ext_dert__ from part of", "0, 0, 0, 0, 0, 0, 0, x # current", "= P_.popleft() # load left-most (lowest-x) input-row P stack =", "every P into its stack of Ps, merge blobs next_stack_", "boundary if x0 == 0 or xn == root_dert__[0].shape[1] or", "# [y,x,params], there is at least one dert in line", "up_connect_.append(stack) # buffer P-connected higher-row stacks into P' up_connect_ else:", "if sub_blob.Dert['M'] - borrow > aveB * rdn: # M", "mask_[x] if ~mask: # current dert is not masked sign", "scan_P_ while P_: P, up_connect_ = P_.popleft() I, G, Dy,", "= int G = int Dy = int Dx =", "which is the root_dert__ dert__ = [*zip(*dert__)] # transpose dert__", "next-P x0 if not up_connect_: # initialize new stack for", "optional raster-to-vector conversion. intra_blob recursively evaluates each blob for two", "blob: new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M, iDy=iDy, iDx=iDx,", "in dert and Dert: g in der+ fork, i+m in", "input-row P that has no connections in higher row: blob", "current dert is masked elif ~_mask: # prior dert is", "stacks _P = stack.Py_[-1] # last element of each stack", "from itertools import zip_longest from class_stream import BlobStreamer from utils", "= int M = int iDy = int iDx =", "AdjBinder from frame_blobs_yx import assign_adjacents from intra_comp_g import comp_g, comp_r", "= deque() # to recycle P + up_connect_ that finished", "and stack.sign): # sign taken accounted next_P_.append((P, up_connect_)) # recycle", "rdn: # M - (intra_comp value lend to edge blob)", "stack_ = form_stack_(P_, root_dert__, sub_blobs, y) stack_binder.bind_from_lower(P_binder) while stack_: #", "frame_blobs, intra_blob, and comp_P: optional raster-to-vector conversion. intra_blob recursively evaluates", "while P_: # terminate Ps and stacks that continue at", "and stack_ are not empty x0 = P.x0 # first", "orthogonal overlaps only: 4 directions, edge blobs are more selective", "stack_.popleft() _P = stack.Py_[-1] else: # no stack left: terminate", "not masked sign = sign_[x] if ~_mask and sign !=", "Dx += dx M += m L += 1 _sign", "not masked and sign changed # pack P P =", "+= down_connect_cnt - 1 # incomplete stack cnt + terminated", "with same sign and x_coord overlap next_P_ = deque() #", "# frame ends, last-line stacks are merged into their blobs:", "binder): # segment dert__ into P__, in horizontal ) vertical", "mask: # min size in y and x, least one", "stacks that continue at row's end next_P_.append((P_.popleft(), [])) # no", "height, first and last row are discarded; print(f'Processing intra line", "is a combination of frame_blobs, intra_blob, and comp_P: optional raster-to-vector", "L # next-P x0 if not up_connect_: # initialize new", "or adjacent M if negative sign? if sub_blob.sign: if sub_blob.Dert['M']", "set of fork params? ''' from collections import deque, defaultdict", "blob.Dert['G']; adj_G = blob.adj_blobs[2] borrow = min(abs(G), abs(adj_G) / 2)", "# extend box xn for stack in merged_blob.stack_: if not", "ext_dert__ from part of root_dert__ ext_dert__ = [derts[y0e:yne, x0e:xne] if", "for extended # take ext_dert__ from part of root_dert__ ext_dert__", "i+m in rng+ fork? fig, # flag input is gradient", "idx, g, dy, dx, m stack_[ stack_params, Py_ [(P_params, dert_)]]:", "within blob # fig: flag input is g | p,", "is always by m? root_dert__ = dert__ # derts after", "dict, **params) -> None: Dert.update({param: Dert[param] + value for param,", "L=L, x0=x0, sign=_sign) P_.append(P) for _P, P in pairwise(P_): if", "!= _sign: # prior dert is not masked and sign", "= object adj_blobs = list fopen = bool margin =", "deque() # to recycle P + up_connect_ that finished scanning", "not up_connect_: # initialize new stack for each input-row P", "for each input-row P that has no connections in higher", "of other up_connects into blob of 1st up_connect if up_connect.down_connect_cnt", "0 x0 = 0 try: while mask_[x0]: # skip until", "blob_binder = AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder) # add adj_blobs to each", "terminate Ps and stacks that continue at row's end next_P_.append((P_.popleft(),", "return False, stop rendering P_ = scan_P_(P_, stack_, root_dert__, sub_blobs,", "of 1st up_connect if up_connect.down_connect_cnt == 1: form_blob(up_connect, root_dert__, sub_blobs)", "last P in a row if prior dert is unmasked", "1 blob.root_dert__ = root_dert__ blob.box = (y0, yn, x0, xn)", "P + up_connect_ that finished scanning _P, will be converted", "= 1 blob.root_dert__ = root_dert__ blob.box = (y0, yn, x0,", "up_connects into blob of 1st up_connect if up_connect.down_connect_cnt == 1:", "]: list of layers across sub_blob derivation tree # deeper", "size # determine pad size y0e = max(0, y0 -", "mask = object adj_blobs = list fopen = bool margin", "blob is terminated and packed in blob root: last_stack =", "to edge blob) # comp_r fork: blob.sub_layers += intra_blob(sub_blob, rdn", "return spliced_layers def cluster_derts(dert__, mask, Ave, fcr, fig, render=False): #", "render = streamer.update_blob_conversion(y, P_) # if return False, stop rendering", "blobs in other up_connects are references to blob in the", "iDy, iDx, G, Dy, Dx, M, L, x0 = 0,", "rng+ | der+ cross-comp within blob # fig: flag input", "Py_: vertical buffer of Ps new_stack.down_connect_cnt = 0 # reset", "next_P_.append((P, up_connect_)) break while P_: # terminate Ps and stacks", "cross-comp in high-variation edge areas of +vg: positive deviation of", "# deeper layers are nested, multiple forks: no single set", "last element of each stack is higher-row P up_connect_ =", "x beyond _P if stack.G > 0: # check for", "visibility and next-fork rdn blob.sub_layers = [sub_blobs] # 1st layer", "ALL WORK-IN-PROGRESS: def intra_blob(blob, rdn, rng, fig, fcr, **kwargs): #", "mask[i]: # [y,x,params], there is at least one dert in", "deque() # row of Ps sign_ = crit_ > 0", "0, 0, 0, 0, x + 1 if ~mask: #", "comp_g fork: blob.sub_layers += intra_blob(sub_blob, rdn + 1 + 1", "= stack.unpack() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx,", "stack.G > 0: # check for overlaps in 8 directions,", "+ P.L # first x beyond P _x0 = _P.x0", "transposed else: crit__ = Ave - dert__[3] # eval by", "overlap if stack.down_connect_cnt != 1: # terminate stack, merge it", "accum_Dert(Dert: dict, **params) -> None: Dert.update({param: Dert[param] + value for", "down_connect_cnt, sign = stack.unpack() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M,", "spliced_layers, sub_layers in zip_longest(spliced_layers, blob.sub_layers, fillvalue=[])] return spliced_layers def cluster_derts(dert__,", "[] if P_: P = P_.popleft() # load next P", "# initialize new stack for each input-row P that has", "= blob.id blob.stack_.append(stack) # buffer of merged root stacks. up_connect.blob", "> 2 and dert__[0].shape[1] > 2 and False in mask:", "each element is P + up_connect_ refs def form_stack_(P_, root_dert__,", "new_stack.id # assign higher cluster id for P next_stack_.append(new_stack) return", "if len(up_connect_) == 1 and up_connect_[0].down_connect_cnt == 1: # P", "M, iDy, iDx, S, Ly, y0, Py_, blob, down_connect_cnt, sign", "that finished scanning _P, will be converted into next_stack_ if", "Dy, Dx, M, iDy, iDx, L, x0, s = P.unpack()", "# comp_r output; form clustering criterion: if fig: crit__ =", "< _xn + 1: # x overlap between loaded P", "*= rdn: ave = 50 # fixed cost per dert,", "All *= rdn: ave = 50 # fixed cost per", "False in mask: # min size in y and x,", "Ps in next run of scan_P_ if blob.open_stacks == 0:", "spliced_layers = [] # to extend root_blob sub_layers ext_dert__, ext_mask", "or yn == root_dert__[0].shape[0]: fopen = 1 blob.root_dert__ = root_dert__", "streamer = BlobStreamer(CDeepBlob, crit__, mask) if render: streamer = BlobStreamer(CDeepBlob,", "P = P_.popleft() # load next P else: # terminate", "in y and x, least one dert in dert__ sub_blobs", "= streamer.update_blob_conversion(y, P_) # if return False, stop rendering P_", "x0 < _xn + 1: # x overlap between loaded", "stack_: # if both input row and higher row have", "blob.box[1] = min(blob.box[1], merged_blob.box[1]) # extend box x0 blob.box[2] =", "def cluster_derts(dert__, mask, Ave, fcr, fig, render=False): # similar to", "sub_blob in sub_blobs: # evaluate for intra_blob comp_g | comp_r:", "sub_layers in zip_longest(spliced_layers, blob.sub_layers, fillvalue=[])] return spliced_layers def cluster_derts(dert__, mask,", "version of 1st-level algorithm is a combination of frame_blobs, intra_blob,", "= int # for visibility and next-fork rdn sub_layers =", "M += m L += 1 _sign = sign #", "# eval by i + m, accum in rng; dert__[:,:,0]", "+ 1 if ~mask: # accumulate P params: I +=", "not transposed else: crit__ = Ave - dert__[3] # eval", "for up_connect in up_connect_[1:len(up_connect_)]: # merge blobs of other up_connects", "in pairwise(P_): if _P.x0 + _P.L == P.x0: # check", "cross-comp within blob # fig: flag input is g |", "# each element is P + up_connect_ refs def form_stack_(P_,", "negative sign? if sub_blob.sign: if sub_blob.Dert['M'] - borrow > aveB", "sign != _sign: # prior dert is not masked and", "each blob # sub_blobs = find_adjacent(sub_blobs) if render: # rendering", "and x_coord overlap next_P_ = deque() # to recycle P", "0, x # current dert is masked elif ~_mask: #", "from frame_blobs_yx import assign_adjacents from intra_comp_g import comp_g, comp_r from", "P_ and stack_ are not empty x0 = P.x0 #", "import comp_g, comp_r from itertools import zip_longest from class_stream import", "rdn + 1 + 1 / blob.Ls, rng * 2,", "50 # fixed cost per dert, from average m, reflects", "filters, All *= rdn: ave = 50 # fixed cost", "Ps stack_binder = AdjBinder(CDeepStack) if render: streamer = BlobStreamer(CDeepBlob, crit__,", "+= i iDy += idy iDx += idx G +=", "overlap with merged blob. blob.box[1] = min(blob.box[1], x0) # extend", "of frame_blobs, intra_blob, and comp_P: optional raster-to-vector conversion. intra_blob recursively", "layers of blob hierarchy: root_dert__, Dert = I, iDy, iDx,", "rng = int Ls = int # for visibility and", "# prior dert is not masked and sign changed #", "P.x0 - x0 x_stop = x_start + P.L mask[y, x_start:x_stop]", "extend dert borders (+1 dert to boundaries) y0, yn, x0,", "tree, in vertical (horizontal) order # next fork: fcr, #", "in high-variation edge areas of +vg: positive deviation of gradient", "or 0 at boundaries mask = np.pad(blob.mask, ((y0 - y0e,", "Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) blob.open_stacks += merged_blob.open_stacks", "stack, merge it into up_connects' blobs form_blob(stack, root_dert__, sub_blobs) break", "x0, xn], stack_=[], sign=s, open_stacks=1) new_stack = CDeepStack(I=I, G=G, Dy=0,", "each row of derts mask = mask_[x] if ~mask: #", "when blob is too small if blob.Dert['S'] < 100: kwargs['render']", "dert__[6] - Ave # eval by i + m, accum", "is higher-row P up_connect_ = [] # list of same-sign", "= [derts[y0e:yne, x0e:xne] if derts is not None else None", "_P if stack.G > 0: # check for overlaps in", "or xn == root_dert__[0].shape[1] or y0 == 0 or yn", "# first x in _P _xn = _x0 + _P.L", "if negative sign? if sub_blob.sign: if sub_blob.Dert['M'] - borrow >", "# -> m sub_blobs else: dert__, mask = comp_g(ext_dert__, ext_mask)", "stack stack_ = form_stack_(P_, root_dert__, sub_blobs, y) stack_binder.bind_from_lower(P_binder) while stack_:", "fcr=0, **kwargs) # else: comp_P_ spliced_layers = [spliced_layers + sub_layers", "skip until not masked next(dert_) x0 += 1 except IndexError:", "check for orthogonal overlaps only: 4 directions, edge blobs are", "m) in enumerate(dert_, start=x0+1): # loop left to right in", "dert is masked elif ~_mask: # prior dert is not", "_xn and stack.sign): # sign taken accounted next_P_.append((P, up_connect_)) #", "S (area), Ly (vertical dimension) # I: input, (iDy, iDx):", "current dert is not masked sign = sign_[x] if ~_mask", "== P.x0: # check if Ps are adjacents binder.bind(_P, P)", "P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L,", "Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) for", "len(up_connect_) > 1: # merge blobs of all up_connects if", "P_) # if return False, stop rendering P_ = scan_P_(P_,", "= mask_[x0] # mask bit per dert for x, (i,", "try: while mask_[x0]: # skip until not masked next(dert_) x0", "each blob for two forks of extended internal cross-comparison and", "sub_blobs, binder): # merge P into higher-row stack of Ps", "- y0, xn - x0), dtype=bool) # mask box, then", "= [[], 0, 0] blob.fopen = fopen sub_blobs.append(blob) def extend_dert(blob):", "aveB * rdn: # M - (intra_comp value lend to", "== root_dert__[0].shape[1] or y0 == 0 or yn == root_dert__[0].shape[0]:", "right in each row of derts mask = mask_[x] if", "Ps: for stack in blob.stack_: for y, P in enumerate(stack.Py_,", "triggers comp_g, rng+: incremental range cross-comp in low-variation flat areas", "import numpy as np # from comp_P_draft import comp_P_blob #", "P) else: # -G, check for orthogonal overlaps only: 4", "up_connects, or 1 up_connect that has > 1 down_connect_cnt: blob", "Dy, Dx, M, L, x0 = 0, 0, 0, 0,", "areas of +vg: positive deviation of gradient triggers comp_g, rng+:", "(lowest-x) input-row P stack = stack_.popleft() # higher-row stacks _P", "form_blob(stack_.popleft(), root_dert__, sub_blobs) # down_connect_cnt always == 0 return next_P_", "= NoneType open_stacks = int root_dert__ = object dert__ =", "determine pad size y0e = max(0, y0 - 1) yne", "P_ and stack_: # if both input row and higher", "sign_ = crit_ > 0 x0 = 0 try: while", "Dy, Dx, M, iDy, iDx, S, Ly, y0, Py_, blob,", "dert__ = object mask = object adj_blobs = list fopen", "while both P_ and stack_ are not empty x0 =", "derivation tree # deeper layers are nested, multiple forks: no", "blob.adj_blobs[2] borrow = min(abs(G), abs(adj_G) / 2) # or adjacent", "object dert__ = object mask = object adj_blobs = list", "x0, xn = blob.box # extend dert box: rY, rX", "+ 1: # x overlap between loaded P and _P", "= NoneType class CDeepBlob(ClusterStructure): Dert = dict box = list", "S=S, Ly=Ly) # terminated stack is merged into continued or", "one dert in line P_binder = AdjBinder(CDeepP) # binder needs", "< xn and x0 < _xn: # x overlap between", "iDy = int iDx = int S = int Ly", "# load stack with next _P stack = stack_.popleft() _P", "box, then unmask Ps: for stack in blob.stack_: for y,", "continue at row's end next_P_.append((P_.popleft(), [])) # no up_connect while", "stack_ are not empty x0 = P.x0 # first x", "the next run of scan_P_ up_connect_ = [] if P_:", "else None for derts in blob.root_dert__] # pad mask: top,", "merged root stacks. up_connect.blob = blob up_connect.hid = blob.id blob.stack_.append(up_connect)", "higher-row stacks into P' up_connect_ else: binder.bind(_P, P) if (xn", "merge P into up_connect stack: new_stack = up_connect_[0] new_stack.accumulate(I=I, G=G,", "np.pad(blob.mask, ((y0 - y0e, yne - yn), (x0 - x0e,", "are discarded; print(f'Processing intra line {y}...') # if False in", "P I, iDy, iDx, G, Dy, Dx, M, L =", "range cross-comp in low-variation flat areas of +v--vg: positive deviation", "P stack = stack_.popleft() # higher-row stacks _P = stack.Py_[-1]", "L = *next(dert_), 1 # initialize P params _sign =", "of Ps if render: render = streamer.update_blob_conversion(y, P_) # if", "Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1) new_stack.Py_.append(P) # Py_:", "blob=blob, down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) if len(up_connect_) >", "for the next run of scan_P_ up_connect_ = [] if", "comp_r(ext_dert__, fig, fcr, ext_mask) # -> m sub_blobs else: dert__,", "dert for x, (i, idy, idx, g, dy, dx, m)", "cost, may be different for comp_a? aveB = 50 #", "- borrow > aveB * rdn: # M - (intra_comp", "M = int iDy = int iDx = int S", "stack_: form_blob(stack_.popleft(), root_dert__, sub_blobs) # down_connect_cnt always == 0 return", "mask = comp_r(ext_dert__, fig, fcr, ext_mask) # -> m sub_blobs", "dert__ into P__, in horizontal ) vertical order P_ =", "iDy, iDx, G, Dy, Dx, M, S (area), Ly (vertical", "dert__[:,:,0] if not transposed else: crit__ = Ave - dert__[3]", "find_adjacent(sub_blobs) if render: # rendering mode after blob conversion streamer.end_blob_conversion(y)", "else: dert__, mask = comp_g(ext_dert__, ext_mask) # -> g sub_blobs:", "to recycle P + up_connect_ that finished scanning _P, will", "comp_r from itertools import zip_longest from class_stream import BlobStreamer from", "flag: blob on frame boundary if x0 == 0 or", "stop rendering P_ = scan_P_(P_, stack_, root_dert__, sub_blobs, P_binder) #", "adj_G = blob.adj_blobs[2] borrow = min(abs(G), abs(adj_G) / 2) #", "connections in higher row: blob = CDeepBlob(Dert=dict(I=0, G=0, Dy=0, Dx=0,", "into up_connect stack: new_stack = up_connect_[0] new_stack.accumulate(I=I, G=G, Dy=Dy, Dx=Dx,", "der+ if kwargs.get('render', None) is not None: # stop rendering", "idx, g, dy, dx, m) in enumerate(dert_, start=x0+1): # loop", "stack_=[], sign=s, open_stacks=1) new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M,", "utils import pairwise import numpy as np # from comp_P_draft", "int Dx = int M = int iDy = int", "not None: # stop rendering sub-blobs when blob is too", "next_P_.append((P, up_connect_)) # recycle _P for the next run of", "M, iDy, iDx, L, x0, s = P.unpack() xn =", "extend box y0 blob.box[1] = min(blob.box[1], merged_blob.box[1]) # extend box", "sign_[x] if ~_mask and sign != _sign: # prior dert", "and down_connect_cnt per stack stack_ = form_stack_(P_, root_dert__, sub_blobs, y)", "if ~_mask: # terminate and pack last P in a", "sub_blob.Dert['G'] + borrow > aveB * rdn: # G +", "comp_g, comp_r from itertools import zip_longest from class_stream import BlobStreamer", "comp_r output; form clustering criterion: if fig: crit__ = dert__[0]", "# horizontal clustering, adds a row of Ps if render:", "for visibility and next-fork rdn sub_layers = list # --------------------------------------------------------------------------------------------------------------", "sub_blobs) # down_connect_cnt always == 0 return next_P_ # each", "= int iDy = int iDx = int L =", "into continued or initialized blob (all connected stacks): blob.open_stacks +=", "yn + 1) x0e = max(0, x0 - 1) xne", "1 # incomplete stack cnt + terminated stack down_connect_cnt -", "- 1 < xn and x0 < _xn + 1:", "y0, x0, xn = blob.box yn = last_stack.y0 + last_stack.Ly", "will be converted into next_stack_ if P_ and stack_: #", "if number of incomplete stacks == 0 # blob is", "structure, for all layers of blob hierarchy: root_dert__, Dert =", "element of each stack is higher-row P up_connect_ = []", "Ds, M: match sign, box, # y0, yn, x0, xn", "g sub_blobs: if dert__[0].shape[0] > 2 and dert__[0].shape[1] > 2", "break else: # no next-P overlap if stack.down_connect_cnt != 1:", "from collections import deque, defaultdict from class_cluster import ClusterStructure, NoneType", "I, G, Dy, Dx, M, iDy, iDx, L, x0, s", "blob.box[2] = max(blob.box[2], xn) # extend box xn P.hid =", "per intra_blob comp and clustering class CDeepP(ClusterStructure): I = int", "= _P.x0 # first x in _P _xn = _x0", "initialize new_stack with up_connect blob: new_stack = CDeepStack(I=I, G=G, Dy=0,", "streamer.update_blob_conversion(y, P_) # if return False, stop rendering P_ =", "import assign_adjacents from intra_comp_g import comp_g, comp_r from itertools import", "into higher-row stack of Ps with same sign and x_coord", "sign=s, open_stacks=1) new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M, iDy=iDy,", "_x0 + _P.L # first x beyond _P if stack.G", "one down_connect=P: merge P into up_connect stack: new_stack = up_connect_[0]", "+= m L += 1 _sign = sign # prior", "sub_blobs) break else: # no next-P overlap if stack.down_connect_cnt !=", "dert size # determine pad size y0e = max(0, y0", "# extend dert borders (+1 dert to boundaries) y0, yn,", "x, (i, idy, idx, g, dy, dx, m) in enumerate(dert_,", "and dert__[0].shape[1] > 2 and False in mask: # min", "per stack stack_ = form_stack_(P_, root_dert__, sub_blobs, y) stack_binder.bind_from_lower(P_binder) while", "P.unpack() xn = x0 + L # next-P x0 if", "is up_connect: stack.blob = blob # blobs in other up_connects", "terminate loop next_P_.append((P, up_connect_)) break while P_: # terminate Ps", "int G = int Dy = int Dx = int", "iDx = int L = int x0 = int sign", "M=M, iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) # initialize P", "up_connect. stack.hid = blob.id blob.stack_.append(stack) # buffer of merged root", "# extend box x0 blob.box[2] = max(blob.box[2], xn) # extend", "Ly=Ly) # terminated stack is merged into continued or initialized", "P' up_connect_ else: binder.bind(_P, P) if (xn < _xn or", "= 0 try: while mask_[x0]: # skip until not masked", "int iDx = int S = int Ly = int", "1) yne = min(rY, yn + 1) x0e = max(0,", "**params) -> None: Dert.update({param: Dert[param] + value for param, value", "= fopen sub_blobs.append(blob) def extend_dert(blob): # extend dert borders (+1", "[y,x,params], there is at least one dert in line P_binder", "sign = NoneType class CDeepBlob(ClusterStructure): Dert = dict box =", "= mask blob.adj_blobs = [[], 0, 0] blob.fopen = fopen", "crit__ = dert__[6] - Ave # comp_g output eval by", "# prior dert is not masked # pack P P", "iDx=iDx, S=S, Ly=Ly) # terminated stack is merged into continued", "no connections in higher row: blob = CDeepBlob(Dert=dict(I=0, G=0, Dy=0,", "y0, yn, x0, xn = blob.box # extend dert box:", "up_connect_)) # recycle _P for the next run of scan_P_", "= stack.Py_[-1] else: # no stack left: terminate loop next_P_.append((P,", "the root_dert__ dert__ = [*zip(*dert__)] # transpose dert__ into shape", "blob.dert__ = [derts[y0:yn, x0:xn] for derts in root_dert__] blob.mask =", "rng=rng, fig=1, fcr=0, **kwargs) # else: comp_P_ spliced_layers = [spliced_layers", "mask def accum_Dert(Dert: dict, **params) -> None: Dert.update({param: Dert[param] +", "beyond _P if stack.G > 0: # check for overlaps", "# if > 1 up_connects, or 1 up_connect that has", "= blob up_connect.hid = blob.id blob.stack_.append(up_connect) blob.open_stacks -= 1 #", "while True: # while both P_ and stack_ are not", "rng, # comp range sub_layers # [sub_blobs ]: list of", "zip_longest(spliced_layers, blob.sub_layers, fillvalue=[])] return spliced_layers def cluster_derts(dert__, mask, Ave, fcr,", "stack_: # frame ends, last-line stacks are merged into their", "if render: streamer = BlobStreamer(CDeepBlob, crit__, mask) if render: streamer", "P_binder) # vertical clustering, adds up_connects per P and down_connect_cnt", "mask_[x0] # mask bit per dert for x, (i, idy,", "crit__ = Ave - dert__[3] # eval by -g, accum", "last row are discarded; print(f'Processing intra line {y}...') # if", "+ 1 + 1 / blob.Ls, rng * 2, fig=fig,", "blob.open_stacks == 0: # if number of incomplete stacks ==", "# initialize P params: (redundant) # I, iDy, iDx, G,", "1 # initialize P params _sign = sign_[x0] _mask =", "1 _sign = sign # prior sign _mask = mask", "with terminated stack, check for blob termination I, G, Dy,", "blob conversion streamer.end_blob_conversion(y) return sub_blobs # clustering functions: # -------------------------------------------------------------------------------------------------------------------", "next P else: # terminate loop if stack.down_connect_cnt != 1:", "= max(blob.box[2], merged_blob.box[2]) # extend box xn for stack in", "the next run of scan_P_ while P_: P, up_connect_ =", "list blob = object down_connect_cnt = int sign = NoneType", "# [sub_blobs ]: list of layers across sub_blob derivation tree", "object mask = object adj_blobs = list fopen = bool", "0 at boundaries mask = np.pad(blob.mask, ((y0 - y0e, yne", "<filename>frame_2D_alg/alternative versions/intra_blob_xy.py<gh_stars>0 ''' 2D version of 1st-level algorithm is a", "extend box x0 blob.box[2] = max(blob.box[2], xn) # extend box", "= BlobStreamer(CDeepBlob, crit__, mask) for y, dert_ in enumerate(dert__): #", "stack_binder.bind_from_lower(P_binder) while stack_: # frame ends, last-line stacks are merged", "fcr: dert__, mask = comp_r(ext_dert__, fig, fcr, ext_mask) # ->", "= 50 # fixed cost per intra_blob comp and clustering", "has no connections in higher row: blob = CDeepBlob(Dert=dict(I=0, G=0,", "rendering P_ = scan_P_(P_, stack_, root_dert__, sub_blobs, P_binder) # vertical", "= up_connect_[0].blob # initialize new_stack with up_connect blob: new_stack =", "x0e = max(0, x0 - 1) xne = min(rX, xn", "adj_blobs to each blob # sub_blobs = find_adjacent(sub_blobs) if render:", "assign_adjacents from intra_comp_g import comp_g, comp_r from itertools import zip_longest", "= int S = int Ly = int y0 =", "stacks contain Ps of a current row and may be", "be converted into next_stack_ if P_ and stack_: # if", "for visibility and next-fork rdn blob.sub_layers = [sub_blobs] # 1st", "0, 0, 0, 0, 0, 0, x # current dert", "M=0, iDy=0, iDx=0, S=0, Ly=0), box=[y, x0, xn], stack_=[], sign=s,", "is not masked sign = sign_[x] if ~_mask and sign", "= list blob = object down_connect_cnt = int sign =", "is masked elif ~_mask: # prior dert is not masked", "import ClusterStructure, NoneType from class_bind import AdjBinder from frame_blobs_yx import", "# extend box xn P.hid = new_stack.id # assign higher", "deque() # buffer of running vertical stacks of Ps stack_binder", "new_stack with up_connect blob: new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx,", "merge blobs next_stack_ = deque() # converted to stack_ in", "der+ fork, i+m in rng+ fork? fig, # flag input", "Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1, y0=y, Py_=[P], blob=blob, down_connect_cnt=0,", "= new_stack.blob else: # if > 1 up_connects, or 1", "= np.ones((yn - y0, xn - x0), dtype=bool) # mask", "+ borrow > aveB * rdn: # G + (intra_comp", "blob = object down_connect_cnt = int sign = NoneType class", "# accumulate P params: I += i iDy += idy", "import comp_P_blob # filters, All *= rdn: ave = 50", "same sign and x_coord overlap next_P_ = deque() # to", "def form_stack_(P_, root_dert__, sub_blobs, y): # Convert or merge every", "= False spliced_layers = [] # to extend root_blob sub_layers", "to frame_to_blobs if fcr: # comp_r output; form clustering criterion:", "(Dy, Dx): vertical and lateral Ds, M: match sign, box,", "derts in blob.root_dert__] # pad mask: top, btm, left, right.", "= CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L, x0=x0,", "== _xn and stack.sign): # sign taken accounted next_P_.append((P, up_connect_))", "root_dert__, sub_blobs, y): # Convert or merge every P into", "sub_blob.sign: if sub_blob.Dert['M'] - borrow > aveB * rdn: #", "~mask: # current dert is not masked sign = sign_[x]", "root_dert__ blob.box = (y0, yn, x0, xn) blob.dert__ = [derts[y0:yn,", "# higher dert size # determine pad size y0e =", "list fopen = bool margin = list fcr = bool", "render: # rendering mode after blob conversion streamer.end_blob_conversion(y) return sub_blobs", "derts in root_dert__] blob.mask = mask blob.adj_blobs = [[], 0,", "overlaps in 8 directions, else a blob may leak through", "- 1) yne = min(rY, yn + 1) x0e =", "# next-P x0 if not up_connect_: # initialize new stack", "take ext_dert__ from part of root_dert__ ext_dert__ = [derts[y0e:yne, x0e:xne]", "average m, reflects blob definition cost, may be different for", "= bool margin = list fcr = bool fig =", "intra_blob(sub_blob, rdn + 1 + 1 / blob.Ls, rng *", "crit_ > 0 x0 = 0 try: while mask_[x0]: #", "> 1 down_connect_cnt: blob = up_connect_[0].blob # initialize new_stack with", "# extend box y0 blob.box[1] = min(blob.box[1], merged_blob.box[1]) # extend", "stack down_connect_cnt - 1: stack itself # open stacks contain", "reset down_connect_cnt blob = new_stack.blob else: # if > 1", "P into its stack of Ps, merge blobs next_stack_ =", "P) if (xn < _xn or # _P overlaps next", "x in P xn = x0 + P.L # first", "each = i, idy, idx, g, dy, dx, m stack_[", "P__, in horizontal ) vertical order P_ = deque() #", "0, 0, 0, 0, 0, 0, 0, 0, x elif", "blob.box # extend dert box: rY, rX = blob.root_dert__[0].shape #", "''' 2D version of 1st-level algorithm is a combination of", "form_stack_(P_, root_dert__, sub_blobs, y) stack_binder.bind_from_lower(P_binder) while stack_: # frame ends,", "np.ones((yn - y0, xn - x0), dtype=bool) # mask box,", "up_connect_)) break while P_: # terminate Ps and stacks that", "stack is up_connect: stack.blob = blob # blobs in other", "pairwise import numpy as np # from comp_P_draft import comp_P_blob", "x0e:xne] if derts is not None else None for derts", "/ blob.Ls, rng * 2, fig=fig, fcr=1, **kwargs) # else:", "row if prior dert is unmasked P = CDeepP(I=I, G=G,", "xn = x0 + P.L # first x beyond P", "blob: merged_blob = up_connect.blob I, G, Dy, Dx, M, iDy,", "or 1 up_connect that has > 1 down_connect_cnt: blob =", "_mask: I, iDy, iDx, G, Dy, Dx, M, L, x0", "between loaded P and _P if P.sign == stack.sign: #", "if render: render = streamer.update_blob_conversion(y, P_) # if return False,", "with new x-overlapping Ps in next run of scan_P_ if", "x_coord overlap next_P_ = deque() # to recycle P +", "fcr: # comp_r output; form clustering criterion: if fig: crit__", "pack last P in a row if prior dert is", "flat areas of +v--vg: positive deviation of negated -vg triggers", "0, 0, 0, 0, 0, 0, 0, x elif _mask:", "up_connect in up_connect_[1:len(up_connect_)]: # merge blobs of other up_connects into", "recycle P + up_connect_ that finished scanning _P, will be", "_P.L # first x beyond _P if stack.G > 0:", "False fopen = 0 # flag: blob on frame boundary", "are references to blob in the first up_connect. stack.hid =", "criterion in dert and Dert: g in der+ fork, i+m", "are merged into their blobs: form_blob(stack_.popleft(), root_dert__, sub_blobs) blob_binder =", "P_ = deque() # row of Ps sign_ = crit_", "y0 == 0 or yn == root_dert__[0].shape[0]: fopen = 1", "hierarchy: root_dert__, Dert = I, iDy, iDx, G, Dy, Dx,", "always == 0 return next_P_ # each element is P", "extend_dert(blob): # extend dert borders (+1 dert to boundaries) y0,", "== 0 # blob is terminated and packed in blob", "not stack is up_connect: stack.blob = blob # blobs in", "positive deviation of gradient triggers comp_g, rng+: incremental range cross-comp", "or initialized blob (all connected stacks): blob.open_stacks += down_connect_cnt -", "= [derts[y0:yn, x0:xn] for derts in root_dert__] blob.mask = mask", "else: crit__ = Ave - dert__[3] # eval by -g,", "up_connect stack: new_stack = up_connect_[0] new_stack.accumulate(I=I, G=G, Dy=Dy, Dx=Dx, M=M,", "if fig: crit__ = dert__[0] + dert__[6] - Ave #", "fork: fcr, # flag comp rng, also clustering criterion in", "stack.sign): # sign taken accounted next_P_.append((P, up_connect_)) # recycle _P", "ext_mask = extend_dert(blob) if fcr: dert__, mask = comp_r(ext_dert__, fig,", "[(P_params, dert_)]]: refs down blob formation tree, in vertical (horizontal)", "0, 0] blob.fopen = fopen sub_blobs.append(blob) def extend_dert(blob): # extend", "blob=blob, down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) else: if len(up_connect_)", "params, x] sub_blobs = [] # from form_blob: stack_ =", "dert__, mask = comp_g(ext_dert__, ext_mask) # -> g sub_blobs: if", "Dy, Dx, M, iDy, iDx, S, Ly = merged_blob.Dert.values() accum_Dert(blob.Dert,", "id for P next_stack_.append(new_stack) return next_stack_ def form_blob(stack, root_dert__, sub_blobs):", "comp_r: G = blob.Dert['G']; adj_G = blob.adj_blobs[2] borrow = min(abs(G),", "rY, rX = blob.root_dert__[0].shape # higher dert size # determine", "# terminate stack, merge it into up_connects' blobs form_blob(stack, root_dert__,", "stack.hid = blob.id blob.stack_.append(stack) # buffer of merged root stacks.", "(+1 dert to boundaries) y0, yn, x0, xn = blob.box", "= AdjBinder(CDeepP) # binder needs data about clusters of the", "# current dert is masked elif ~_mask: # prior dert", "= [] if P_: P = P_.popleft() # load next", "part of root_dert__ ext_dert__ = [derts[y0e:yne, x0e:xne] if derts is", "x0=x0, sign=_sign) P_.append(P) # initialize P params: (redundant) # I,", "root_dert__[0].shape[1] or y0 == 0 or yn == root_dert__[0].shape[0]: fopen", "NoneType open_stacks = int root_dert__ = object dert__ = object", "= dict box = list stack_ = list sign =", "CDeepBlob(ClusterStructure): Dert = dict box = list stack_ = list", "P_ def scan_P_(P_, stack_, root_dert__, sub_blobs, binder): # merge P", "merged_blob.box[2]) # extend box xn for stack in merged_blob.stack_: if", "0, 0, x # current dert is masked elif ~_mask:", "else: # if > 1 up_connects, or 1 up_connect that", "1 if ~mask: # accumulate P params: I += i", "fig: flag input is g | p, fcr: flag comp", "Ps new_stack.down_connect_cnt = 0 # reset down_connect_cnt blob = new_stack.blob", "# derts after the comps operation, which is the root_dert__", "rdn blob.rng = rng blob.Ls = len(sub_blobs) # for visibility", "= form_P_(zip(*dert_), crit__[y], mask[y], P_binder) # horizontal clustering, adds a", "if stack.down_connect_cnt != 1: # terminate stack, merge it into", "cost per intra_blob comp and clustering class CDeepP(ClusterStructure): I =", "return sub_blobs # clustering functions: # ------------------------------------------------------------------------------------------------------------------- def form_P_(dert_, crit_,", "extend root_blob sub_layers ext_dert__, ext_mask = extend_dert(blob) if fcr: dert__,", "areas of +v--vg: positive deviation of negated -vg triggers comp_r.", "no stack left: terminate loop next_P_.append((P, up_connect_)) break while P_:", "# merge blobs of all up_connects if up_connect_[0].down_connect_cnt == 1:", "root_dert__, sub_blobs, P_binder) # vertical clustering, adds up_connects per P", "[[], 0, 0] blob.fopen = fopen sub_blobs.append(blob) def extend_dert(blob): #", "fig=1, fcr=0, **kwargs) # else: comp_P_ spliced_layers = [spliced_layers +", "= new_stack.id # assign higher cluster id for P next_stack_.append(new_stack)", "for all layers of blob hierarchy: root_dert__, Dert = I,", "dy Dx += dx M += m L += 1", "box, # y0, yn, x0, xn dert__, # box of", "adds up_connects per P and down_connect_cnt per stack stack_ =", "if blob.Dert['S'] < 100: kwargs['render'] = False spliced_layers = []", "m L += 1 _sign = sign # prior sign", "down_connect_cnt = int sign = NoneType class CDeepBlob(ClusterStructure): Dert =", "be extended with new x-overlapping Ps in next run of", "- y0): x_start = P.x0 - x0 x_stop = x_start", "two forks of extended internal cross-comparison and sub-clustering: der+: incremental", "sub_layers ext_dert__, ext_mask = extend_dert(blob) if fcr: dert__, mask =", "merged_blob = up_connect.blob I, G, Dy, Dx, M, iDy, iDx,", "= 0, 0, 0, 0, 0, 0, 0, 0, x", "match sign, box, # y0, yn, x0, xn dert__, #", "+ 1 / blob.Ls, rng=rng, fig=1, fcr=0, **kwargs) # else:", "Ly (vertical dimension) # I: input, (iDy, iDx): angle of", "P_ xn == _xn and stack.sign): # sign taken accounted", "ext_dert__ = [derts[y0e:yne, x0e:xne] if derts is not None else", "P xn = x0 + P.L # first x beyond", "from average m, reflects blob definition cost, may be different", "P.hid = new_stack.id # assign higher cluster id for P", "scan_P_(P_, stack_, root_dert__, sub_blobs, binder): # merge P into higher-row", "# assign higher cluster id for P next_stack_.append(new_stack) return next_stack_", "lend to edge blob) # comp_r fork: blob.sub_layers += intra_blob(sub_blob,", "blob.box yn = last_stack.y0 + last_stack.Ly mask = np.ones((yn -", "blob # blobs in other up_connects are references to blob", "> 0: # check for overlaps in 8 directions, else", "G + (intra_comp value borrow from flat blob) # comp_g", "if False in mask[i]: # [y,x,params], there is at least", "stack itself # open stacks contain Ps of a current", "may be different for comp_a? aveB = 50 # fixed", "in line P_binder = AdjBinder(CDeepP) # binder needs data about", "sign_[x0] _mask = mask_[x0] # mask bit per dert for", "= (y0, yn, x0, xn) blob.dert__ = [derts[y0:yn, x0:xn] for", "S=0, Ly=0), box=[y, x0, xn], stack_=[], sign=s, open_stacks=1) new_stack =", "new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L,", "stack.down_connect_cnt += 1 up_connect_.append(stack) # buffer P-connected higher-row stacks into", "idy, idx, g, dy, dx, m stack_[ stack_params, Py_ [(P_params,", "x + 1 if ~mask: # accumulate P params: I", "blob may leak through its external blob if _x0 -", "P has one up_connect and that up_connect has one down_connect=P:", "of negated -vg triggers comp_r. Each adds a layer of", "for x, (i, idy, idx, g, dy, dx, m) in", "blob.box[1] = min(blob.box[1], x0) # extend box x0 blob.box[2] =", "blob formation tree, in vertical (horizontal) order # next fork:", "# box of derts, each = i, idy, idx, g,", "Dx, M, L = *next(dert_), 1 # initialize P params", "extended internal cross-comparison and sub-clustering: der+: incremental derivation cross-comp in", "list of layers across sub_blob derivation tree # deeper layers", "0, 0, 0, 0, 0, 0, 0, 0, x +", "overlaps next P in P_ xn == _xn and stack.sign):", "borrow > aveB * rdn: # G + (intra_comp value", "while P_: P, up_connect_ = P_.popleft() I, G, Dy, Dx,", "last-line stacks are merged into their blobs: form_blob(stack_.popleft(), root_dert__, sub_blobs)", "fork, i+m in rng+ fork? fig, # flag input is", "[*zip(*dert__)] # transpose dert__ into shape [y, params, x] sub_blobs", "to boundaries) y0, yn, x0, xn = blob.box # extend", "1 < xn and x0 < _xn + 1: #", "from intra_comp_g import comp_g, comp_r from itertools import zip_longest from", "is not terminated form_blob(up_connect_[0], root_dert__, sub_blobs) # merge stack of", "- 1: stack itself # open stacks contain Ps of", "== 1: # P has one up_connect and that up_connect", "+ 1) # e is for extended # take ext_dert__", "100: kwargs['render'] = False spliced_layers = [] # to extend", "# P has one up_connect and that up_connect has one", "+ 1 / blob.Ls, rng * 2, fig=fig, fcr=1, **kwargs)", "_sign: # prior dert is not masked and sign changed", "Ly=1) new_stack.Py_.append(P) # Py_: vertical buffer of Ps new_stack.down_connect_cnt =", "else: # no stack left: terminate loop next_P_.append((P, up_connect_)) break", "else: if len(up_connect_) == 1 and up_connect_[0].down_connect_cnt == 1: #", "fig, fcr, ext_mask) # -> m sub_blobs else: dert__, mask", "row are discarded; print(f'Processing intra line {y}...') # if False", "Ly=1, y0=y, Py_=[P], blob=blob, down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack)", "comp_P_blob # filters, All *= rdn: ave = 50 #", "= NoneType class CDeepStack(ClusterStructure): I = int G = int", "= P_.popleft() # load next P else: # terminate loop", "of scan_P_ up_connect_ = [] if P_: P = P_.popleft()", "elif sub_blob.Dert['G'] + borrow > aveB * rdn: # G", "through its external blob if _x0 - 1 < xn", "= [] # to extend root_blob sub_layers ext_dert__, ext_mask =", "stack_ = list sign = NoneType open_stacks = int root_dert__", "[sub_blobs] # 1st layer of sub_blobs for sub_blob in sub_blobs:", "number of incomplete stacks == 0 # blob is terminated", "merge blobs of other up_connects into blob of 1st up_connect", "empty x0 = P.x0 # first x in P xn", "G, Dy, Dx, M, L, x0 = 0, 0, 0,", "Ps sign_ = crit_ > 0 x0 = 0 try:", "line is masked, return an empty P I, iDy, iDx,", "ClusterStructure, NoneType from class_bind import AdjBinder from frame_blobs_yx import assign_adjacents", "[] # to extend root_blob sub_layers ext_dert__, ext_mask = extend_dert(blob)", "iDy=iDy, iDx=iDx, S=L, Ly=1, y0=y, Py_=[P], blob=blob, down_connect_cnt=0, sign=s) new_stack.hid", "Dy=0, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1, y0=y, Py_=[P], blob=blob,", "extended with new x-overlapping Ps in next run of scan_P_", "terminate stack, merge it into up_connects' blobs form_blob(stack, root_dert__, sub_blobs)", "and _P if P.sign == stack.sign: # sign match stack.down_connect_cnt", "row of derts mask = mask_[x] if ~mask: # current", "the first up_connect. stack.hid = blob.id blob.stack_.append(stack) # buffer of", "# to extend root_blob sub_layers ext_dert__, ext_mask = extend_dert(blob) if", "row of Ps sign_ = crit_ > 0 x0 =", "Dx=0, M=0, iDy=0, iDx=0, S=0, Ly=0), box=[y, x0, xn], stack_=[],", "-> m sub_blobs else: dert__, mask = comp_g(ext_dert__, ext_mask) #", "else a blob may leak through its external blob if", "0 or xn == root_dert__[0].shape[1] or y0 == 0 or", "root_dert__, sub_blobs) if not up_connect.blob is blob: merged_blob = up_connect.blob", "sub_blobs) blob_binder = AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder) # add adj_blobs to", "of input gradient, G: gradient, (Dy, Dx): vertical and lateral", "return P_ # the whole line is masked, return an", "# while both P_ and stack_ are not empty x0", "M, L, x0 = 0, 0, 0, 0, 0, 0,", "x_start = P.x0 - x0 x_stop = x_start + P.L", "x0 + P.L # first x beyond P _x0 =", "or merge every P into its stack of Ps, merge", "at row's end next_P_.append((P_.popleft(), [])) # no up_connect while stack_:", "iDx=0, S=0, Ly=0), box=[y, x0, xn], stack_=[], sign=s, open_stacks=1) new_stack", "dtype=bool) # mask box, then unmask Ps: for stack in", "comp range sub_layers # [sub_blobs ]: list of layers across", "different for comp_a? aveB = 50 # fixed cost per", "end next_P_.append((P_.popleft(), [])) # no up_connect while stack_: form_blob(stack_.popleft(), root_dert__,", "for overlaps in 8 directions, else a blob may leak", "blob.id blob.stack_.append(stack) # buffer of merged root stacks. up_connect.blob =", "I: input, (iDy, iDx): angle of input gradient, G: gradient,", "Py_ = list blob = object down_connect_cnt = int sign", "# loop left to right in each row of derts", "# y0, yn, x0, xn dert__, # box of derts,", "masked elif ~_mask: # prior dert is not masked #", "from comp_P_draft import comp_P_blob # filters, All *= rdn: ave", "= P_.popleft() I, G, Dy, Dx, M, iDy, iDx, L,", "* 2, fig=fig, fcr=1, **kwargs) # else: comp_P_ elif sub_blob.Dert['G']", "mask[y, x_start:x_stop] = False fopen = 0 # flag: blob", "= deque() # converted to stack_ in the next run", "Py_ [(P_params, dert_)]]: refs down blob formation tree, in vertical", "new_stack.Py_.append(P) # Py_: vertical buffer of Ps new_stack.down_connect_cnt = 0", "scan_P_ up_connect_ = [] if P_: P = P_.popleft() #", "# ------------------------------------------------------------------------------------------------------------------- def form_P_(dert_, crit_, mask_, binder): # segment dert__", "is merged into continued or initialized blob (all connected stacks):", "P while True: # while both P_ and stack_ are", "fcr, ext_mask) # -> m sub_blobs else: dert__, mask =", "- Ave # comp_g output eval by m, or clustering", "sub_layers # [sub_blobs ]: list of layers across sub_blob derivation", "xn)), mode='constant', constant_values=True) return ext_dert__, mask def accum_Dert(Dert: dict, **params)", "0, 0, x + 1 if ~mask: # accumulate P", "first x in _P _xn = _x0 + _P.L #", "I = int G = int Dy = int Dx", "pack P P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy,", "# _P overlaps next P in P_ xn == _xn", "into P__, in horizontal ) vertical order P_ = deque()", "Please see diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob structure, for all layers of", "next(dert_) x0 += 1 except IndexError: return P_ # the", "Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) # initialize", "blob.fig = fig blob.rdn = rdn blob.rng = rng blob.Ls", "ave = 50 # fixed cost per dert, from average", "one up_connect and that up_connect has one down_connect=P: merge P", "# blobs in other up_connects are references to blob in", "and up_connect_[0].down_connect_cnt == 1: # P has one up_connect and", "rng+: incremental range cross-comp in low-variation flat areas of +v--vg:", "sign changed # pack P P = CDeepP(I=I, G=G, Dy=Dy,", "stack_.popleft() # higher-row stacks _P = stack.Py_[-1] # last element", "derivation cross-comp in high-variation edge areas of +vg: positive deviation", "into its blob for up_connect in up_connect_[1:len(up_connect_)]: # merge blobs", "output; form clustering criterion: if fig: crit__ = dert__[0] +", "stack of Ps, merge blobs next_stack_ = deque() # converted", "- Ave # eval by i + m, accum in", "# load next P else: # terminate loop if stack.down_connect_cnt", "too small if blob.Dert['S'] < 100: kwargs['render'] = False spliced_layers", "if ~mask: # current dert is not masked sign =", "sign _mask = mask if ~_mask: # terminate and pack", "2 and False in mask: # min size in y", "+= intra_blob(sub_blob, rdn + 1 + 1 / blob.Ls, rng", "high-variation edge areas of +vg: positive deviation of gradient triggers", "rdn: # G + (intra_comp value borrow from flat blob)", "for y, P in enumerate(stack.Py_, start=stack.y0 - y0): x_start =", "per blob. Please see diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob structure, for all", "# determine pad size y0e = max(0, y0 - 1)", "y, P in enumerate(stack.Py_, start=stack.y0 - y0): x_start = P.x0", "fillvalue=[])] return spliced_layers def cluster_derts(dert__, mask, Ave, fcr, fig, render=False):", "if stack.G > 0: # check for overlaps in 8", "# filters, All *= rdn: ave = 50 # fixed", "deque, defaultdict from class_cluster import ClusterStructure, NoneType from class_bind import", "= stack_.popleft() # higher-row stacks _P = stack.Py_[-1] # last", "CDeepBlob(Dert=dict(I=0, G=0, Dy=0, Dx=0, M=0, iDy=0, iDx=0, S=0, Ly=0), box=[y,", "has > 1 down_connect_cnt: blob = up_connect_[0].blob # initialize new_stack", "iDy=iDy, iDx=iDx, L=L,x0=x0, sign=_sign) P_.append(P) # initialize P params: I,", "I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) #", "angle of input gradient, G: gradient, (Dy, Dx): vertical and", "blob.open_stacks += merged_blob.open_stacks blob.box[0] = min(blob.box[0], merged_blob.box[0]) # extend box", "= deque() # row of Ps sign_ = crit_ >", "Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) for _P,", "# Convert or merge every P into its stack of", "x # current dert is masked elif ~_mask: # prior", "= blob.id blob.stack_.append(new_stack) else: if len(up_connect_) == 1 and up_connect_[0].down_connect_cnt", "P into up_connect stack: new_stack = up_connect_[0] new_stack.accumulate(I=I, G=G, Dy=Dy,", "iDy += idy iDx += idx G += g Dy", "# buffer P-connected higher-row stacks into P' up_connect_ else: binder.bind(_P,", "intra_blob recursively evaluates each blob for two forks of extended", "int # for visibility and next-fork rdn sub_layers = list", "_P.L == P.x0: # check if Ps are adjacents binder.bind(_P,", "definition cost, may be different for comp_a? aveB = 50", "dert__[0].shape[1] > 2 and False in mask: # min size", "stack_ = deque() # buffer of running vertical stacks of", "into up_connects' blobs form_blob(stack, root_dert__, sub_blobs) if stack_: # load", "rng else: # comp_g output crit__ = dert__[6] - Ave", "# first x beyond _P if stack.G > 0: #", "render=False): # similar to frame_to_blobs if fcr: # comp_r output;", "L=L,x0=x0, sign=_sign) P_.append(P) # initialize P params: I, iDy, iDx,", "dict box = list stack_ = list sign = NoneType", "# take ext_dert__ from part of root_dert__ ext_dert__ = [derts[y0e:yne,", "0, 0, 0, 0, 0, 0, 0, 0, x #", "stack.sign: # sign match stack.down_connect_cnt += 1 up_connect_.append(stack) # buffer", "stack in merged_blob.stack_: if not stack is up_connect: stack.blob =", "L, x0, s = P.unpack() xn = x0 + L", "# segment dert__ into P__, in horizontal ) vertical order", "G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) blob.open_stacks +=", "list # -------------------------------------------------------------------------------------------------------------- # functions, ALL WORK-IN-PROGRESS: def intra_blob(blob, rdn,", "the whole line is masked, return an empty P I,", "blob.id blob.stack_.append(new_stack) else: if len(up_connect_) == 1 and up_connect_[0].down_connect_cnt ==", "next-fork rdn sub_layers = list # -------------------------------------------------------------------------------------------------------------- # functions, ALL", "# eval by -g, accum in rng else: # comp_g", "Dx): vertical and lateral Ds, M: match sign, box, #", "of the same level P_ = form_P_(zip(*dert_), crit__[y], mask[y], P_binder)", "blob = up_connect_[0].blob # initialize new_stack with up_connect blob: new_stack", "Ave # comp_g output eval by m, or clustering is", "(iDy, iDx): angle of input gradient, G: gradient, (Dy, Dx):", "of scan_P_ while P_: P, up_connect_ = P_.popleft() I, G,", "= sign_[x] if ~_mask and sign != _sign: # prior", "P_.popleft() # load left-most (lowest-x) input-row P stack = stack_.popleft()", "numpy as np # from comp_P_draft import comp_P_blob # filters,", "blob.box = (y0, yn, x0, xn) blob.dert__ = [derts[y0:yn, x0:xn]", "accum in rng; dert__[:,:,0] if not transposed else: crit__ =", "stack left: terminate loop next_P_.append((P, up_connect_)) break while P_: #", "(i, idy, idx, g, dy, dx, m) in enumerate(dert_, start=x0+1):", "down_connect=P: merge P into up_connect stack: new_stack = up_connect_[0] new_stack.accumulate(I=I,", "if up_connect.down_connect_cnt == 1: form_blob(up_connect, root_dert__, sub_blobs) if not up_connect.blob", "dert_)]]: refs down blob formation tree, in vertical (horizontal) order", "of sub_blobs per blob. Please see diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob structure,", "if sub_blob.sign: if sub_blob.Dert['M'] - borrow > aveB * rdn:", "+= g Dy += dy Dx += dx M +=", "positive deviation of negated -vg triggers comp_r. Each adds a", "# else: comp_P_ spliced_layers = [spliced_layers + sub_layers for spliced_layers,", "dert__[0].shape[0] > 2 and dert__[0].shape[1] > 2 and False in", "of derts, each = i, idy, idx, g, dy, dx,", "int root_dert__ = object dert__ = object mask = object", "ext_mask) # -> m sub_blobs else: dert__, mask = comp_g(ext_dert__,", "pad size y0e = max(0, y0 - 1) yne =", "the comps operation, which is the root_dert__ dert__ = [*zip(*dert__)]", "0, 0, 0, x + 1 if ~mask: # accumulate", "pairwise(P_): if _P.x0 + _P.L == P.x0: # check if", "at least one dert in line P_binder = AdjBinder(CDeepP) #", "1) # e is for extended # take ext_dert__ from", "dert__[0] + dert__[6] - Ave # eval by i +", "G, Dy, Dx, M, S (area), Ly (vertical dimension) #", "1 + 1 / blob.Ls, rng=rng, fig=1, fcr=0, **kwargs) #", "comp over rng+ | der+ if kwargs.get('render', None) is not", "taken accounted next_P_.append((P, up_connect_)) # recycle _P for the next", "= min(blob.box[1], x0) # extend box x0 blob.box[2] = max(blob.box[2],", "# comp_r fork: blob.sub_layers += intra_blob(sub_blob, rdn + 1 +", "# overlap with merged blob. blob.box[1] = min(blob.box[1], x0) #", "btm, left, right. 1 or 0 at boundaries mask =", "other up_connects are references to blob in the first up_connect.", "= object mask = object adj_blobs = list fopen =", "blob.stack_.append(new_stack) else: if len(up_connect_) == 1 and up_connect_[0].down_connect_cnt == 1:", "(vertical dimension) # I: input, (iDy, iDx): angle of input", "fork params? ''' from collections import deque, defaultdict from class_cluster", "an empty P I, iDy, iDx, G, Dy, Dx, M,", "flag input is gradient rdn, # redundancy to higher layers", "root_dert__ ext_dert__ = [derts[y0e:yne, x0e:xne] if derts is not None", "import deque, defaultdict from class_cluster import ClusterStructure, NoneType from class_bind", "by m, or clustering is always by m? root_dert__ =", "left-most (lowest-x) input-row P stack = stack_.popleft() # higher-row stacks", "P and down_connect_cnt per stack stack_ = form_stack_(P_, root_dert__, sub_blobs,", "flag comp rng, also clustering criterion in dert and Dert:", "loaded P and _P if P.sign == stack.sign: # sign", "# -> g sub_blobs: if dert__[0].shape[0] > 2 and dert__[0].shape[1]", "directions, edge blobs are more selective if _x0 < xn", "root_dert__, sub_blobs): # increment blob with terminated stack, check for", "idx G += g Dy += dy Dx += dx", "x0 x_stop = x_start + P.L mask[y, x_start:x_stop] = False", "extend_dert(blob) if fcr: dert__, mask = comp_r(ext_dert__, fig, fcr, ext_mask)", "- 1) xne = min(rX, xn + 1) # e", "is blob: merged_blob = up_connect.blob I, G, Dy, Dx, M,", "= x_start + P.L mask[y, x_start:x_stop] = False fopen =", "on frame boundary if x0 == 0 or xn ==", "converted into next_stack_ if P_ and stack_: # if both", "up_connects' blobs form_blob(stack, root_dert__, sub_blobs) break else: # no next-P", "changed # pack P P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx,", "input-row P stack = stack_.popleft() # higher-row stacks _P =", "P_.append(P) # initialize P params: I, iDy, iDx, G, Dy,", "== root_dert__[0].shape[0]: fopen = 1 blob.root_dert__ = root_dert__ blob.box =", "iDx): angle of input gradient, G: gradient, (Dy, Dx): vertical", "# for visibility and next-fork rdn sub_layers = list #", "up_connects' blobs form_blob(stack, root_dert__, sub_blobs) if stack_: # load stack", "y and x, least one dert in dert__ sub_blobs =", "accounted next_P_.append((P, up_connect_)) # recycle _P for the next run", "for blob termination I, G, Dy, Dx, M, iDy, iDx,", "recursively evaluates each blob for two forks of extended internal", "formation tree, in vertical (horizontal) order # next fork: fcr,", "I, iDy, iDx, G, Dy, Dx, M, L = *next(dert_),", "Dx, M, L, x0 = 0, 0, 0, 0, 0,", "if Ps are adjacents binder.bind(_P, P) return P_ def scan_P_(P_,", "clustering, adds a row of Ps if render: render =", "ave * rdn, fcr, fig, **kwargs) # fork params: blob.fcr", "and last row are discarded; print(f'Processing intra line {y}...') #", "sub_blobs else: dert__, mask = comp_g(ext_dert__, ext_mask) # -> g", "in enumerate(dert__): # in height, first and last row are", "bool rdn = float rng = int Ls = int", "clustering class CDeepP(ClusterStructure): I = int G = int Dy", "class CDeepBlob(ClusterStructure): Dert = dict box = list stack_ =", "as np # from comp_P_draft import comp_P_blob # filters, All", "or y0 == 0 or yn == root_dert__[0].shape[0]: fopen =", "# pad mask: top, btm, left, right. 1 or 0", "Ps, merge blobs next_stack_ = deque() # converted to stack_", "M: match sign, box, # y0, yn, x0, xn dert__,", "P_binder) # horizontal clustering, adds a row of Ps if", "blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder) # add adj_blobs to each blob # sub_blobs", "x0 = int sign = NoneType class CDeepStack(ClusterStructure): I =", "G=G, Dy=0, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1, y0=y, Py_=[P],", "S, Ly = merged_blob.Dert.values() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M,", "up_connect that has > 1 down_connect_cnt: blob = up_connect_[0].blob #", "blob.open_stacks += down_connect_cnt - 1 # incomplete stack cnt +", "and comp_P: optional raster-to-vector conversion. intra_blob recursively evaluates each blob", "= CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1,", "in each row of derts mask = mask_[x] if ~mask:", "about clusters of the same level P_ = form_P_(zip(*dert_), crit__[y],", "its external blob if _x0 - 1 < xn and", "0, 0, 0, 0, x elif _mask: I, iDy, iDx,", "binder): # merge P into higher-row stack of Ps with", "_x0 - 1 < xn and x0 < _xn +", "G = int Dy = int Dx = int M", "their blobs: form_blob(stack_.popleft(), root_dert__, sub_blobs) blob_binder = AdjBinder(CDeepBlob) blob_binder.bind_from_lower(stack_binder) assign_adjacents(blob_binder)", "iDy, iDx, G, Dy, Dx, M, L = *next(dert_), 1", "= max(0, x0 - 1) xne = min(rX, xn +", "blobs are more selective if _x0 < xn and x0", "# incomplete stack cnt + terminated stack down_connect_cnt - 1:", "sub_blobs = cluster_derts(dert__, mask, ave * rdn, fcr, fig, **kwargs)", "next_stack_ if P_ and stack_: # if both input row", "layers across sub_blob derivation tree # deeper layers are nested,", "+= intra_blob(sub_blob, rdn + 1 + 1 / blob.Ls, rng=rng,", "flag input is g | p, fcr: flag comp over", "min(blob.box[1], merged_blob.box[1]) # extend box x0 blob.box[2] = max(blob.box[2], merged_blob.box[2])", "ext_dert__, ext_mask = extend_dert(blob) if fcr: dert__, mask = comp_r(ext_dert__,", "intra line {y}...') # if False in mask[i]: # [y,x,params],", "for spliced_layers, sub_layers in zip_longest(spliced_layers, blob.sub_layers, fillvalue=[])] return spliced_layers def", "0, 0, x elif _mask: I, iDy, iDx, G, Dy,", "all up_connects if up_connect_[0].down_connect_cnt == 1: # up_connect is not", "1 and up_connect_[0].down_connect_cnt == 1: # P has one up_connect", "G: gradient, (Dy, Dx): vertical and lateral Ds, M: match", "last_stack.Ly mask = np.ones((yn - y0, xn - x0), dtype=bool)", "= False fopen = 0 # flag: blob on frame", "up_connect if up_connect.down_connect_cnt == 1: form_blob(up_connect, root_dert__, sub_blobs) if not", "# if number of incomplete stacks == 0 # blob", "P_.append(P) for _P, P in pairwise(P_): if _P.x0 + _P.L", "least one dert in line P_binder = AdjBinder(CDeepP) # binder", "P, up_connect_ = P_.popleft() I, G, Dy, Dx, M, iDy,", "up_connect is not terminated form_blob(up_connect_[0], root_dert__, sub_blobs) # merge stack", "= blob.id blob.stack_.append(new_stack) if len(up_connect_) > 1: # merge blobs", "lateral Ds, M: match sign, box, # y0, yn, x0,", "blob.sub_layers += intra_blob(sub_blob, rdn + 1 + 1 / blob.Ls,", "dert in line P_binder = AdjBinder(CDeepP) # binder needs data", "params? ''' from collections import deque, defaultdict from class_cluster import", "range sub_layers # [sub_blobs ]: list of layers across sub_blob", "row and higher row have any Ps / _Ps left", "for derts in blob.root_dert__] # pad mask: top, btm, left,", "scan_P_(P_, stack_, root_dert__, sub_blobs, P_binder) # vertical clustering, adds up_connects", "stack_ in the next run of scan_P_ while P_: P,", "if stack_: # load stack with next _P stack =", "Ave # eval by i + m, accum in rng;", "each input-row P that has no connections in higher row:", "comp_P: optional raster-to-vector conversion. intra_blob recursively evaluates each blob for", "shape [y, params, x] sub_blobs = [] # from form_blob:", "+ 1 + 1 / blob.Ls, rng=rng, fig=1, fcr=0, **kwargs)", "form_blob(stack, root_dert__, sub_blobs) if stack_: # load stack with next", "0 # flag: blob on frame boundary if x0 ==", "sign, box, # y0, yn, x0, xn dert__, # box", "blob.root_dert__] # pad mask: top, btm, left, right. 1 or", "to extend root_blob sub_layers ext_dert__, ext_mask = extend_dert(blob) if fcr:", "first x beyond P _x0 = _P.x0 # first x", "x0 if not up_connect_: # initialize new stack for each", "+ m, accum in rng; dert__[:,:,0] if not transposed else:", "Ps with same sign and x_coord overlap next_P_ = deque()", "P.L # first x beyond P _x0 = _P.x0 #", "merged_blob.open_stacks blob.box[0] = min(blob.box[0], merged_blob.box[0]) # extend box y0 blob.box[1]", "Ave, fcr, fig, render=False): # similar to frame_to_blobs if fcr:", "if dert__[0].shape[0] > 2 and dert__[0].shape[1] > 2 and False", "G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=S, Ly=Ly) # terminated", "# row of Ps sign_ = crit_ > 0 x0", "_P = stack.Py_[-1] # last element of each stack is", "+ L # next-P x0 if not up_connect_: # initialize", "fcr = bool fig = bool rdn = float rng", "*next(dert_), 1 # initialize P params _sign = sign_[x0] _mask", "initialize P params _sign = sign_[x0] _mask = mask_[x0] #", "sign = stack.unpack() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy,", "else: comp_P_ elif sub_blob.Dert['G'] + borrow > aveB * rdn:", "x in _P _xn = _x0 + _P.L # first", "blob on frame boundary if x0 == 0 or xn", "# extend dert box: rY, rX = blob.root_dert__[0].shape # higher", "input row and higher row have any Ps / _Ps", "iDy = int iDx = int L = int x0", "next_stack_ def form_blob(stack, root_dert__, sub_blobs): # increment blob with terminated", "segment dert__ into P__, in horizontal ) vertical order P_", "vertical order P_ = deque() # row of Ps sign_", "fixed cost per intra_blob comp and clustering class CDeepP(ClusterStructure): I", "xn + 1) # e is for extended # take", "buffer of merged root stacks. up_connect.blob = blob up_connect.hid =", "by -g, accum in rng else: # comp_g output crit__", "_P for the next run of scan_P_ up_connect_ = []", "iDy=0, iDx=0, S=0, Ly=0), box=[y, x0, xn], stack_=[], sign=s, open_stacks=1)", "blob.stack_.append(new_stack) if len(up_connect_) > 1: # merge blobs of all", "= stack y0, x0, xn = blob.box yn = last_stack.y0", "intra_blob, and comp_P: optional raster-to-vector conversion. intra_blob recursively evaluates each", "= sign # prior sign _mask = mask if ~_mask:", "of Ps stack_binder = AdjBinder(CDeepStack) if render: streamer = BlobStreamer(CDeepBlob,", "[derts[y0e:yne, x0e:xne] if derts is not None else None for", "g | p, fcr: flag comp over rng+ | der+", "prior sign _mask = mask if ~_mask: # terminate and", "intra_comp_g import comp_g, comp_r from itertools import zip_longest from class_stream", "50 # fixed cost per intra_blob comp and clustering class", "increment blob with terminated stack, check for blob termination I,", "is masked, return an empty P I, iDy, iDx, G,", "~_mask and sign != _sign: # prior dert is not", "open stacks contain Ps of a current row and may", "in mask: # min size in y and x, least", "same-sign x-overlapping _Ps per P while True: # while both", "rng, also clustering criterion in dert and Dert: g in", "CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L,x0=x0, sign=_sign) P_.append(P)", "that continue at row's end next_P_.append((P_.popleft(), [])) # no up_connect", "merged blob. blob.box[1] = min(blob.box[1], x0) # extend box x0", "x_start:x_stop] = False fopen = 0 # flag: blob on", "sign = NoneType open_stacks = int root_dert__ = object dert__", "each stack is higher-row P up_connect_ = [] # list", "# G + (intra_comp value borrow from flat blob) #", "similar to frame_to_blobs if fcr: # comp_r output; form clustering", "itself # open stacks contain Ps of a current row", "m stack_[ stack_params, Py_ [(P_params, dert_)]]: refs down blob formation", "dert__ # derts after the comps operation, which is the", "# no stack left: terminate loop next_P_.append((P, up_connect_)) break while", "Py_=[P], blob=blob, down_connect_cnt=0, sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) else: if", "Dx, M, S (area), Ly (vertical dimension) # I: input,", "if (xn < _xn or # _P overlaps next P", "> aveB * rdn: # G + (intra_comp value borrow", "Ly = merged_blob.Dert.values() accum_Dert(blob.Dert, I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy,", "run of scan_P_ if blob.open_stacks == 0: # if number", "= fcr blob.fig = fig blob.rdn = rdn blob.rng =", "# in height, first and last row are discarded; print(f'Processing", "stack.Py_[-1] # last element of each stack is higher-row P", "if prior dert is unmasked P = CDeepP(I=I, G=G, Dy=Dy,", "dy, dx, m) in enumerate(dert_, start=x0+1): # loop left to", "it into up_connects' blobs form_blob(stack, root_dert__, sub_blobs) break else: #", "< _xn: # x overlap between loaded P and _P", "x0e, xne - xn)), mode='constant', constant_values=True) return ext_dert__, mask def", "yn, x0, xn dert__, # box of derts, each =", "M=M, iDy=iDy, iDx=iDx, S=L, Ly=1) new_stack.Py_.append(P) # Py_: vertical buffer", "incremental range cross-comp in low-variation flat areas of +v--vg: positive", "intra_blob(blob, rdn, rng, fig, fcr, **kwargs): # recursive input rng+", "Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L,x0=x0, sign=_sign) P_.append(P) # initialize", "connected stacks): blob.open_stacks += down_connect_cnt - 1 # incomplete stack", "0, x elif _mask: I, iDy, iDx, G, Dy, Dx,", "xn = blob.box # extend dert box: rY, rX =", "G, Dy, Dx, M, L = *next(dert_), 1 # initialize", "iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign) P_.append(P) for _P, P in", "Dert = I, iDy, iDx, G, Dy, Dx, M, S", "= i, idy, idx, g, dy, dx, m stack_[ stack_params,", "for derts in root_dert__] blob.mask = mask blob.adj_blobs = [[],", "= int Dx = int M = int iDy =", "see diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob structure, for all layers of blob", "stacks into P' up_connect_ else: binder.bind(_P, P) if (xn <", "rX = blob.root_dert__[0].shape # higher dert size # determine pad", "in merged_blob.stack_: if not stack is up_connect: stack.blob = blob", "# 1st layer of sub_blobs for sub_blob in sub_blobs: #", "rendering sub-blobs when blob is too small if blob.Dert['S'] <", "P_: P, up_connect_ = P_.popleft() I, G, Dy, Dx, M,", "current row and may be extended with new x-overlapping Ps", "xn = x0 + L # next-P x0 if not", "| comp_r: G = blob.Dert['G']; adj_G = blob.adj_blobs[2] borrow =", "up_connect: stack.blob = blob # blobs in other up_connects are", "# terminate and pack last P in a row if", "stacks are merged into their blobs: form_blob(stack_.popleft(), root_dert__, sub_blobs) blob_binder", "fig, fcr, **kwargs): # recursive input rng+ | der+ cross-comp", "extend box x0 blob.box[2] = max(blob.box[2], merged_blob.box[2]) # extend box", "rdn sub_layers = list # -------------------------------------------------------------------------------------------------------------- # functions, ALL WORK-IN-PROGRESS:", "streamer.end_blob_conversion(y) return sub_blobs # clustering functions: # ------------------------------------------------------------------------------------------------------------------- def form_P_(dert_,", "sign = sign_[x] if ~_mask and sign != _sign: #", "input is g | p, fcr: flag comp over rng+", "1: stack itself # open stacks contain Ps of a", "to right in each row of derts mask = mask_[x]", "Ps of a current row and may be extended with", "else: # comp_g output crit__ = dert__[6] - Ave #", "min(rX, xn + 1) # e is for extended #", "# comp_g fork: blob.sub_layers += intra_blob(sub_blob, rdn + 1 +", "is gradient rdn, # redundancy to higher layers rng, #", "0, 0, 0, 0, 0, x + 1 if ~mask:", "dx M += m L += 1 _sign = sign", "next fork: fcr, # flag comp rng, also clustering criterion", "comp_P_draft import comp_P_blob # filters, All *= rdn: ave =", "root_dert__, sub_blobs) # merge stack of 1st up_connect into its", "cluster id for P next_stack_.append(new_stack) return next_stack_ def form_blob(stack, root_dert__,", "g in der+ fork, i+m in rng+ fork? fig, #", "in higher row: blob = CDeepBlob(Dert=dict(I=0, G=0, Dy=0, Dx=0, M=0,", "dert is unmasked P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M,", "iDx=iDx, S=S, Ly=Ly) blob.open_stacks += merged_blob.open_stacks blob.box[0] = min(blob.box[0], merged_blob.box[0])", "in dert__ sub_blobs = cluster_derts(dert__, mask, ave * rdn, fcr,", "# terminated stack is merged into continued or initialized blob", "G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1) new_stack.Py_.append(P) #", "1 down_connect_cnt: blob = up_connect_[0].blob # initialize new_stack with up_connect", "box x0 blob.box[2] = max(blob.box[2], merged_blob.box[2]) # extend box xn", "def accum_Dert(Dert: dict, **params) -> None: Dert.update({param: Dert[param] + value", "of all up_connects if up_connect_[0].down_connect_cnt == 1: # up_connect is", "eval by m, or clustering is always by m? root_dert__", "row of Ps if render: render = streamer.update_blob_conversion(y, P_) #", "small if blob.Dert['S'] < 100: kwargs['render'] = False spliced_layers =", "and x0 < _xn + 1: # x overlap between", "comp_g output eval by m, or clustering is always by", "# evaluate for intra_blob comp_g | comp_r: G = blob.Dert['G'];", "0, 0, 0, 0, 0, 0, 0, x + 1", "per P while True: # while both P_ and stack_", "derts mask = mask_[x] if ~mask: # current dert is", "first x in P xn = x0 + P.L #", "1 / blob.Ls, rng=rng, fig=1, fcr=0, **kwargs) # else: comp_P_", "= rng blob.Ls = len(sub_blobs) # for visibility and next-fork", "# comp_g output crit__ = dert__[6] - Ave # comp_g", "= list fopen = bool margin = list fcr =", "stack: new_stack = up_connect_[0] new_stack.accumulate(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy,", "in enumerate(dert_, start=x0+1): # loop left to right in each", "comp_P_ elif sub_blob.Dert['G'] + borrow > aveB * rdn: #", "boundaries mask = np.pad(blob.mask, ((y0 - y0e, yne - yn),", "= form_stack_(P_, root_dert__, sub_blobs, y) stack_binder.bind_from_lower(P_binder) while stack_: # frame", "idy, idx, g, dy, dx, m) in enumerate(dert_, start=x0+1): #", "in rng+ fork? fig, # flag input is gradient rdn,", "# merge stack of 1st up_connect into its blob for", "new_stack.hid = blob.id blob.stack_.append(new_stack) else: if len(up_connect_) == 1 and", "1 except IndexError: return P_ # the whole line is", "fig=fig, fcr=1, **kwargs) # else: comp_P_ elif sub_blob.Dert['G'] + borrow", "eval by i + m, accum in rng; dert__[:,:,0] if", "flat blob) # comp_g fork: blob.sub_layers += intra_blob(sub_blob, rdn +", "no up_connect while stack_: form_blob(stack_.popleft(), root_dert__, sub_blobs) # down_connect_cnt always", "# or adjacent M if negative sign? if sub_blob.sign: if", "= min(rY, yn + 1) x0e = max(0, x0 -", "layer of sub_blobs per blob. Please see diagram: https://github.com/boris-kz/CogAlg/blob/master/frame_2D_alg/Illustrations/intra_blob_2_fork_scheme.png Blob", "its stack of Ps, merge blobs next_stack_ = deque() #", "all layers of blob hierarchy: root_dert__, Dert = I, iDy,", "# vertical clustering, adds up_connects per P and down_connect_cnt per", "P in enumerate(stack.Py_, start=stack.y0 - y0): x_start = P.x0 -", "derts is not None else None for derts in blob.root_dert__]", "# to recycle P + up_connect_ that finished scanning _P,", "- x0e, xne - xn)), mode='constant', constant_values=True) return ext_dert__, mask", "yn == root_dert__[0].shape[0]: fopen = 1 blob.root_dert__ = root_dert__ blob.box", "converted to stack_ in the next run of scan_P_ while", "crit__[y], mask[y], P_binder) # horizontal clustering, adds a row of", "1 up_connect_.append(stack) # buffer P-connected higher-row stacks into P' up_connect_", "= blob.box yn = last_stack.y0 + last_stack.Ly mask = np.ones((yn", "= min(abs(G), abs(adj_G) / 2) # or adjacent M if", "# binder needs data about clusters of the same level", "_P = stack.Py_[-1] else: # no stack left: terminate loop", "of sub_blobs for sub_blob in sub_blobs: # evaluate for intra_blob", "blob of 1st up_connect if up_connect.down_connect_cnt == 1: form_blob(up_connect, root_dert__,", "# initialize P params _sign = sign_[x0] _mask = mask_[x0]", "sign match stack.down_connect_cnt += 1 up_connect_.append(stack) # buffer P-connected higher-row", "up_connect_ else: binder.bind(_P, P) else: # -G, check for orthogonal", "in the next run of scan_P_ while P_: P, up_connect_", "bit per dert for x, (i, idy, idx, g, dy,", "(xn < _xn or # _P overlaps next P in", "new stack for each input-row P that has no connections", "rdn = float rng = int Ls = int #", "else: # -G, check for orthogonal overlaps only: 4 directions,", "blob hierarchy: root_dert__, Dert = I, iDy, iDx, G, Dy,", "box xn for stack in merged_blob.stack_: if not stack is", "for comp_a? aveB = 50 # fixed cost per intra_blob", "accumulate P params: I += i iDy += idy iDx", "until not masked next(dert_) x0 += 1 except IndexError: return", "WORK-IN-PROGRESS: def intra_blob(blob, rdn, rng, fig, fcr, **kwargs): # recursive", "render: streamer = BlobStreamer(CDeepBlob, crit__, mask) for y, dert_ in", "= _x0 + _P.L # first x beyond _P if", "then unmask Ps: for stack in blob.stack_: for y, P", "loop if stack.down_connect_cnt != 1: # terminate stack, merge it", "masked sign = sign_[x] if ~_mask and sign != _sign:", "of scan_P_ if blob.open_stacks == 0: # if number of", "# redundancy to higher layers rng, # comp range sub_layers", "blob.open_stacks -= 1 # overlap with merged blob. blob.box[1] =", "next P in P_ xn == _xn and stack.sign): #", "P _x0 = _P.x0 # first x in _P _xn", "terminated form_blob(up_connect_[0], root_dert__, sub_blobs) # merge stack of 1st up_connect", "**kwargs): # recursive input rng+ | der+ cross-comp within blob", "+ dert__[6] - Ave # eval by i + m,", "has one down_connect=P: merge P into up_connect stack: new_stack =", "criterion: if fig: crit__ = dert__[0] + dert__[6] - Ave", "0, 0, 0, 0, x # current dert is masked", "low-variation flat areas of +v--vg: positive deviation of negated -vg", "= dert__[6] - Ave # comp_g output eval by m,", "if not up_connect_: # initialize new stack for each input-row", "contain Ps of a current row and may be extended", "+ _P.L # first x beyond _P if stack.G >", "dert is not masked and sign changed # pack P", "# functions, ALL WORK-IN-PROGRESS: def intra_blob(blob, rdn, rng, fig, fcr,", "blob.Ls = len(sub_blobs) # for visibility and next-fork rdn blob.sub_layers", "root stacks. up_connect.blob = blob up_connect.hid = blob.id blob.stack_.append(up_connect) blob.open_stacks", "adj_blobs = list fopen = bool margin = list fcr", "**kwargs) # fork params: blob.fcr = fcr blob.fig = fig", "loop next_P_.append((P, up_connect_)) break while P_: # terminate Ps and", "zip_longest from class_stream import BlobStreamer from utils import pairwise import", "M, iDy, iDx, S, Ly = merged_blob.Dert.values() accum_Dert(blob.Dert, I=I, G=G,", "match stack.down_connect_cnt += 1 up_connect_.append(stack) # buffer P-connected higher-row stacks", "blob.stack_.append(stack) # buffer of merged root stacks. up_connect.blob = blob", "is not masked and sign changed # pack P P", "CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, L=L, x0=x0, sign=_sign)", "up_connect blob: new_stack = CDeepStack(I=I, G=G, Dy=0, Dx=Dx, M=M, iDy=iDy,", "Ps are adjacents binder.bind(_P, P) return P_ def scan_P_(P_, stack_,", "blobs next_stack_ = deque() # converted to stack_ in the", "# up_connect is not terminated form_blob(up_connect_[0], root_dert__, sub_blobs) # merge", "in zip_longest(spliced_layers, blob.sub_layers, fillvalue=[])] return spliced_layers def cluster_derts(dert__, mask, Ave,", "output crit__ = dert__[6] - Ave # comp_g output eval", "max(0, x0 - 1) xne = min(rX, xn + 1)", "triggers comp_r. Each adds a layer of sub_blobs per blob.", "aveB = 50 # fixed cost per intra_blob comp and", "def intra_blob(blob, rdn, rng, fig, fcr, **kwargs): # recursive input", "len(sub_blobs) # for visibility and next-fork rdn blob.sub_layers = [sub_blobs]", "box = list stack_ = list sign = NoneType open_stacks", "(y0, yn, x0, xn) blob.dert__ = [derts[y0:yn, x0:xn] for derts", "spliced_layers = [spliced_layers + sub_layers for spliced_layers, sub_layers in zip_longest(spliced_layers,", "if ~_mask and sign != _sign: # prior dert is", "y, dert_ in enumerate(dert__): # in height, first and last", "sign=s) new_stack.hid = blob.id blob.stack_.append(new_stack) else: if len(up_connect_) == 1", "[])) # no up_connect while stack_: form_blob(stack_.popleft(), root_dert__, sub_blobs) #", "up_connect.down_connect_cnt == 1: form_blob(up_connect, root_dert__, sub_blobs) if not up_connect.blob is", "root_blob sub_layers ext_dert__, ext_mask = extend_dert(blob) if fcr: dert__, mask", "P into higher-row stack of Ps with same sign and", "versions/intra_blob_xy.py<gh_stars>0 ''' 2D version of 1st-level algorithm is a combination", "borders (+1 dert to boundaries) y0, yn, x0, xn =", "# skip until not masked next(dert_) x0 += 1 except", "unmasked P = CDeepP(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx,", "dert in dert__ sub_blobs = cluster_derts(dert__, mask, ave * rdn,", "import BlobStreamer from utils import pairwise import numpy as np", "xn) blob.dert__ = [derts[y0:yn, x0:xn] for derts in root_dert__] blob.mask", "from utils import pairwise import numpy as np # from", "[] # list of same-sign x-overlapping _Ps per P while", "blob.rdn = rdn blob.rng = rng blob.Ls = len(sub_blobs) #", "0 return next_P_ # each element is P + up_connect_", "sign=_sign) P_.append(P) # initialize P params: I, iDy, iDx, G,", "kwargs['render'] = False spliced_layers = [] # to extend root_blob", "over rng+ | der+ if kwargs.get('render', None) is not None:", "new_stack.down_connect_cnt = 0 # reset down_connect_cnt blob = new_stack.blob else:", "new_stack.accumulate(I=I, G=G, Dy=Dy, Dx=Dx, M=M, iDy=iDy, iDx=iDx, S=L, Ly=1) new_stack.Py_.append(P)", "in _P _xn = _x0 + _P.L # first x", "dert_ in enumerate(dert__): # in height, first and last row", "else: binder.bind(_P, P) if (xn < _xn or # _P", "and next-fork rdn blob.sub_layers = [sub_blobs] # 1st layer of", "= len(sub_blobs) # for visibility and next-fork rdn blob.sub_layers =", "< xn and x0 < _xn + 1: # x", "terminate loop if stack.down_connect_cnt != 1: # terminate stack, merge", "merged_blob.stack_: if not stack is up_connect: stack.blob = blob #", "blob.fopen = fopen sub_blobs.append(blob) def extend_dert(blob): # extend dert borders" ]
[ "from __future__ import print_function import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))", "number of cells within the grid. When we sample around", "edge of two triangle pieces. To prevent this from happening,", "/ self._cell_length) y_index = int(point[1] / self._cell_length) return x_index, y_index", "grid. \"\"\" return (0 <= index2d[0] < self._grid_size_x) and (0", "from all existing points. \"\"\" active_point = self._active_list.pop() for _", "to add some random blocks on the ground. Possion disk", "int(grid_length / self._cell_length) + 1 self._grid_size_y = int(grid_width / self._cell_length)", "for the triangles in the mesh file. \"\"\" self._terrain_type =", "not place blocks near the point [0, 0], where the", "continue maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point is not None and", "Implements the algorithm described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the uniform sampling", "Returns: The index of the point within the self._grid array.", "a point in the grid array. Args: point: A 2D", "if not self._is_in_grid(sample): continue if self._is_close_to_existing_points(sample): continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] =", "1.0, 0.3] def randomize_env(self, env): \"\"\"Generate a random terrain for", "of a point (aka the cell ID) in the grid.", "described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the uniform sampling method that creates", "inside the grid. \"\"\" return (0 <= point[0] < self._grid_length)", "blocks to be in front of the robot. shifted_center =", "cell because of the minimum distance constraint. Once the current", "point. Removes the sampling base point and also stores the", "factor for the triangles in the mesh file. \"\"\" self._terrain_type", "points around a active site. See details in the algorithm", "grid array. Args: index2d: The 2D index of a point", "_is_in_grid(self, point): \"\"\"Checks if the point is inside the grid", "already sampled (and stored) points. Args: point: A 2D point", "self._grid[self._point_to_index_1d(sample)] = sample def generate(self): \"\"\"Generates the Poisson disc distribution", "The 2D index of a point (aka the cell ID)", "disk method enforces the minimum distance between points and is", "robot will start. if abs(shifted_center[0]) < 1.0 and abs(shifted_center[1]) <", "algorithm to add some random blocks on the ground. Possion", "active_point if not self._is_in_grid(sample): continue if self._is_close_to_existing_points(sample): continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)]", "x index of the cell the point belongs to. y_index:", "triangle mesh. mesh_filename: The mesh file to be used. The", "2 box_id = env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length, half_height]) env.pybullet_client.createMultiBody( baseMass=0,", "index2d[0] + index2d[1] * self._grid_size_x def _is_in_grid(self, point): \"\"\"Checks if", "self._min_radius) random_angle = np.random.uniform(0, 2 * math.pi) # The sampled", "will only be loaded if terrain_type is set to TerrainType.TRIANGLE_MESH.", "of the bounding square in which points are sampled. min_radius:", "file. \"\"\" self._terrain_type = terrain_type self._mesh_filename = mesh_filename self._mesh_scale =", "index2d[0] < self._grid_size_x) and (0 <= index2d[1] < self._grid_size_y) def", "points, thus voiding the clustering effect in uniform N-D distribution.", "is smaller than the min_radius \"\"\" px, py = self._point_to_index_2d(point)", "\"\"\" return (0 <= point[0] < self._grid_length) and (0 <=", "grid. Returns: The 1D position of the cell within the", "which points are sampled. grid_width: The width of the bounding", "We want the blocks to be in front of the", "itertools import math import enum import numpy as np from", "distance between two sampling points, thus voiding the clustering effect", "point described by its coordinates (x, y). Returns: The index", "< self._grid_size_y) def _is_close_to_existing_points(self, point): \"\"\"Checks if the point is", "the grid. Args: point: A 2D point (list) described by", "(aka cell ID) of a point in the grid. Args:", "_is_close_to_existing_points(self, point): \"\"\"Checks if the point is close to any", "False def sample(self): \"\"\"Samples new points around some existing point.", "distance between points and is more suitable for generating a", "2), xrange(py - 1, py + 2)): if not self._is_in_range(neighbor_cell):", "def _load_triangle_mesh(self, env): \"\"\"Represents the random terrain using a triangle", "details in the algorithm description. \"\"\" self._cell_length = min_radius /", "inside the quare [0, grid_length] x [0, grid_width] \"\"\" while", "10 _MAX_SAMPLE_SIZE = 30 _MIN_BLOCK_DISTANCE = 0.7 _MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE", "for center in block_centers: # We want the blocks to", "(x, y). Returns: The index of the point within the", "cell ID) of a point in the grid. Args: point:", "_GRID_LENGTH = 15 _GRID_WIDTH = 10 _MAX_SAMPLE_SIZE = 30 _MIN_BLOCK_DISTANCE", "The mesh file to be used. The mesh will only", "to TerrainType.TRIANGLE_MESH. mesh_scale: the scaling factor for the triangles in", "minitaur gym environment. \"\"\" poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE)", "continue half_length = np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 * math.sqrt(2)) half_height", "creates small clusters of points, Poisson disk method enforces the", "self._min_radius: return True return False def sample(self): \"\"\"Samples new points", "0.7 _MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2 _MAX_BLOCK_HEIGHT", "env: A minitaur gym environment. \"\"\" if self._terrain_type is TerrainType.TRIANGLE_MESH:", "Unlike the uniform sampling method that creates small clusters of", "def sample(self): \"\"\"Samples new points around some existing point. Removes", "terrain for the current env. Args: env: A minitaur gym", "2D points near the active point sample = random_radius *", "coordinates (x, y). Returns: Whether the point is inside the", "random terrain for the current env. Args: env: A minitaur", "grid. Args: point: A 2D point (list) described by its", "and abs(shifted_center[1]) < 1.0: continue half_length = np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) /", "a random terrain for the current env. Args: env: A", "generating a spatial distribution of non-overlapping objects. \"\"\" def __init__(self,", "MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates an uneven terrain in the gym env.\"\"\" def", "to generate random blocks or load a triangle mesh. mesh_filename:", "foot in sim. Args: env: A minitaur gym environment. \"\"\"", "self._grid_size_x) and (0 <= index2d[1] < self._grid_size_y) def _is_close_to_existing_points(self, point):", "all future searches cannot start from within the same base", "mesh. mesh_filename: The mesh file to be used. The mesh", "random_radius = np.random.uniform(self._min_radius, 2 * self._min_radius) random_angle = np.random.uniform(0, 2", "The x index of the cell the point belongs to.", "1 TRIANGLE_MESH = 2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates an uneven terrain", "for Minitaur foot in sim. Args: env: A minitaur gym", "= [] for p in self._grid: if p is not", "the 2D index (aka cell ID) of a point in", "in the grid. Returns: The 1D position of the cell", "any already sampled (and stored) points. Args: point: A 2D", "check nearby cells for existing points for neighbor_cell in itertools.product(xrange(px", "add some random blocks on the ground. Possion disk algorithm", "= _MAX_BLOCK_LENGTH / 2 _MAX_BLOCK_HEIGHT = 0.05 _MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT", "of a point in the grid. Args: point: A 2D", "Returns: All sampled points. The points are inside the quare", "algorithm described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the uniform sampling method that", "import env_randomizer_base _GRID_LENGTH = 15 _GRID_WIDTH = 10 _MAX_SAMPLE_SIZE =", "point is inside the grid boundary. Args: point: A 2D", "\"\"\" if self._terrain_type is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if self._terrain_type is TerrainType.RANDOM_BLOCKS:", "gym environment. \"\"\" poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers", "2D grid as an 1D array. The grid is used", "because of the minimum distance constraint. Once the current base", "voiding the clustering effect in uniform N-D distribution. Args: env:", "+ 1 self._min_radius = min_radius self._max_sample_size = max_sample_size # Flattern", "# Generate random points near the current active_point between the", "of the cell within the self._grid array. \"\"\" return index2d[0]", "grid as an 1D array. The grid is used for", "the minimum distance between points and is more suitable for", "30 _MIN_BLOCK_DISTANCE = 0.7 _MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH", "cell ID is within the grid. Args: index2d: The 2D", "continue if self._is_close_to_existing_points(sample): continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] = sample def generate(self):", "spatial distribution of non-overlapping objects. \"\"\" def __init__(self, grid_length, grid_width,", "= PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers = poisson_disc.generate() for center", "* math.sqrt(2)) half_height = np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) / 2 box_id =", "points. Args: point: A 2D point (list) described by its", "Args: index2d: The 2D index of a point (aka the", "import itertools import math import enum import numpy as np", "The maximum number of sample points around a active site.", "its coordinates (x, y). Returns: True iff the distance of", "clusters of points, Poisson disk method enforces the minimum distance", "random_radius * np.array([np.cos(random_angle), np.sin(random_angle)]) + active_point if not self._is_in_grid(sample): continue", "distribution of 2D points. Although the while loop looks scary,", "+ 1 self._grid_size_y = int(grid_width / self._cell_length) + 1 self._min_radius", "np from pybullet_envs.minitaur.envs import env_randomizer_base _GRID_LENGTH = 15 _GRID_WIDTH =", "random blocks or load a triangle mesh. mesh_filename: The mesh", "in the grid array. Args: point: A 2D point described", "be pushed into the base cell because of the minimum", "+ index2d[1] * self._grid_size_x def _is_in_grid(self, point): \"\"\"Checks if the", "Returns: The 1D position of the cell within the self._grid", "cannot start from within the same base cell. Returns: All", "from __future__ import absolute_import from __future__ import division from __future__", "def _index_2d_to_1d(self, index2d): \"\"\"Converts the 2D index to the 1D", "index (aka cell ID) of a point in the grid.", "PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers = poisson_disc.generate() for center in", "are inside the quare [0, grid_length] x [0, grid_width] \"\"\"", "random blocks on the ground. Possion disk algorithm sets the", "x_index: The x index of the cell the point belongs", "triangle pieces. To prevent this from happening, we recommend using", "* self._min_radius) random_angle = np.random.uniform(0, 2 * math.pi) # The", "more suitable for generating a spatial distribution of non-overlapping objects.", "np.array(np.random.random_sample(2)) * [grid_length, grid_width] self._active_list = [first_sample] # Also store", "searches cannot start from within the same base cell. Returns:", "None: all_sites.append(p) return all_sites class TerrainType(enum.Enum): \"\"\"The randomzied terrain types", "disk sampling method. Implements the algorithm described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike", "parentdir) import itertools import math import enum import numpy as", "http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the uniform sampling method that creates small clusters", "itertools.product(xrange(px - 1, px + 2), xrange(py - 1, py", "xrange(self._max_sample_size): # Generate random points near the current active_point between", "base cell because of the minimum distance constraint. Once the", "_ in xrange(self._max_sample_size): # Generate random points near the current", "2 * math.pi) # The sampled 2D points near the", "else [1.0, 1.0, 0.3] def randomize_env(self, env): \"\"\"Generate a random", "mesh_scale=None): \"\"\"Initializes the randomizer. Args: terrain_type: Whether to generate random", "TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def _load_triangle_mesh(self, env): \"\"\"Represents the random terrain using", "mesh_scale: the scaling factor for the triangles in the mesh", "and set it as an active site. first_sample = np.array(np.random.random_sample(2))", "same base cell. Returns: All sampled points. The points are", "point: A 2D point described by its coordinates (x, y).", "2D index to the 1D position in the grid array.", "algorithm sets the minimum distance between two sampling points, thus", "\"\"\"Generates an uneven terrain in the gym env.\"\"\" def __init__(self,", "distribution of non-overlapping objects. \"\"\" def __init__(self, grid_length, grid_width, min_radius,", "self._cell_length) return x_index, y_index def _index_2d_to_1d(self, index2d): \"\"\"Converts the 2D", "cell ID) in the grid. Returns: Whether the cell (2D", "point is removed, all future searches cannot start from within", "minimum distance constraint. Once the current base point is removed,", "Removes the sampling base point and also stores the new", "leg to stuck at the common edge of two triangle", "the minimum distance between two sampling points, thus voiding the", "points using Poisson disk sampling method. Implements the algorithm described", "the grid. Args: index2d: The 2D index of a point", "happening, we recommend using hard contacts (or high stiffness values)", "current env. Args: env: A minitaur gym environment. \"\"\" if", "stuck at the common edge of two triangle pieces. To", "the bounding square in which points are sampled. grid_width: The", "\"\"\"Checks if the point is close to any already sampled", "_point_to_index_1d(self, point): \"\"\"Computes the index of a point in the", "Also store the sample point in the grid. self._grid[self._point_to_index_1d(first_sample)] =", "self._grid[self._point_to_index_1d(first_sample)] = first_sample def _point_to_index_1d(self, point): \"\"\"Computes the index of", "the robot will start. if abs(shifted_center[0]) < 1.0 and abs(shifted_center[1])", "point): \"\"\"Checks if the point is close to any already", "start. if abs(shifted_center[0]) < 1.0 and abs(shifted_center[1]) < 1.0: continue", "/ self._cell_length) + 1 self._min_radius = min_radius self._max_sample_size = max_sample_size", "\"\"\"Converts the 2D index to the 1D position in the", "in the grid array. Args: index2d: The 2D index of", "points will not be pushed into the base cell because", "+ active_point if not self._is_in_grid(sample): continue if self._is_close_to_existing_points(sample): continue self._active_list.append(sample)", "new jksampled points if they are far enough from all", "be loaded if terrain_type is set to TerrainType.TRIANGLE_MESH. mesh_scale: the", "self._grid_size_y = int(grid_width / self._cell_length) + 1 self._min_radius = min_radius", "<= point[0] < self._grid_length) and (0 <= point[1] < self._grid_width)", "length of the bounding square in which points are sampled.", "N is the number of cells within the grid. When", "stored) points. Args: point: A 2D point (list) described by", "# point searching. self._grid = [None] * self._grid_size_x * self._grid_size_y", "is inside the grid boundary. Args: point: A 2D point", "start from within the same base cell. Returns: All sampled", "(0 <= index2d[0] < self._grid_size_x) and (0 <= index2d[1] <", "is inside the grid. \"\"\" return (0 <= point[0] <", "in front of the robot. shifted_center = np.array(center) - [2,", "any pair of points. max_sample_size: The maximum number of sample", "self._active_list = [first_sample] # Also store the sample point in", "TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if self._terrain_type is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def _load_triangle_mesh(self, env):", "When we sample around a base point (in some base", "stores the new jksampled points if they are far enough", "and also stores the new jksampled points if they are", "continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] = sample def generate(self): \"\"\"Generates the Poisson", "base point (in some base cell), new points will not", "The 1D position of the cell within the self._grid array.", "index of the cell the point belongs to. y_index: The", "Poisson disk method enforces the minimum distance between points and", "objects. \"\"\" def __init__(self, grid_length, grid_width, min_radius, max_sample_size): \"\"\"Initializes the", "To prevent this from happening, we recommend using hard contacts", "to the flat ground. We use the Possion disk algorithm", "ground. Possion disk algorithm sets the minimum distance between two", "abs(shifted_center[0]) < 1.0 and abs(shifted_center[1]) < 1.0: continue half_length =", "return True return False def sample(self): \"\"\"Samples new points around", "np.linalg.norm(maybe_a_point - point) < self._min_radius: return True return False def", "py + 2)): if not self._is_in_range(neighbor_cell): continue maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)]", "[None] * self._grid_size_x * self._grid_size_y # Generate the first sample", "point): \"\"\"Computes the index of a point in the grid", "flags=1, meshScale=self._mesh_scale) env.ground_id = env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0, 0])", "the algorithm. Args: grid_length: The length of the bounding square", "self._terrain_type is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if self._terrain_type is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def", "in sim. Args: env: A minitaur gym environment. \"\"\" env.pybullet_client.removeBody(env.ground_id)", "nearby cells for existing points for neighbor_cell in itertools.product(xrange(px -", "the first sample point and set it as an active", "points for neighbor_cell in itertools.product(xrange(px - 1, px + 2),", "= int(point[0] / self._cell_length) y_index = int(point[1] / self._cell_length) return", "the new jksampled points if they are far enough from", "is set to TerrainType.TRIANGLE_MESH. mesh_scale: the scaling factor for the", "point and set it as an active site. first_sample =", "\"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None): \"\"\"Initializes the randomizer. Args: terrain_type: Whether to generate", "The length of the bounding square in which points are", "\"\"\"Samples new points around some existing point. Removes the sampling", "if terrain_type is set to TerrainType.TRIANGLE_MESH. mesh_scale: the scaling factor", "randomize_env(self, env): \"\"\"Generate a random terrain for the current env.", "_GRID_WIDTH / 2] # Do not place blocks near the", "environment reset.\"\"\" from __future__ import absolute_import from __future__ import division", "currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) parentdir = os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0,", "the cell ID) in the grid. Returns: Whether the cell", "where N is the number of cells within the grid.", "bounding square in which points are sampled. grid_width: The width", "point searching. self._grid = [None] * self._grid_size_x * self._grid_size_y #", "the point is inside the grid. \"\"\" return (0 <=", "grid_width self._grid_size_x = int(grid_length / self._cell_length) + 1 self._grid_size_y =", "active_point = self._active_list.pop() for _ in xrange(self._max_sample_size): # Generate random", "Minitaur leg to stuck at the common edge of two", "2D index (aka cell ID) of a point in the", "a active site. See details in the algorithm description. \"\"\"", "pybullet_envs.minitaur.envs import env_randomizer_base _GRID_LENGTH = 15 _GRID_WIDTH = 10 _MAX_SAMPLE_SIZE", "the number of cells within the grid. When we sample", "scaling factor for the triangles in the mesh file. \"\"\"", "flat ground. We use the Possion disk algorithm to add", "algorithm. Args: grid_length: The length of the bounding square in", "an active site. first_sample = np.array(np.random.random_sample(2)) * [grid_length, grid_width] self._active_list", "- point) < self._min_radius: return True return False def sample(self):", "site. See details in the algorithm description. \"\"\" self._cell_length =", "point and also stores the new jksampled points if they", "0.3] def randomize_env(self, env): \"\"\"Generate a random terrain for the", "division from __future__ import print_function import os, inspect currentdir =", "def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None): \"\"\"Initializes the randomizer. Args:", "terrain_collision_shape_id = env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale) env.ground_id = env.pybullet_client.createMultiBody(", "np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 * math.sqrt(2)) half_height = np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT)", "= min_radius / math.sqrt(2) self._grid_length = grid_length self._grid_width = grid_width", "= np.array(np.random.random_sample(2)) * [grid_length, grid_width] self._active_list = [first_sample] # Also", "point (list) described by its coordinates (x, y). Returns: Whether", "max_sample_size: The maximum number of sample points around a active", "self.sample() all_sites = [] for p in self._grid: if p", "self._is_in_range(neighbor_cell): continue maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point is not None", "class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates an uneven terrain in the gym env.\"\"\"", "_load_triangle_mesh(self, env): \"\"\"Represents the random terrain using a triangle mesh.", "import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) parentdir", "base cell. Returns: All sampled points. The points are inside", "some random blocks on the ground. Possion disk algorithm sets", "the algorithm description. \"\"\" self._cell_length = min_radius / math.sqrt(2) self._grid_length", "env): \"\"\"Adds random convex blocks to the flat ground. We", "= terrain_type self._mesh_filename = mesh_filename self._mesh_scale = mesh_scale if mesh_scale", "# Also store the sample point in the grid. self._grid[self._point_to_index_1d(first_sample)]", "self._grid_width) def _is_in_range(self, index2d): \"\"\"Checks if the cell ID is", "mesh_scale if mesh_scale else [1.0, 1.0, 0.3] def randomize_env(self, env):", "is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def _load_triangle_mesh(self, env): \"\"\"Represents the random terrain", "we can use in the gym env.\"\"\" RANDOM_BLOCKS = 1", "= np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) / 2 box_id = env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length,", "= int(grid_width / self._cell_length) + 1 self._min_radius = min_radius self._max_sample_size", "existing points. \"\"\" active_point = self._active_list.pop() for _ in xrange(self._max_sample_size):", "px + 2), xrange(py - 1, py + 2)): if", "np.sin(random_angle)]) + active_point if not self._is_in_grid(sample): continue if self._is_close_to_existing_points(sample): continue", "point [0, 0], where the robot will start. if abs(shifted_center[0])", "os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) parentdir =", "point belongs to. \"\"\" x_index = int(point[0] / self._cell_length) y_index", "self._max_sample_size = max_sample_size # Flattern the 2D grid as an", "self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self, point): \"\"\"Computes the 2D index (aka cell", "to the 1D position in the grid array. Args: index2d:", "shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale) env.ground_id = env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0,", "parentdir = os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir) import itertools import math import", "generate(self): \"\"\"Generates the Poisson disc distribution of 2D points. Although", "index2d): \"\"\"Converts the 2D index to the 1D position in", "def generate(self): \"\"\"Generates the Poisson disc distribution of 2D points.", "only be loaded if terrain_type is set to TerrainType.TRIANGLE_MESH. mesh_scale:", "TerrainType(enum.Enum): \"\"\"The randomzied terrain types we can use in the", "Flattern the 2D grid as an 1D array. The grid", "ground. We use the Possion disk algorithm to add some", "the Poisson disc distribution of 2D points. Although the while", "while self._active_list: self.sample() all_sites = [] for p in self._grid:", "of 2D points. Although the while loop looks scary, the", "y_index = int(point[1] / self._cell_length) return x_index, y_index def _index_2d_to_1d(self,", "_MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2 _MAX_BLOCK_HEIGHT = 0.05 _MIN_BLOCK_HEIGHT =", "1.0: continue half_length = np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 * math.sqrt(2))", "\"\"\"Generates a random terrain at Minitaur gym environment reset.\"\"\" from", "the minimum distance constraint. Once the current base point is", "the robot. shifted_center = np.array(center) - [2, _GRID_WIDTH / 2]", "within the self._grid array. \"\"\" return index2d[0] + index2d[1] *", "or load a triangle mesh. mesh_filename: The mesh file to", "described by its coordinates (x, y). Returns: True iff the", "# Do not place blocks near the point [0, 0],", "half_length = np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 * math.sqrt(2)) half_height =", "self._grid_width = grid_width self._grid_size_x = int(grid_length / self._cell_length) + 1", "not None: all_sites.append(p) return all_sites class TerrainType(enum.Enum): \"\"\"The randomzied terrain", "self._grid array. \"\"\" return self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self, point): \"\"\"Computes the", "px, py = self._point_to_index_2d(point) # Now we can check nearby", "y). Returns: The index of the point within the self._grid", "index2d[1] * self._grid_size_x def _is_in_grid(self, point): \"\"\"Checks if the point", "Now we can check nearby cells for existing points for", "coordinates (x, y). Returns: The index of the point within", "__future__ import print_function import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir", "disk algorithm to add some random blocks on the ground.", "sampling method. Implements the algorithm described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the", "of cells within the grid. When we sample around a", "small clusters of points, Poisson disk method enforces the minimum", "minimum distance between any pair of points. max_sample_size: The maximum", "1, px + 2), xrange(py - 1, py + 2)):", "The mesh will only be loaded if terrain_type is set", "point): \"\"\"Checks if the point is inside the grid boundary.", "sample around a base point (in some base cell), new", "mesh file. \"\"\" self._terrain_type = terrain_type self._mesh_filename = mesh_filename self._mesh_scale", "within the grid. Args: index2d: The 2D index of a", "sample point and set it as an active site. first_sample", "terrain_type self._mesh_filename = mesh_filename self._mesh_scale = mesh_scale if mesh_scale else", "Do not place blocks near the point [0, 0], where", "the gym env.\"\"\" RANDOM_BLOCKS = 1 TRIANGLE_MESH = 2 class", "a triangle mesh. mesh_filename: The mesh file to be used.", "point): \"\"\"Computes the 2D index (aka cell ID) of a", "x [0, grid_width] \"\"\" while self._active_list: self.sample() all_sites = []", "2D points. Although the while loop looks scary, the algorithm", "self._grid_size_x def _is_in_grid(self, point): \"\"\"Checks if the point is inside", "grid_width: The width of the bounding square in which points", "= env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale) env.ground_id = env.pybullet_client.createMultiBody( baseMass=0,", "self._mesh_filename = mesh_filename self._mesh_scale = mesh_scale if mesh_scale else [1.0,", "the cell ID is within the grid. Args: index2d: The", "if maybe_a_point is not None and np.linalg.norm(maybe_a_point - point) <", "See details in the algorithm description. \"\"\" self._cell_length = min_radius", "int(point[0] / self._cell_length) y_index = int(point[1] / self._cell_length) return x_index,", "grid_length, grid_width, min_radius, max_sample_size): \"\"\"Initializes the algorithm. Args: grid_length: The", "for Minitaur leg to stuck at the common edge of", "Args: env: A minitaur gym environment. \"\"\" if self._terrain_type is", "a spatial distribution of non-overlapping objects. \"\"\" def __init__(self, grid_length,", "True return False def sample(self): \"\"\"Samples new points around some", "(2 * math.sqrt(2)) half_height = np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) / 2 box_id", "TerrainType.TRIANGLE_MESH. mesh_scale: the scaling factor for the triangles in the", "the radius random_radius = np.random.uniform(self._min_radius, 2 * self._min_radius) random_angle =", "math import enum import numpy as np from pybullet_envs.minitaur.envs import", "self._cell_length = min_radius / math.sqrt(2) self._grid_length = grid_length self._grid_width =", "env. Args: env: A minitaur gym environment. \"\"\" if self._terrain_type", "minimum distance between two sampling points, thus voiding the clustering", "self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] = sample def generate(self): \"\"\"Generates the Poisson disc", "The width of the bounding square in which points are", "point sample = random_radius * np.array([np.cos(random_angle), np.sin(random_angle)]) + active_point if", "= grid_width self._grid_size_x = int(grid_length / self._cell_length) + 1 self._grid_size_y", "to be in front of the robot. shifted_center = np.array(center)", "active site. See details in the algorithm description. \"\"\" self._cell_length", "The y index of the cell the point belongs to.", "for fast nearest # point searching. self._grid = [None] *", "cell within the self._grid array. \"\"\" return index2d[0] + index2d[1]", "\"\"\" poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers = poisson_disc.generate()", "- 1, py + 2)): if not self._is_in_range(neighbor_cell): continue maybe_a_point", "Args: point: A 2D point (list) described by its coordinates", "[] for p in self._grid: if p is not None:", "enough from all existing points. \"\"\" active_point = self._active_list.pop() for", "\"\"\"Checks if the point is inside the grid boundary. Args:", "os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir) import itertools import math import enum import", "__init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None): \"\"\"Initializes the randomizer. Args: terrain_type:", "poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers = poisson_disc.generate() for", "the scaling factor for the triangles in the mesh file.", "this from happening, we recommend using hard contacts (or high", "mesh_scale else [1.0, 1.0, 0.3] def randomize_env(self, env): \"\"\"Generate a", "by its coordinates (x, y). Returns: True iff the distance", "within the grid. When we sample around a base point", "[0, grid_width] \"\"\" while self._active_list: self.sample() all_sites = [] for", "coordinates (x, y). Returns: x_index: The x index of the", "A 2D point described by its coordinates (x, y). Returns:", "- [2, _GRID_WIDTH / 2] # Do not place blocks", "sample points around a active site. See details in the", "2D index of a point (aka the cell ID) in", "are sampled. grid_width: The width of the bounding square in", "the grid array. Args: point: A 2D point described by", "types we can use in the gym env.\"\"\" RANDOM_BLOCKS =", "gym env.\"\"\" def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None): \"\"\"Initializes the", "= 30 _MIN_BLOCK_DISTANCE = 0.7 _MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH =", "self._grid_size_y # Generate the first sample point and set it", "def _point_to_index_1d(self, point): \"\"\"Computes the index of a point in", "Possion disk algorithm sets the minimum distance between two sampling", "\"\"\" return self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self, point): \"\"\"Computes the 2D index", "Generate random points near the current active_point between the radius", "blocks on the ground. Possion disk algorithm sets the minimum", "square in which points are sampled. grid_width: The width of", "self._grid_length = grid_length self._grid_width = grid_width self._grid_size_x = int(grid_length /", "(0 <= index2d[1] < self._grid_size_y) def _is_close_to_existing_points(self, point): \"\"\"Checks if", "grid_length self._grid_width = grid_width self._grid_size_x = int(grid_length / self._cell_length) +", "coordinates (x, y). Returns: True iff the distance of the", "cell (2D index) is inside the grid. \"\"\" return (0", "values) for Minitaur foot in sim. Args: env: A minitaur", "meshScale=self._mesh_scale) env.ground_id = env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0, 0]) def", "than the min_radius \"\"\" px, py = self._point_to_index_2d(point) # Now", "some existing point. Removes the sampling base point and also", "# The sampled 2D points near the active point sample", "the current active_point between the radius random_radius = np.random.uniform(self._min_radius, 2", "not be pushed into the base cell because of the", "_MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers = poisson_disc.generate() for center in block_centers: #", "env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0, 0]) def _generate_convex_blocks(self, env): \"\"\"Adds", "from __future__ import division from __future__ import print_function import os,", "Once the current base point is removed, all future searches", "point[0] < self._grid_length) and (0 <= point[1] < self._grid_width) def", "minitaur gym environment. \"\"\" env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id = env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename,", "p is not None: all_sites.append(p) return all_sites class TerrainType(enum.Enum): \"\"\"The", "searching. self._grid = [None] * self._grid_size_x * self._grid_size_y # Generate", "from happening, we recommend using hard contacts (or high stiffness", "y). Returns: x_index: The x index of the cell the", "place blocks near the point [0, 0], where the robot", "by its coordinates (x, y). Returns: Whether the point is", "distribution. Args: env: A minitaur gym environment. \"\"\" poisson_disc =", "to. y_index: The y index of the cell the point", "point in the grid array. Args: point: A 2D point", "[0, grid_length] x [0, grid_width] \"\"\" while self._active_list: self.sample() all_sites", "int(point[1] / self._cell_length) return x_index, y_index def _index_2d_to_1d(self, index2d): \"\"\"Converts", "self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point is not None and np.linalg.norm(maybe_a_point - point)", "None and np.linalg.norm(maybe_a_point - point) < self._min_radius: return True return", "1D position of the cell within the self._grid array. \"\"\"", "= os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir) import itertools import math import enum", "new points around some existing point. Removes the sampling base", "looks scary, the algorithm is in fact O(N), where N", "all_sites.append(p) return all_sites class TerrainType(enum.Enum): \"\"\"The randomzied terrain types we", "\"\"\"Initializes the algorithm. Args: grid_length: The length of the bounding", "the bounding square in which points are sampled. min_radius: The", "\"\"\"Initializes the randomizer. Args: terrain_type: Whether to generate random blocks", "the ground. Possion disk algorithm sets the minimum distance between", "block_centers: # We want the blocks to be in front", "by its coordinates (x, y). Returns: x_index: The x index", "to any existing points is smaller than the min_radius \"\"\"", "Poisson disk sampling method. Implements the algorithm described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf", "env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length, half_height]) env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=box_id, basePosition=[shifted_center[0], shifted_center[1], half_height])", "1D position in the grid array. Args: index2d: The 2D", "if self._terrain_type is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if self._terrain_type is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env)", "= int(grid_length / self._cell_length) + 1 self._grid_size_y = int(grid_width /", "number of sample points around a active site. See details", "the 2D grid as an 1D array. The grid is", "in the mesh file. \"\"\" self._terrain_type = terrain_type self._mesh_filename =", "for generating a spatial distribution of non-overlapping objects. \"\"\" def", "def _is_close_to_existing_points(self, point): \"\"\"Checks if the point is close to", "half_height = np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) / 2 box_id = env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX,", "ID) of a point in the grid. Args: point: A", "position of the cell within the self._grid array. \"\"\" return", "sampled (and stored) points. Args: point: A 2D point (list)", "of sample points around a active site. See details in", "grid boundary. Args: point: A 2D point (list) described by", "self._is_close_to_existing_points(sample): continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] = sample def generate(self): \"\"\"Generates the", "cell), new points will not be pushed into the base", "(x, y). Returns: True iff the distance of the point", "0.05 _MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2 class PoissonDisc2D(object): \"\"\"Generates 2D", "[grid_length, grid_width] self._active_list = [first_sample] # Also store the sample", "described by its coordinates (x, y). Returns: x_index: The x", "Whether the point is inside the grid. \"\"\" return (0", "a random terrain at Minitaur gym environment reset.\"\"\" from __future__", "will not be pushed into the base cell because of", "the current base point is removed, all future searches cannot", "belongs to. \"\"\" x_index = int(point[0] / self._cell_length) y_index =", "in self._grid: if p is not None: all_sites.append(p) return all_sites", "the triangles in the mesh file. \"\"\" self._terrain_type = terrain_type", "\"\"\"Computes the 2D index (aka cell ID) of a point", "import numpy as np from pybullet_envs.minitaur.envs import env_randomizer_base _GRID_LENGTH =", "It is possible for Minitaur leg to stuck at the", "common edge of two triangle pieces. To prevent this from", "15 _GRID_WIDTH = 10 _MAX_SAMPLE_SIZE = 30 _MIN_BLOCK_DISTANCE = 0.7", "its coordinates (x, y). Returns: The index of the point", "env: A minitaur gym environment. \"\"\" poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH,", "possible for Minitaur leg to stuck at the common edge", "array. Args: point: A 2D point described by its coordinates", "TRIANGLE_MESH = 2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates an uneven terrain in", "random points near the current active_point between the radius random_radius", "index) is inside the grid. \"\"\" return (0 <= index2d[0]", "env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale) env.ground_id = env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id,", "_MAX_BLOCK_LENGTH / 2 _MAX_BLOCK_HEIGHT = 0.05 _MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT /", "suitable for generating a spatial distribution of non-overlapping objects. \"\"\"", "in the grid. self._grid[self._point_to_index_1d(first_sample)] = first_sample def _point_to_index_1d(self, point): \"\"\"Computes", "in the algorithm description. \"\"\" self._cell_length = min_radius / math.sqrt(2)", "y index of the cell the point belongs to. \"\"\"", "= env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0, 0]) def _generate_convex_blocks(self, env):", "the distance of the point to any existing points is", "while loop looks scary, the algorithm is in fact O(N),", "p in self._grid: if p is not None: all_sites.append(p) return", "non-overlapping objects. \"\"\" def __init__(self, grid_length, grid_width, min_radius, max_sample_size): \"\"\"Initializes", "return (0 <= point[0] < self._grid_length) and (0 <= point[1]", "the grid. When we sample around a base point (in", "high stiffness values) for Minitaur foot in sim. Args: env:", "points and is more suitable for generating a spatial distribution", "max_sample_size): \"\"\"Initializes the algorithm. Args: grid_length: The length of the", "description. \"\"\" self._cell_length = min_radius / math.sqrt(2) self._grid_length = grid_length", "grid. self._grid[self._point_to_index_1d(first_sample)] = first_sample def _point_to_index_1d(self, point): \"\"\"Computes the index", "far enough from all existing points. \"\"\" active_point = self._active_list.pop()", "the quare [0, grid_length] x [0, grid_width] \"\"\" while self._active_list:", "A 2D point (list) described by its coordinates (x, y).", "py = self._point_to_index_2d(point) # Now we can check nearby cells", "the point within the self._grid array. \"\"\" return self._index_2d_to_1d(self._point_to_index_2d(point)) def", "points, Poisson disk method enforces the minimum distance between points", "terrain_type: Whether to generate random blocks or load a triangle", "\"\"\" env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id = env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale) env.ground_id", "within the self._grid array. \"\"\" return self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self, point):", "import division from __future__ import print_function import os, inspect currentdir", "gym environment reset.\"\"\" from __future__ import absolute_import from __future__ import", "(0 <= point[1] < self._grid_width) def _is_in_range(self, index2d): \"\"\"Checks if", "the algorithm described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the uniform sampling method", "_is_in_range(self, index2d): \"\"\"Checks if the cell ID is within the", "N-D distribution. Args: env: A minitaur gym environment. \"\"\" poisson_disc", "The grid is used for fast nearest # point searching.", "points are sampled. grid_width: The width of the bounding square", "algorithm description. \"\"\" self._cell_length = min_radius / math.sqrt(2) self._grid_length =", "self._grid array. \"\"\" return index2d[0] + index2d[1] * self._grid_size_x def", "<= point[1] < self._grid_width) def _is_in_range(self, index2d): \"\"\"Checks if the", "(aka the cell ID) in the grid. Returns: Whether the", "the cell (2D index) is inside the grid. \"\"\" return", "poisson_disc.generate() for center in block_centers: # We want the blocks", "of the robot. shifted_center = np.array(center) - [2, _GRID_WIDTH /", "= np.array(center) - [2, _GRID_WIDTH / 2] # Do not", "triangle mesh. It is possible for Minitaur leg to stuck", "_MAX_SAMPLE_SIZE = 30 _MIN_BLOCK_DISTANCE = 0.7 _MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH", "A minitaur gym environment. \"\"\" env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id = env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH,", "position in the grid array. Args: index2d: The 2D index", "method. Implements the algorithm described in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the uniform", "the self._grid array. \"\"\" return index2d[0] + index2d[1] * self._grid_size_x", "self._active_list.pop() for _ in xrange(self._max_sample_size): # Generate random points near", "constraint. Once the current base point is removed, all future", "True iff the distance of the point to any existing", "store the sample point in the grid. self._grid[self._point_to_index_1d(first_sample)] = first_sample", "in the grid. Args: point: A 2D point (list) described", "in uniform N-D distribution. Args: env: A minitaur gym environment.", "if not self._is_in_range(neighbor_cell): continue maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point is", "_GRID_WIDTH = 10 _MAX_SAMPLE_SIZE = 30 _MIN_BLOCK_DISTANCE = 0.7 _MAX_BLOCK_LENGTH", "self._min_radius = min_radius self._max_sample_size = max_sample_size # Flattern the 2D", "is more suitable for generating a spatial distribution of non-overlapping", "algorithm is in fact O(N), where N is the number", "new points will not be pushed into the base cell", "env_randomizer_base _GRID_LENGTH = 15 _GRID_WIDTH = 10 _MAX_SAMPLE_SIZE = 30", "self._terrain_type = terrain_type self._mesh_filename = mesh_filename self._mesh_scale = mesh_scale if", "return all_sites class TerrainType(enum.Enum): \"\"\"The randomzied terrain types we can", "self._grid_size_x = int(grid_length / self._cell_length) + 1 self._grid_size_y = int(grid_width", "the randomizer. Args: terrain_type: Whether to generate random blocks or", "import absolute_import from __future__ import division from __future__ import print_function", "self._grid: if p is not None: all_sites.append(p) return all_sites class", "base cell), new points will not be pushed into the", "jksampled points if they are far enough from all existing", "min_radius, max_sample_size): \"\"\"Initializes the algorithm. Args: grid_length: The length of", "env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length, half_height]) env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=box_id, basePosition=[shifted_center[0], shifted_center[1],", "the uniform sampling method that creates small clusters of points,", "- 1, px + 2), xrange(py - 1, py +", "index of the cell the point belongs to. \"\"\" x_index", "the cell the point belongs to. y_index: The y index", "Minitaur foot in sim. Args: env: A minitaur gym environment.", "file to be used. The mesh will only be loaded", "= first_sample def _point_to_index_1d(self, point): \"\"\"Computes the index of a", "= self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point is not None and np.linalg.norm(maybe_a_point -", "<= index2d[0] < self._grid_size_x) and (0 <= index2d[1] < self._grid_size_y)", "self._grid_size_y) def _is_close_to_existing_points(self, point): \"\"\"Checks if the point is close", "We use the Possion disk algorithm to add some random", "int(grid_width / self._cell_length) + 1 self._min_radius = min_radius self._max_sample_size =", "grid_width] \"\"\" while self._active_list: self.sample() all_sites = [] for p", "if self._is_close_to_existing_points(sample): continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] = sample def generate(self): \"\"\"Generates", "/ 2 box_id = env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length, half_height]) env.pybullet_client.createMultiBody(", "use the Possion disk algorithm to add some random blocks", "cell. Returns: All sampled points. The points are inside the", "at Minitaur gym environment reset.\"\"\" from __future__ import absolute_import from", "= grid_length self._grid_width = grid_width self._grid_size_x = int(grid_length / self._cell_length)", "return (0 <= index2d[0] < self._grid_size_x) and (0 <= index2d[1]", "env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id = env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale) env.ground_id =", "the point [0, 0], where the robot will start. if", "used for fast nearest # point searching. self._grid = [None]", "_MAX_BLOCK_HEIGHT / 2 class PoissonDisc2D(object): \"\"\"Generates 2D points using Poisson", "we can check nearby cells for existing points for neighbor_cell", "in the grid. Returns: Whether the cell (2D index) is", "the cell ID) in the grid. Returns: The 1D position", "terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None): \"\"\"Initializes the randomizer. Args: terrain_type: Whether", "self._cell_length) y_index = int(point[1] / self._cell_length) return x_index, y_index def", "abs(shifted_center[1]) < 1.0: continue half_length = np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2", "\"\"\" return index2d[0] + index2d[1] * self._grid_size_x def _is_in_grid(self, point):", "Although the while loop looks scary, the algorithm is in", "= env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length, half_height]) env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=box_id, basePosition=[shifted_center[0],", "point) < self._min_radius: return True return False def sample(self): \"\"\"Samples", "import print_function import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir =", "2 class PoissonDisc2D(object): \"\"\"Generates 2D points using Poisson disk sampling", "maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point is not None and np.linalg.norm(maybe_a_point", "The index of the point within the self._grid array. \"\"\"", "into the base cell because of the minimum distance constraint.", "(or high stiffness values) for Minitaur foot in sim. Args:", "(x, y). Returns: x_index: The x index of the cell", "for existing points for neighbor_cell in itertools.product(xrange(px - 1, px", "1 self._grid_size_y = int(grid_width / self._cell_length) + 1 self._min_radius =", "blocks to the flat ground. We use the Possion disk", "current active_point between the radius random_radius = np.random.uniform(self._min_radius, 2 *", "env: A minitaur gym environment. \"\"\" env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id = env.pybullet_client.createCollisionShape(", "sampling points, thus voiding the clustering effect in uniform N-D", "\"\"\" px, py = self._point_to_index_2d(point) # Now we can check", "\"\"\" self._cell_length = min_radius / math.sqrt(2) self._grid_length = grid_length self._grid_width", "maybe_a_point is not None and np.linalg.norm(maybe_a_point - point) < self._min_radius:", "block_centers = poisson_disc.generate() for center in block_centers: # We want", "/ 2] # Do not place blocks near the point", "sampled. min_radius: The minimum distance between any pair of points.", "points. Although the while loop looks scary, the algorithm is", "os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) parentdir = os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir) import", "index to the 1D position in the grid array. Args:", "< self._grid_size_x) and (0 <= index2d[1] < self._grid_size_y) def _is_close_to_existing_points(self,", "an 1D array. The grid is used for fast nearest", "belongs to. y_index: The y index of the cell the", "the index of a point in the grid array. Args:", "the blocks to be in front of the robot. shifted_center", "def _is_in_range(self, index2d): \"\"\"Checks if the cell ID is within", "1.0 and abs(shifted_center[1]) < 1.0: continue half_length = np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH)", "class TerrainType(enum.Enum): \"\"\"The randomzied terrain types we can use in", "the self._grid array. \"\"\" return self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self, point): \"\"\"Computes", "(and stored) points. Args: point: A 2D point (list) described", "points if they are far enough from all existing points.", "removed, all future searches cannot start from within the same", "the cell within the self._grid array. \"\"\" return index2d[0] +", "= max_sample_size # Flattern the 2D grid as an 1D", "generate random blocks or load a triangle mesh. mesh_filename: The", "_GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers = poisson_disc.generate() for center in block_centers:", "a point in the grid. Args: point: A 2D point", "points near the active point sample = random_radius * np.array([np.cos(random_angle),", "enum import numpy as np from pybullet_envs.minitaur.envs import env_randomizer_base _GRID_LENGTH", "using a triangle mesh. It is possible for Minitaur leg", "are far enough from all existing points. \"\"\" active_point =", "gym environment. \"\"\" if self._terrain_type is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if self._terrain_type", "in fact O(N), where N is the number of cells", "import enum import numpy as np from pybullet_envs.minitaur.envs import env_randomizer_base", "min_radius: The minimum distance between any pair of points. max_sample_size:", "as np from pybullet_envs.minitaur.envs import env_randomizer_base _GRID_LENGTH = 15 _GRID_WIDTH", "the grid. Returns: Whether the cell (2D index) is inside", "# We want the blocks to be in front of", "the sampling base point and also stores the new jksampled", "near the point [0, 0], where the robot will start.", "of two triangle pieces. To prevent this from happening, we", "a base point (in some base cell), new points will", "grid_length: The length of the bounding square in which points", "index2d: The 2D index of a point (aka the cell", "the base cell because of the minimum distance constraint. Once", "class PoissonDisc2D(object): \"\"\"Generates 2D points using Poisson disk sampling method.", "def __init__(self, grid_length, grid_width, min_radius, max_sample_size): \"\"\"Initializes the algorithm. Args:", "sample = random_radius * np.array([np.cos(random_angle), np.sin(random_angle)]) + active_point if not", "= self._active_list.pop() for _ in xrange(self._max_sample_size): # Generate random points", "point[1] < self._grid_width) def _is_in_range(self, index2d): \"\"\"Checks if the cell", "triangles in the mesh file. \"\"\" self._terrain_type = terrain_type self._mesh_filename", "for the current env. Args: env: A minitaur gym environment.", "_MAX_BLOCK_HEIGHT = 0.05 _MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2 class PoissonDisc2D(object):", "_MAX_SAMPLE_SIZE) block_centers = poisson_disc.generate() for center in block_centers: # We", "(0 <= point[0] < self._grid_length) and (0 <= point[1] <", "site. first_sample = np.array(np.random.random_sample(2)) * [grid_length, grid_width] self._active_list = [first_sample]", "= 0.05 _MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2 class PoissonDisc2D(object): \"\"\"Generates", "* self._grid_size_x * self._grid_size_y # Generate the first sample point", "is used for fast nearest # point searching. self._grid =", "[1.0, 1.0, 0.3] def randomize_env(self, env): \"\"\"Generate a random terrain", "to stuck at the common edge of two triangle pieces.", "= 10 _MAX_SAMPLE_SIZE = 30 _MIN_BLOCK_DISTANCE = 0.7 _MAX_BLOCK_LENGTH =", "mesh will only be loaded if terrain_type is set to", "= mesh_scale if mesh_scale else [1.0, 1.0, 0.3] def randomize_env(self,", "we recommend using hard contacts (or high stiffness values) for", "Args: env: A minitaur gym environment. \"\"\" poisson_disc = PoissonDisc2D(_GRID_LENGTH,", "array. \"\"\" return self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self, point): \"\"\"Computes the 2D", "[first_sample] # Also store the sample point in the grid.", "2 * self._min_radius) random_angle = np.random.uniform(0, 2 * math.pi) #", "fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale) env.ground_id = env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0,", "points around some existing point. Removes the sampling base point", "is close to any already sampled (and stored) points. Args:", "grid_length] x [0, grid_width] \"\"\" while self._active_list: self.sample() all_sites =", "_index_2d_to_1d(self, index2d): \"\"\"Converts the 2D index to the 1D position", "The points are inside the quare [0, grid_length] x [0,", "The sampled 2D points near the active point sample =", "point (in some base cell), new points will not be", "from within the same base cell. Returns: All sampled points.", "the random terrain using a triangle mesh. It is possible", "and is more suitable for generating a spatial distribution of", "/ self._cell_length) return x_index, y_index def _index_2d_to_1d(self, index2d): \"\"\"Converts the", "[2, _GRID_WIDTH / 2] # Do not place blocks near", "near the active point sample = random_radius * np.array([np.cos(random_angle), np.sin(random_angle)])", "which points are sampled. min_radius: The minimum distance between any", "is inside the grid. \"\"\" return (0 <= index2d[0] <", "front of the robot. shifted_center = np.array(center) - [2, _GRID_WIDTH", "points. The points are inside the quare [0, grid_length] x", "1, py + 2)): if not self._is_in_range(neighbor_cell): continue maybe_a_point =", "the Possion disk algorithm to add some random blocks on", "the point belongs to. y_index: The y index of the", "within the same base cell. Returns: All sampled points. The", "pieces. To prevent this from happening, we recommend using hard", "xrange(py - 1, py + 2)): if not self._is_in_range(neighbor_cell): continue", "effect in uniform N-D distribution. Args: env: A minitaur gym", "points. \"\"\" active_point = self._active_list.pop() for _ in xrange(self._max_sample_size): #", "y_index: The y index of the cell the point belongs", "math.sqrt(2) self._grid_length = grid_length self._grid_width = grid_width self._grid_size_x = int(grid_length", "* np.array([np.cos(random_angle), np.sin(random_angle)]) + active_point if not self._is_in_grid(sample): continue if", "random convex blocks to the flat ground. We use the", "boundary. Args: point: A 2D point (list) described by its", "self._terrain_type is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def _load_triangle_mesh(self, env): \"\"\"Represents the random", "existing points for neighbor_cell in itertools.product(xrange(px - 1, px +", "scary, the algorithm is in fact O(N), where N is", "point within the self._grid array. \"\"\" return self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self,", "\"\"\"Generates 2D points using Poisson disk sampling method. Implements the", "is the number of cells within the grid. When we", "in the gym env.\"\"\" RANDOM_BLOCKS = 1 TRIANGLE_MESH = 2", "gym environment. \"\"\" env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id = env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1,", "the grid. Returns: The 1D position of the cell within", "\"\"\" active_point = self._active_list.pop() for _ in xrange(self._max_sample_size): # Generate", "import math import enum import numpy as np from pybullet_envs.minitaur.envs", "the grid array. Args: index2d: The 2D index of a", "env.\"\"\" RANDOM_BLOCKS = 1 TRIANGLE_MESH = 2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates", "terrain at Minitaur gym environment reset.\"\"\" from __future__ import absolute_import", "method that creates small clusters of points, Poisson disk method", "the point belongs to. \"\"\" x_index = int(point[0] / self._cell_length)", "in itertools.product(xrange(px - 1, px + 2), xrange(py - 1,", "_point_to_index_2d(self, point): \"\"\"Computes the 2D index (aka cell ID) of", "existing point. Removes the sampling base point and also stores", "\"\"\" while self._active_list: self.sample() all_sites = [] for p in", "random terrain using a triangle mesh. It is possible for", "first sample point and set it as an active site.", "disk algorithm sets the minimum distance between two sampling points,", "sampled. grid_width: The width of the bounding square in which", "= 1 TRIANGLE_MESH = 2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates an uneven", "blocks or load a triangle mesh. mesh_filename: The mesh file", "index2d[1] < self._grid_size_y) def _is_close_to_existing_points(self, point): \"\"\"Checks if the point", "existing points is smaller than the min_radius \"\"\" px, py", "the grid boundary. Args: point: A 2D point (list) described", "point (list) described by its coordinates (x, y). Returns: True", "if they are far enough from all existing points. \"\"\"", "and np.linalg.norm(maybe_a_point - point) < self._min_radius: return True return False", "around some existing point. Removes the sampling base point and", "radius random_radius = np.random.uniform(self._min_radius, 2 * self._min_radius) random_angle = np.random.uniform(0,", "grid. Returns: Whether the cell (2D index) is inside the", "the gym env.\"\"\" def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None): \"\"\"Initializes", "0], where the robot will start. if abs(shifted_center[0]) < 1.0", "env): \"\"\"Generate a random terrain for the current env. Args:", "= [first_sample] # Also store the sample point in the", "in which points are sampled. grid_width: The width of the", "for p in self._grid: if p is not None: all_sites.append(p)", "grid. \"\"\" return (0 <= point[0] < self._grid_length) and (0", "is possible for Minitaur leg to stuck at the common", "baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0, 0]) def _generate_convex_blocks(self, env): \"\"\"Adds random", "_generate_convex_blocks(self, env): \"\"\"Adds random convex blocks to the flat ground.", "O(N), where N is the number of cells within the", "= np.random.uniform(self._min_radius, 2 * self._min_radius) random_angle = np.random.uniform(0, 2 *", "cells within the grid. When we sample around a base", "for neighbor_cell in itertools.product(xrange(px - 1, px + 2), xrange(py", "can check nearby cells for existing points for neighbor_cell in", "The minimum distance between any pair of points. max_sample_size: The", "grid array. Args: point: A 2D point described by its", "points. max_sample_size: The maximum number of sample points around a", "set to TerrainType.TRIANGLE_MESH. mesh_scale: the scaling factor for the triangles", "terrain types we can use in the gym env.\"\"\" RANDOM_BLOCKS", "the common edge of two triangle pieces. To prevent this", "shifted_center = np.array(center) - [2, _GRID_WIDTH / 2] # Do", "point is close to any already sampled (and stored) points.", "< 1.0 and abs(shifted_center[1]) < 1.0: continue half_length = np.random.uniform(_MIN_BLOCK_LENGTH,", "< 1.0: continue half_length = np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 *", "__future__ import absolute_import from __future__ import division from __future__ import", "<= index2d[1] < self._grid_size_y) def _is_close_to_existing_points(self, point): \"\"\"Checks if the", "points are inside the quare [0, grid_length] x [0, grid_width]", "all_sites = [] for p in self._grid: if p is", "2 _MAX_BLOCK_HEIGHT = 0.05 _MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2 class", "\"\"\" self._terrain_type = terrain_type self._mesh_filename = mesh_filename self._mesh_scale = mesh_scale", "two triangle pieces. To prevent this from happening, we recommend", "0]) def _generate_convex_blocks(self, env): \"\"\"Adds random convex blocks to the", "= os.path.dirname(os.path.dirname(currentdir)) parentdir = os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir) import itertools import", "the min_radius \"\"\" px, py = self._point_to_index_2d(point) # Now we", "__init__(self, grid_length, grid_width, min_radius, max_sample_size): \"\"\"Initializes the algorithm. Args: grid_length:", "return False def sample(self): \"\"\"Samples new points around some existing", "np.array([np.cos(random_angle), np.sin(random_angle)]) + active_point if not self._is_in_grid(sample): continue if self._is_close_to_existing_points(sample):", "hard contacts (or high stiffness values) for Minitaur foot in", "2D point (list) described by its coordinates (x, y). Returns:", "is not None and np.linalg.norm(maybe_a_point - point) < self._min_radius: return", "of the cell the point belongs to. \"\"\" x_index =", "mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None): \"\"\"Initializes the randomizer. Args: terrain_type: Whether to", "point is inside the grid. \"\"\" return (0 <= point[0]", "baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0, 0]) def _generate_convex_blocks(self, env): \"\"\"Adds random convex", "self._active_list: self.sample() all_sites = [] for p in self._grid: if", "= 2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates an uneven terrain in the", "point in the grid. Args: point: A 2D point (list)", "return x_index, y_index def _index_2d_to_1d(self, index2d): \"\"\"Converts the 2D index", "reset.\"\"\" from __future__ import absolute_import from __future__ import division from", "the 2D index to the 1D position in the grid", "1D array. The grid is used for fast nearest #", "os.path.dirname(os.path.dirname(currentdir)) parentdir = os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir) import itertools import math", "index2d): \"\"\"Checks if the cell ID is within the grid.", "also stores the new jksampled points if they are far", "use in the gym env.\"\"\" RANDOM_BLOCKS = 1 TRIANGLE_MESH =", "if p is not None: all_sites.append(p) return all_sites class TerrainType(enum.Enum):", "= np.random.uniform(0, 2 * math.pi) # The sampled 2D points", "of the cell the point belongs to. y_index: The y", "min_radius self._max_sample_size = max_sample_size # Flattern the 2D grid as", "distance constraint. Once the current base point is removed, all", "is not None: all_sites.append(p) return all_sites class TerrainType(enum.Enum): \"\"\"The randomzied", "near the current active_point between the radius random_radius = np.random.uniform(self._min_radius,", "want the blocks to be in front of the robot.", "ID) in the grid. Returns: Whether the cell (2D index)", "(list) described by its coordinates (x, y). Returns: True iff", "point (aka the cell ID) in the grid. Returns: The", "print_function import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir))", "\"\"\"Generates the Poisson disc distribution of 2D points. Although the", "of non-overlapping objects. \"\"\" def __init__(self, grid_length, grid_width, min_radius, max_sample_size):", "and (0 <= index2d[1] < self._grid_size_y) def _is_close_to_existing_points(self, point): \"\"\"Checks", "\"\"\"Represents the random terrain using a triangle mesh. It is", "they are far enough from all existing points. \"\"\" active_point", "contacts (or high stiffness values) for Minitaur foot in sim.", "_MAX_BLOCK_LENGTH) / (2 * math.sqrt(2)) half_height = np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) /", "self._mesh_scale = mesh_scale if mesh_scale else [1.0, 1.0, 0.3] def", "RANDOM_BLOCKS = 1 TRIANGLE_MESH = 2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates an", "Returns: x_index: The x index of the cell the point", "\"\"\"Computes the index of a point in the grid array.", "cell the point belongs to. \"\"\" x_index = int(point[0] /", "in block_centers: # We want the blocks to be in", "center in block_centers: # We want the blocks to be", "return index2d[0] + index2d[1] * self._grid_size_x def _is_in_grid(self, point): \"\"\"Checks", "thus voiding the clustering effect in uniform N-D distribution. Args:", "cells for existing points for neighbor_cell in itertools.product(xrange(px - 1,", "uniform N-D distribution. Args: env: A minitaur gym environment. \"\"\"", "neighbor_cell in itertools.product(xrange(px - 1, px + 2), xrange(py -", "minimum distance between points and is more suitable for generating", "gym env.\"\"\" RANDOM_BLOCKS = 1 TRIANGLE_MESH = 2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase):", "the grid. self._grid[self._point_to_index_1d(first_sample)] = first_sample def _point_to_index_1d(self, point): \"\"\"Computes the", "not None and np.linalg.norm(maybe_a_point - point) < self._min_radius: return True", "(in some base cell), new points will not be pushed", "self._cell_length) + 1 self._grid_size_y = int(grid_width / self._cell_length) + 1", "is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if self._terrain_type is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def _load_triangle_mesh(self,", "_MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2 _MAX_BLOCK_HEIGHT =", "\"\"\"The randomzied terrain types we can use in the gym", "inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) parentdir = os.path.dirname(os.path.dirname(parentdir))", "env): \"\"\"Represents the random terrain using a triangle mesh. It", "Possion disk algorithm to add some random blocks on the", "point (list) described by its coordinates (x, y). Returns: x_index:", "will start. if abs(shifted_center[0]) < 1.0 and abs(shifted_center[1]) < 1.0:", "(list) described by its coordinates (x, y). Returns: x_index: The", "np.random.uniform(self._min_radius, 2 * self._min_radius) random_angle = np.random.uniform(0, 2 * math.pi)", "x_index = int(point[0] / self._cell_length) y_index = int(point[1] / self._cell_length)", "for _ in xrange(self._max_sample_size): # Generate random points near the", "the flat ground. We use the Possion disk algorithm to", "points are sampled. min_radius: The minimum distance between any pair", "= 15 _GRID_WIDTH = 10 _MAX_SAMPLE_SIZE = 30 _MIN_BLOCK_DISTANCE =", "is in fact O(N), where N is the number of", "uneven terrain in the gym env.\"\"\" def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\"", "terrain in the gym env.\"\"\" def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\",", "mesh_filename self._mesh_scale = mesh_scale if mesh_scale else [1.0, 1.0, 0.3]", "the sample point in the grid. self._grid[self._point_to_index_1d(first_sample)] = first_sample def", "= os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) parentdir = os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir)", "= random_radius * np.array([np.cos(random_angle), np.sin(random_angle)]) + active_point if not self._is_in_grid(sample):", "is removed, all future searches cannot start from within the", "in the gym env.\"\"\" def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None):", "current base point is removed, all future searches cannot start", "np.random.uniform(0, 2 * math.pi) # The sampled 2D points near", "we sample around a base point (in some base cell),", "PoissonDisc2D(object): \"\"\"Generates 2D points using Poisson disk sampling method. Implements", "basePosition=[0, 0, 0]) def _generate_convex_blocks(self, env): \"\"\"Adds random convex blocks", "1 self._min_radius = min_radius self._max_sample_size = max_sample_size # Flattern the", "= 0.7 _MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2", "* [grid_length, grid_width] self._active_list = [first_sample] # Also store the", "cell ID) in the grid. Returns: The 1D position of", "environment. \"\"\" poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE) block_centers =", "recommend using hard contacts (or high stiffness values) for Minitaur", "(aka the cell ID) in the grid. Returns: The 1D", "Args: grid_length: The length of the bounding square in which", "bounding square in which points are sampled. min_radius: The minimum", "the point to any existing points is smaller than the", "* math.pi) # The sampled 2D points near the active", "array. \"\"\" return index2d[0] + index2d[1] * self._grid_size_x def _is_in_grid(self,", "are sampled. min_radius: The minimum distance between any pair of", "math.pi) # The sampled 2D points near the active point", "random terrain at Minitaur gym environment reset.\"\"\" from __future__ import", "Returns: True iff the distance of the point to any", "a triangle mesh. It is possible for Minitaur leg to", "by its coordinates (x, y). Returns: The index of the", "to be used. The mesh will only be loaded if", "Args: terrain_type: Whether to generate random blocks or load a", "index of a point in the grid array. Args: point:", "randomizer. Args: terrain_type: Whether to generate random blocks or load", "between points and is more suitable for generating a spatial", "< self._grid_width) def _is_in_range(self, index2d): \"\"\"Checks if the cell ID", "minitaur gym environment. \"\"\" if self._terrain_type is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if", "parentdir = os.path.dirname(os.path.dirname(currentdir)) parentdir = os.path.dirname(os.path.dirname(parentdir)) os.sys.path.insert(0, parentdir) import itertools", "environment. \"\"\" env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id = env.pybullet_client.createCollisionShape( shapeType=env.pybullet_client.GEOM_MESH, fileName=self._mesh_filename, flags=1, meshScale=self._mesh_scale)", "2)): if not self._is_in_range(neighbor_cell): continue maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point", "self._grid = [None] * self._grid_size_x * self._grid_size_y # Generate the", "in xrange(self._max_sample_size): # Generate random points near the current active_point", "if the point is inside the grid boundary. Args: point:", "0, 0]) def _generate_convex_blocks(self, env): \"\"\"Adds random convex blocks to", "environment. \"\"\" if self._terrain_type is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env) if self._terrain_type is", "math.sqrt(2)) half_height = np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) / 2 box_id = env.pybullet_client.createCollisionShape(", "= _MAX_BLOCK_HEIGHT / 2 class PoissonDisc2D(object): \"\"\"Generates 2D points using", "in: http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf Unlike the uniform sampling method that creates small", "inside the grid. \"\"\" return (0 <= index2d[0] < self._grid_size_x)", "+ 2), xrange(py - 1, py + 2)): if not", "ID) in the grid. Returns: The 1D position of the", "np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) / 2 box_id = env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length,", "of the bounding square in which points are sampled. grid_width:", "smaller than the min_radius \"\"\" px, py = self._point_to_index_2d(point) #", "self._point_to_index_2d(point) # Now we can check nearby cells for existing", "= sample def generate(self): \"\"\"Generates the Poisson disc distribution of", "+ 2)): if not self._is_in_range(neighbor_cell): continue maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)] if", "# Flattern the 2D grid as an 1D array. The", "that creates small clusters of points, Poisson disk method enforces", "the grid. \"\"\" return (0 <= index2d[0] < self._grid_size_x) and", "* self._grid_size_y # Generate the first sample point and set", "between any pair of points. max_sample_size: The maximum number of", "the cell the point belongs to. \"\"\" x_index = int(point[0]", "around a base point (in some base cell), new points", "y_index def _index_2d_to_1d(self, index2d): \"\"\"Converts the 2D index to the", "any existing points is smaller than the min_radius \"\"\" px,", "if the point is close to any already sampled (and", "convex blocks to the flat ground. We use the Possion", "enforces the minimum distance between points and is more suitable", "sample point in the grid. self._grid[self._point_to_index_1d(first_sample)] = first_sample def _point_to_index_1d(self,", "first_sample = np.array(np.random.random_sample(2)) * [grid_length, grid_width] self._active_list = [first_sample] #", "= int(point[1] / self._cell_length) return x_index, y_index def _index_2d_to_1d(self, index2d):", "sets the minimum distance between two sampling points, thus voiding", "= self._point_to_index_2d(point) # Now we can check nearby cells for", "/ 2 class PoissonDisc2D(object): \"\"\"Generates 2D points using Poisson disk", "and (0 <= point[1] < self._grid_width) def _is_in_range(self, index2d): \"\"\"Checks", "Whether to generate random blocks or load a triangle mesh.", "sampled 2D points near the active point sample = random_radius", "the mesh file. \"\"\" self._terrain_type = terrain_type self._mesh_filename = mesh_filename", "\"\"\" return (0 <= index2d[0] < self._grid_size_x) and (0 <=", "the while loop looks scary, the algorithm is in fact", "if mesh_scale else [1.0, 1.0, 0.3] def randomize_env(self, env): \"\"\"Generate", "an uneven terrain in the gym env.\"\"\" def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH,", "env.\"\"\" def __init__(self, terrain_type=TerrainType.TRIANGLE_MESH, mesh_filename=\"robotics/reinforcement_learning/minitaur/envs/testdata/\" \"triangle_mesh_terrain/terrain9735.obj\", mesh_scale=None): \"\"\"Initializes the randomizer.", "max_sample_size # Flattern the 2D grid as an 1D array.", "= mesh_filename self._mesh_scale = mesh_scale if mesh_scale else [1.0, 1.0,", "the clustering effect in uniform N-D distribution. Args: env: A", "_MAX_BLOCK_HEIGHT) / 2 box_id = env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length, half_height])", "A minitaur gym environment. \"\"\" poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH, _MIN_BLOCK_DISTANCE,", "Whether the cell (2D index) is inside the grid. \"\"\"", "the current env. Args: env: A minitaur gym environment. \"\"\"", "as an 1D array. The grid is used for fast", "inside the grid boundary. Args: point: A 2D point (list)", "Poisson disc distribution of 2D points. Although the while loop", "__future__ import division from __future__ import print_function import os, inspect", "sim. Args: env: A minitaur gym environment. \"\"\" env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id", "self._grid_length) and (0 <= point[1] < self._grid_width) def _is_in_range(self, index2d):", "point belongs to. y_index: The y index of the cell", "2D point described by its coordinates (x, y). Returns: The", "it as an active site. first_sample = np.array(np.random.random_sample(2)) * [grid_length,", "method enforces the minimum distance between points and is more", "described by its coordinates (x, y). Returns: Whether the point", "close to any already sampled (and stored) points. Args: point:", "Args: point: A 2D point described by its coordinates (x,", "not self._is_in_grid(sample): continue if self._is_close_to_existing_points(sample): continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] = sample", "iff the distance of the point to any existing points", "load a triangle mesh. mesh_filename: The mesh file to be", "mesh. It is possible for Minitaur leg to stuck at", "os.sys.path.insert(0, parentdir) import itertools import math import enum import numpy", "not self._is_in_range(neighbor_cell): continue maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)] if maybe_a_point is not", "be in front of the robot. shifted_center = np.array(center) -", "= np.random.uniform(_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 * math.sqrt(2)) half_height = np.random.uniform(_MIN_BLOCK_HEIGHT,", "the algorithm is in fact O(N), where N is the", "using hard contacts (or high stiffness values) for Minitaur foot", "sample(self): \"\"\"Samples new points around some existing point. Removes the", "of the point to any existing points is smaller than", "of points, Poisson disk method enforces the minimum distance between", "sampling base point and also stores the new jksampled points", "around a active site. See details in the algorithm description.", "return self._index_2d_to_1d(self._point_to_index_2d(point)) def _point_to_index_2d(self, point): \"\"\"Computes the 2D index (aka", "between two sampling points, thus voiding the clustering effect in", "of the minimum distance constraint. Once the current base point", "to any already sampled (and stored) points. Args: point: A", "two sampling points, thus voiding the clustering effect in uniform", "/ (2 * math.sqrt(2)) half_height = np.random.uniform(_MIN_BLOCK_HEIGHT, _MAX_BLOCK_HEIGHT) / 2", "the grid. \"\"\" return (0 <= point[0] < self._grid_length) and", "all existing points. \"\"\" active_point = self._active_list.pop() for _ in", "be used. The mesh will only be loaded if terrain_type", "fast nearest # point searching. self._grid = [None] * self._grid_size_x", "2] # Do not place blocks near the point [0,", "the active point sample = random_radius * np.array([np.cos(random_angle), np.sin(random_angle)]) +", "array. The grid is used for fast nearest # point", "ID is within the grid. Args: index2d: The 2D index", "loop looks scary, the algorithm is in fact O(N), where", "in which points are sampled. min_radius: The minimum distance between", "of a point in the grid array. Args: point: A", "array. Args: index2d: The 2D index of a point (aka", "distance of the point to any existing points is smaller", "= _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2 _MAX_BLOCK_HEIGHT = 0.05", "(list) described by its coordinates (x, y). Returns: Whether the", "point (aka the cell ID) in the grid. Returns: Whether", "between the radius random_radius = np.random.uniform(self._min_radius, 2 * self._min_radius) random_angle", "sampled points. The points are inside the quare [0, grid_length]", "2D points using Poisson disk sampling method. Implements the algorithm", "active_point between the radius random_radius = np.random.uniform(self._min_radius, 2 * self._min_radius)", "\"\"\"Adds random convex blocks to the flat ground. We use", "np.array(center) - [2, _GRID_WIDTH / 2] # Do not place", "using Poisson disk sampling method. Implements the algorithm described in:", "self._cell_length) + 1 self._min_radius = min_radius self._max_sample_size = max_sample_size #", "if self._terrain_type is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def _load_triangle_mesh(self, env): \"\"\"Represents the", "uniform sampling method that creates small clusters of points, Poisson", "as an active site. first_sample = np.array(np.random.random_sample(2)) * [grid_length, grid_width]", "(2D index) is inside the grid. \"\"\" return (0 <=", "min_radius \"\"\" px, py = self._point_to_index_2d(point) # Now we can", "Returns: Whether the point is inside the grid. \"\"\" return", "* self._grid_size_x def _is_in_grid(self, point): \"\"\"Checks if the point is", "the same base cell. Returns: All sampled points. The points", "all_sites class TerrainType(enum.Enum): \"\"\"The randomzied terrain types we can use", "blocks near the point [0, 0], where the robot will", "if abs(shifted_center[0]) < 1.0 and abs(shifted_center[1]) < 1.0: continue half_length", "terrain_type is set to TerrainType.TRIANGLE_MESH. mesh_scale: the scaling factor for", "point in the grid. self._grid[self._point_to_index_1d(first_sample)] = first_sample def _point_to_index_1d(self, point):", "is within the grid. Args: index2d: The 2D index of", "# Now we can check nearby cells for existing points", "grid_width, min_radius, max_sample_size): \"\"\"Initializes the algorithm. Args: grid_length: The length", "base point is removed, all future searches cannot start from", "maximum number of sample points around a active site. See", "env.ground_id = env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=terrain_collision_shape_id, basePosition=[0, 0, 0]) def _generate_convex_blocks(self,", "< self._grid_length) and (0 <= point[1] < self._grid_width) def _is_in_range(self,", "def randomize_env(self, env): \"\"\"Generate a random terrain for the current", "y). Returns: Whether the point is inside the grid. \"\"\"", "self._generate_convex_blocks(env) def _load_triangle_mesh(self, env): \"\"\"Represents the random terrain using a", "Args: env: A minitaur gym environment. \"\"\" env.pybullet_client.removeBody(env.ground_id) terrain_collision_shape_id =", "a point (aka the cell ID) in the grid. Returns:", "= [None] * self._grid_size_x * self._grid_size_y # Generate the first", "self._load_triangle_mesh(env) if self._terrain_type is TerrainType.RANDOM_BLOCKS: self._generate_convex_blocks(env) def _load_triangle_mesh(self, env): \"\"\"Represents", "grid is used for fast nearest # point searching. self._grid", "\"\"\"Generate a random terrain for the current env. Args: env:", "index of a point (aka the cell ID) in the", "\"\"\" def __init__(self, grid_length, grid_width, min_radius, max_sample_size): \"\"\"Initializes the algorithm.", "base point and also stores the new jksampled points if", "of points. max_sample_size: The maximum number of sample points around", "pushed into the base cell because of the minimum distance", "< self._min_radius: return True return False def sample(self): \"\"\"Samples new", "used. The mesh will only be loaded if terrain_type is", "def _generate_convex_blocks(self, env): \"\"\"Adds random convex blocks to the flat", "\"\"\" x_index = int(point[0] / self._cell_length) y_index = int(point[1] /", "prevent this from happening, we recommend using hard contacts (or", "on the ground. Possion disk algorithm sets the minimum distance", "y). Returns: True iff the distance of the point to", "# Generate the first sample point and set it as", "at the common edge of two triangle pieces. To prevent", "distance between any pair of points. max_sample_size: The maximum number", "index of the point within the self._grid array. \"\"\" return", "def _is_in_grid(self, point): \"\"\"Checks if the point is inside the", "quare [0, grid_length] x [0, grid_width] \"\"\" while self._active_list: self.sample()", "absolute_import from __future__ import division from __future__ import print_function import", "mesh_filename: The mesh file to be used. The mesh will", "to. \"\"\" x_index = int(point[0] / self._cell_length) y_index = int(point[1]", "mesh file to be used. The mesh will only be", "stiffness values) for Minitaur foot in sim. Args: env: A", "random_angle = np.random.uniform(0, 2 * math.pi) # The sampled 2D", "Returns: Whether the cell (2D index) is inside the grid.", "_MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2 _MAX_BLOCK_HEIGHT = 0.05 _MIN_BLOCK_HEIGHT", "nearest # point searching. self._grid = [None] * self._grid_size_x *", "the point is inside the grid boundary. Args: point: A", "self._is_in_grid(sample): continue if self._is_close_to_existing_points(sample): continue self._active_list.append(sample) self._grid[self._point_to_index_1d(sample)] = sample def", "/ 2 _MAX_BLOCK_HEIGHT = 0.05 _MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2", "the point is close to any already sampled (and stored)", "grid_width] self._active_list = [first_sample] # Also store the sample point", "active site. first_sample = np.array(np.random.random_sample(2)) * [grid_length, grid_width] self._active_list =", "cell the point belongs to. y_index: The y index of", "active point sample = random_radius * np.array([np.cos(random_angle), np.sin(random_angle)]) + active_point", "disc distribution of 2D points. Although the while loop looks", "pair of points. max_sample_size: The maximum number of sample points", "(x, y). Returns: Whether the point is inside the grid.", "if the cell ID is within the grid. Args: index2d:", "clustering effect in uniform N-D distribution. Args: env: A minitaur", "sample def generate(self): \"\"\"Generates the Poisson disc distribution of 2D", "loaded if terrain_type is set to TerrainType.TRIANGLE_MESH. mesh_scale: the scaling", "can use in the gym env.\"\"\" RANDOM_BLOCKS = 1 TRIANGLE_MESH", "its coordinates (x, y). Returns: x_index: The x index of", "def _point_to_index_2d(self, point): \"\"\"Computes the 2D index (aka cell ID)", "set it as an active site. first_sample = np.array(np.random.random_sample(2)) *", "= min_radius self._max_sample_size = max_sample_size # Flattern the 2D grid", "points near the current active_point between the radius random_radius =", "[0, 0], where the robot will start. if abs(shifted_center[0]) <", "square in which points are sampled. min_radius: The minimum distance", "described by its coordinates (x, y). Returns: The index of", "min_radius / math.sqrt(2) self._grid_length = grid_length self._grid_width = grid_width self._grid_size_x", "grid. Args: index2d: The 2D index of a point (aka", "numpy as np from pybullet_envs.minitaur.envs import env_randomizer_base _GRID_LENGTH = 15", "_MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2 class PoissonDisc2D(object): \"\"\"Generates 2D points", "randomzied terrain types we can use in the gym env.\"\"\"", "Minitaur gym environment reset.\"\"\" from __future__ import absolute_import from __future__", "fact O(N), where N is the number of cells within", "A minitaur gym environment. \"\"\" if self._terrain_type is TerrainType.TRIANGLE_MESH: self._load_triangle_mesh(env)", "future searches cannot start from within the same base cell.", "self._grid_size_x * self._grid_size_y # Generate the first sample point and", "terrain using a triangle mesh. It is possible for Minitaur", "its coordinates (x, y). Returns: Whether the point is inside", "point: A 2D point (list) described by its coordinates (x,", "of the point within the self._grid array. \"\"\" return self._index_2d_to_1d(self._point_to_index_2d(point))", "points is smaller than the min_radius \"\"\" px, py =", "from pybullet_envs.minitaur.envs import env_randomizer_base _GRID_LENGTH = 15 _GRID_WIDTH = 10", "first_sample def _point_to_index_1d(self, point): \"\"\"Computes the index of a point", "Generate the first sample point and set it as an", "\"\"\"Checks if the cell ID is within the grid. Args:", "where the robot will start. if abs(shifted_center[0]) < 1.0 and", "All sampled points. The points are inside the quare [0,", "robot. shifted_center = np.array(center) - [2, _GRID_WIDTH / 2] #", "2 class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase): \"\"\"Generates an uneven terrain in the gym", "= poisson_disc.generate() for center in block_centers: # We want the", "box_id = env.pybullet_client.createCollisionShape( env.pybullet_client.GEOM_BOX, halfExtents=[half_length, half_length, half_height]) env.pybullet_client.createMultiBody( baseMass=0, baseCollisionShapeIndex=box_id,", "x_index, y_index def _index_2d_to_1d(self, index2d): \"\"\"Converts the 2D index to", "/ math.sqrt(2) self._grid_length = grid_length self._grid_width = grid_width self._grid_size_x =", "width of the bounding square in which points are sampled.", "grid. When we sample around a base point (in some", "/ self._cell_length) + 1 self._grid_size_y = int(grid_width / self._cell_length) +", "point to any existing points is smaller than the min_radius", "_MIN_BLOCK_DISTANCE = 0.7 _MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE _MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH /", "some base cell), new points will not be pushed into", "the 1D position in the grid array. Args: index2d: The", "sampling method that creates small clusters of points, Poisson disk" ]
[ "from psycopg2.sql import SQL, Placeholder from .expression import Expression class", "from polecat.db.query import query as query_module from psycopg2.sql import SQL,", "else: get_values_sql = partial( self.get_values_sql_from_dict, self.values ) return self.get_values_sql(get_values_sql) def", "column_name, column_value in row: value_sql, value = self.value_to_sql(column_value, column_name) row_values_sql.append(value_sql)", "def get_values_sql(self, get_values_sql): values_sql, values_args = get_values_sql() joined_sql = SQL(',", "value_to_sql(self, value, column_name=None): if isinstance(value, Expression): sql, args = value.to_sql()", "values_dict.items(): value_sql, value = self.value_to_sql(column_value, column_name) column_values_sql.append(value_sql) column_values += value", "self.get_values_sql_from_values, self.values ) else: get_values_sql = partial( self.get_values_sql_from_dict, self.values )", "() for column_name, column_value in values_dict.items(): value_sql, value = self.value_to_sql(column_value,", "column_value in row: value_sql, value = self.value_to_sql(column_value, column_name) row_values_sql.append(value_sql) column_values", "= () for column_name, column_value in values_dict.items(): value_sql, value =", "get_values_sql): values_sql, values_args = get_values_sql() joined_sql = SQL(', ').join( SQL('({})').format(", "Values(Expression): def __init__(self, values, relation=None): self.values = values self.relation =", "= self.value_to_sql(column_value, column_name) column_values_sql.append(value_sql) column_values += value return (column_values_sql,), column_values", "self.values ) return self.get_values_sql(get_values_sql) def get_values_sql(self, get_values_sql): values_sql, values_args =", "Expression class Values(Expression): def __init__(self, values, relation=None): self.values = values", "+= value return (column_values_sql,), column_values def value_to_sql(self, value, column_name=None): if", "= column.to_db_value(value) return Placeholder(), (value,) def iter_column_names(self): if isinstance(self.values, dict):", "if self.relation and column_name: column = self.relation.get_column(column_name) value = column.to_db_value(value)", "import Expression class Values(Expression): def __init__(self, values, relation=None): self.values =", "query_module.Values): get_values_sql = partial( self.get_values_sql_from_values, self.values ) else: get_values_sql =", "return self.get_values_sql(get_values_sql) def get_values_sql(self, get_values_sql): values_sql, values_args = get_values_sql() joined_sql", "return column_values_sql, column_values def get_values_sql_from_dict(self, values_dict): column_values_sql = [] column_values", "[] for column_name, column_value in row: value_sql, value = self.value_to_sql(column_value,", "query as query_module from psycopg2.sql import SQL, Placeholder from .expression", "get_values_sql = partial( self.get_values_sql_from_values, self.values ) else: get_values_sql = partial(", "values_sql ) return SQL('%s {}' % self.keyword).format(joined_sql), values_args def get_values_sql_from_values(self,", "column_values = () for column_name, column_value in values_dict.items(): value_sql, value", "'VALUES' def to_sql(self): if isinstance(self.values, query_module.Values): get_values_sql = partial( self.get_values_sql_from_values,", "column.to_db_value(value) return Placeholder(), (value,) def iter_column_names(self): if isinstance(self.values, dict): return", "{}' % self.keyword).format(joined_sql), values_args def get_values_sql_from_values(self, values): column_values_sql = []", "for column_name, column_value in row: value_sql, value = self.value_to_sql(column_value, column_name)", "value = self.value_to_sql(column_value, column_name) column_values_sql.append(value_sql) column_values += value return (column_values_sql,),", "column_values_sql.append(value_sql) column_values += value return (column_values_sql,), column_values def value_to_sql(self, value,", "column_name: column = self.relation.get_column(column_name) value = column.to_db_value(value) return Placeholder(), (value,)", "= 'VALUES' def to_sql(self): if isinstance(self.values, query_module.Values): get_values_sql = partial(", "self.relation.get_column(column_name) value = column.to_db_value(value) return Placeholder(), (value,) def iter_column_names(self): if", ") for row_sql in values_sql ) return SQL('%s {}' %", "values.iter_rows(): row_values_sql = [] for column_name, column_value in row: value_sql,", "values self.relation = relation self.keyword = 'VALUES' def to_sql(self): if", "[] column_values = () for row in values.iter_rows(): row_values_sql =", "(column_values_sql,), column_values def value_to_sql(self, value, column_name=None): if isinstance(value, Expression): sql,", "from functools import partial from polecat.db.query import query as query_module", "def get_values_sql_from_values(self, values): column_values_sql = [] column_values = () for", "column_values += value return (column_values_sql,), column_values def value_to_sql(self, value, column_name=None):", "as query_module from psycopg2.sql import SQL, Placeholder from .expression import", "').join( SQL('({})').format( SQL(', ').join(row_sql) ) for row_sql in values_sql )", "relation=None): self.values = values self.relation = relation self.keyword = 'VALUES'", "= [] for column_name, column_value in row: value_sql, value =", "= get_values_sql() joined_sql = SQL(', ').join( SQL('({})').format( SQL(', ').join(row_sql) )", "partial( self.get_values_sql_from_dict, self.values ) return self.get_values_sql(get_values_sql) def get_values_sql(self, get_values_sql): values_sql,", "values_args def get_values_sql_from_values(self, values): column_values_sql = [] column_values = ()", "if isinstance(self.values, query_module.Values): get_values_sql = partial( self.get_values_sql_from_values, self.values ) else:", "column = self.relation.get_column(column_name) value = column.to_db_value(value) return Placeholder(), (value,) def", "= value.to_sql() return SQL('{}').format(sql), args else: if self.relation and column_name:", "for column_name, column_value in values_dict.items(): value_sql, value = self.value_to_sql(column_value, column_name)", "column_values def get_values_sql_from_dict(self, values_dict): column_values_sql = [] column_values = ()", "value_sql, value = self.value_to_sql(column_value, column_name) column_values_sql.append(value_sql) column_values += value return", "__init__(self, values, relation=None): self.values = values self.relation = relation self.keyword", "values): column_values_sql = [] column_values = () for row in", "row in values.iter_rows(): row_values_sql = [] for column_name, column_value in", "values_sql, values_args = get_values_sql() joined_sql = SQL(', ').join( SQL('({})').format( SQL(',", "from .expression import Expression class Values(Expression): def __init__(self, values, relation=None):", "column_name, column_value in values_dict.items(): value_sql, value = self.value_to_sql(column_value, column_name) column_values_sql.append(value_sql)", ") return self.get_values_sql(get_values_sql) def get_values_sql(self, get_values_sql): values_sql, values_args = get_values_sql()", ") return SQL('%s {}' % self.keyword).format(joined_sql), values_args def get_values_sql_from_values(self, values):", "self.value_to_sql(column_value, column_name) row_values_sql.append(value_sql) column_values += value column_values_sql.append(row_values_sql) return column_values_sql, column_values", "value return (column_values_sql,), column_values def value_to_sql(self, value, column_name=None): if isinstance(value,", "column_values def value_to_sql(self, value, column_name=None): if isinstance(value, Expression): sql, args", "in values_sql ) return SQL('%s {}' % self.keyword).format(joined_sql), values_args def", "row_sql in values_sql ) return SQL('%s {}' % self.keyword).format(joined_sql), values_args", "def __init__(self, values, relation=None): self.values = values self.relation = relation", "for row in values.iter_rows(): row_values_sql = [] for column_name, column_value", "get_values_sql(self, get_values_sql): values_sql, values_args = get_values_sql() joined_sql = SQL(', ').join(", "column_values_sql, column_values def get_values_sql_from_dict(self, values_dict): column_values_sql = [] column_values =", "Placeholder(), (value,) def iter_column_names(self): if isinstance(self.values, dict): return self.values.keys() else:", "values_args = get_values_sql() joined_sql = SQL(', ').join( SQL('({})').format( SQL(', ').join(row_sql)", "else: if self.relation and column_name: column = self.relation.get_column(column_name) value =", "self.relation = relation self.keyword = 'VALUES' def to_sql(self): if isinstance(self.values,", "get_values_sql_from_values(self, values): column_values_sql = [] column_values = () for row", "value column_values_sql.append(row_values_sql) return column_values_sql, column_values def get_values_sql_from_dict(self, values_dict): column_values_sql =", "relation self.keyword = 'VALUES' def to_sql(self): if isinstance(self.values, query_module.Values): get_values_sql", "query_module from psycopg2.sql import SQL, Placeholder from .expression import Expression", "psycopg2.sql import SQL, Placeholder from .expression import Expression class Values(Expression):", "(value,) def iter_column_names(self): if isinstance(self.values, dict): return self.values.keys() else: return", "column_value in values_dict.items(): value_sql, value = self.value_to_sql(column_value, column_name) column_values_sql.append(value_sql) column_values", "SQL('({})').format( SQL(', ').join(row_sql) ) for row_sql in values_sql ) return", "if isinstance(value, Expression): sql, args = value.to_sql() return SQL('{}').format(sql), args", "= () for row in values.iter_rows(): row_values_sql = [] for", "column_values = () for row in values.iter_rows(): row_values_sql = []", "def get_values_sql_from_dict(self, values_dict): column_values_sql = [] column_values = () for", "def iter_column_names(self): if isinstance(self.values, dict): return self.values.keys() else: return self.values.iter_column_names()", "value, column_name=None): if isinstance(value, Expression): sql, args = value.to_sql() return", "SQL('{}').format(sql), args else: if self.relation and column_name: column = self.relation.get_column(column_name)", "value = self.value_to_sql(column_value, column_name) row_values_sql.append(value_sql) column_values += value column_values_sql.append(row_values_sql) return", "column_name) column_values_sql.append(value_sql) column_values += value return (column_values_sql,), column_values def value_to_sql(self,", "get_values_sql_from_dict(self, values_dict): column_values_sql = [] column_values = () for column_name,", "partial from polecat.db.query import query as query_module from psycopg2.sql import", "% self.keyword).format(joined_sql), values_args def get_values_sql_from_values(self, values): column_values_sql = [] column_values", "column_values_sql = [] column_values = () for row in values.iter_rows():", "[] column_values = () for column_name, column_value in values_dict.items(): value_sql,", "Placeholder from .expression import Expression class Values(Expression): def __init__(self, values,", "= SQL(', ').join( SQL('({})').format( SQL(', ').join(row_sql) ) for row_sql in", "for row_sql in values_sql ) return SQL('%s {}' % self.keyword).format(joined_sql),", "= self.relation.get_column(column_name) value = column.to_db_value(value) return Placeholder(), (value,) def iter_column_names(self):", "in values.iter_rows(): row_values_sql = [] for column_name, column_value in row:", ") else: get_values_sql = partial( self.get_values_sql_from_dict, self.values ) return self.get_values_sql(get_values_sql)", "isinstance(self.values, query_module.Values): get_values_sql = partial( self.get_values_sql_from_values, self.values ) else: get_values_sql", "in values_dict.items(): value_sql, value = self.value_to_sql(column_value, column_name) column_values_sql.append(value_sql) column_values +=", "= partial( self.get_values_sql_from_dict, self.values ) return self.get_values_sql(get_values_sql) def get_values_sql(self, get_values_sql):", "in row: value_sql, value = self.value_to_sql(column_value, column_name) row_values_sql.append(value_sql) column_values +=", "= [] column_values = () for column_name, column_value in values_dict.items():", "get_values_sql() joined_sql = SQL(', ').join( SQL('({})').format( SQL(', ').join(row_sql) ) for", "SQL('%s {}' % self.keyword).format(joined_sql), values_args def get_values_sql_from_values(self, values): column_values_sql =", "column_values_sql = [] column_values = () for column_name, column_value in", "and column_name: column = self.relation.get_column(column_name) value = column.to_db_value(value) return Placeholder(),", "functools import partial from polecat.db.query import query as query_module from", "polecat.db.query import query as query_module from psycopg2.sql import SQL, Placeholder", "column_values += value column_values_sql.append(row_values_sql) return column_values_sql, column_values def get_values_sql_from_dict(self, values_dict):", "value.to_sql() return SQL('{}').format(sql), args else: if self.relation and column_name: column", "<reponame>furious-luke/polecat from functools import partial from polecat.db.query import query as", "= self.value_to_sql(column_value, column_name) row_values_sql.append(value_sql) column_values += value column_values_sql.append(row_values_sql) return column_values_sql,", "row: value_sql, value = self.value_to_sql(column_value, column_name) row_values_sql.append(value_sql) column_values += value", "Expression): sql, args = value.to_sql() return SQL('{}').format(sql), args else: if", "get_values_sql = partial( self.get_values_sql_from_dict, self.values ) return self.get_values_sql(get_values_sql) def get_values_sql(self,", "import partial from polecat.db.query import query as query_module from psycopg2.sql", "import query as query_module from psycopg2.sql import SQL, Placeholder from", "self.get_values_sql_from_dict, self.values ) return self.get_values_sql(get_values_sql) def get_values_sql(self, get_values_sql): values_sql, values_args", "return SQL('%s {}' % self.keyword).format(joined_sql), values_args def get_values_sql_from_values(self, values): column_values_sql", "joined_sql = SQL(', ').join( SQL('({})').format( SQL(', ').join(row_sql) ) for row_sql", ".expression import Expression class Values(Expression): def __init__(self, values, relation=None): self.values", "value = column.to_db_value(value) return Placeholder(), (value,) def iter_column_names(self): if isinstance(self.values,", "row_values_sql.append(value_sql) column_values += value column_values_sql.append(row_values_sql) return column_values_sql, column_values def get_values_sql_from_dict(self,", "').join(row_sql) ) for row_sql in values_sql ) return SQL('%s {}'", "= relation self.keyword = 'VALUES' def to_sql(self): if isinstance(self.values, query_module.Values):", "self.value_to_sql(column_value, column_name) column_values_sql.append(value_sql) column_values += value return (column_values_sql,), column_values def", "= values self.relation = relation self.keyword = 'VALUES' def to_sql(self):", "values, relation=None): self.values = values self.relation = relation self.keyword =", "= partial( self.get_values_sql_from_values, self.values ) else: get_values_sql = partial( self.get_values_sql_from_dict,", "SQL(', ').join(row_sql) ) for row_sql in values_sql ) return SQL('%s", "+= value column_values_sql.append(row_values_sql) return column_values_sql, column_values def get_values_sql_from_dict(self, values_dict): column_values_sql", "args = value.to_sql() return SQL('{}').format(sql), args else: if self.relation and", "() for row in values.iter_rows(): row_values_sql = [] for column_name,", "args else: if self.relation and column_name: column = self.relation.get_column(column_name) value", "value_sql, value = self.value_to_sql(column_value, column_name) row_values_sql.append(value_sql) column_values += value column_values_sql.append(row_values_sql)", "SQL, Placeholder from .expression import Expression class Values(Expression): def __init__(self,", "def to_sql(self): if isinstance(self.values, query_module.Values): get_values_sql = partial( self.get_values_sql_from_values, self.values", "self.get_values_sql(get_values_sql) def get_values_sql(self, get_values_sql): values_sql, values_args = get_values_sql() joined_sql =", "class Values(Expression): def __init__(self, values, relation=None): self.values = values self.relation", "SQL(', ').join( SQL('({})').format( SQL(', ').join(row_sql) ) for row_sql in values_sql", "column_name) row_values_sql.append(value_sql) column_values += value column_values_sql.append(row_values_sql) return column_values_sql, column_values def", "isinstance(value, Expression): sql, args = value.to_sql() return SQL('{}').format(sql), args else:", "def value_to_sql(self, value, column_name=None): if isinstance(value, Expression): sql, args =", "self.values = values self.relation = relation self.keyword = 'VALUES' def", "partial( self.get_values_sql_from_values, self.values ) else: get_values_sql = partial( self.get_values_sql_from_dict, self.values", "return (column_values_sql,), column_values def value_to_sql(self, value, column_name=None): if isinstance(value, Expression):", "column_name=None): if isinstance(value, Expression): sql, args = value.to_sql() return SQL('{}').format(sql),", "self.keyword = 'VALUES' def to_sql(self): if isinstance(self.values, query_module.Values): get_values_sql =", "to_sql(self): if isinstance(self.values, query_module.Values): get_values_sql = partial( self.get_values_sql_from_values, self.values )", "row_values_sql = [] for column_name, column_value in row: value_sql, value", "return Placeholder(), (value,) def iter_column_names(self): if isinstance(self.values, dict): return self.values.keys()", "= [] column_values = () for row in values.iter_rows(): row_values_sql", "import SQL, Placeholder from .expression import Expression class Values(Expression): def", "self.values ) else: get_values_sql = partial( self.get_values_sql_from_dict, self.values ) return", "column_values_sql.append(row_values_sql) return column_values_sql, column_values def get_values_sql_from_dict(self, values_dict): column_values_sql = []", "return SQL('{}').format(sql), args else: if self.relation and column_name: column =", "self.keyword).format(joined_sql), values_args def get_values_sql_from_values(self, values): column_values_sql = [] column_values =", "sql, args = value.to_sql() return SQL('{}').format(sql), args else: if self.relation", "values_dict): column_values_sql = [] column_values = () for column_name, column_value", "self.relation and column_name: column = self.relation.get_column(column_name) value = column.to_db_value(value) return" ]
[ "= build_route(R2.split(',')) with open('day3input.txt') as f: line1, line2 = f.readlines()", "for p in points) #R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 = 'U62,R66,U55,R34,D71,R55,D58,R83'", "def main(): #route1 = build_route(R1.split(',')) #route2 = build_route(R2.split(',')) with open('day3input.txt')", "build_route(directions: list) -> list: current_location = (0, 0) route =", "+ 1, x[1])), 'D': (lambda x: (x[0] - 1, x[1])),", "#R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main(): #route1 =", "(x[0], x[1] + 1)), 'L': (lambda x: (x[0], x[1] -", "= MOVES[direction](current_location) route.append(current_location) return route def find_intersections(r1: list, r2: list)", "= (0, 0) route = [] for d in directions:", "p in points) #R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 = 'U62,R66,U55,R34,D71,R55,D58,R83' #R1", "= 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 = 'U62,R66,U55,R34,D71,R55,D58,R83' #R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 =", "x: (x[0], x[1] - 1)), 'U': (lambda x: (x[0] +", "'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 = 'U62,R66,U55,R34,D71,R55,D58,R83' #R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7'", "_ in range(amount): current_location = MOVES[direction](current_location) route.append(current_location) return route def", "abs(p[1])) for p in points) #R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 =", "return min((abs(p[0]) + abs(p[1])) for p in points) #R1 =", "as f: line1, line2 = f.readlines() route1 = build_route(line1.strip().split(',')) route2", "'L': (lambda x: (x[0], x[1] - 1)), 'U': (lambda x:", "route def find_intersections(r1: list, r2: list) -> set: return set(r1).intersection(set(r2))", "route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1, route2))) if __name__ == \"__main__\": main()", "points) #R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 = 'U62,R66,U55,R34,D71,R55,D58,R83' #R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51'", "day 3 MOVES = { 'R': (lambda x: (x[0], x[1]", "advent day 3 MOVES = { 'R': (lambda x: (x[0],", "r2: list) -> set: return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set) ->", "f: line1, line2 = f.readlines() route1 = build_route(line1.strip().split(',')) route2 =", "= f.readlines() route1 = build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1, route2)))", "x: (x[0], x[1] + 1)), 'L': (lambda x: (x[0], x[1]", "def build_route(directions: list) -> list: current_location = (0, 0) route", "for d in directions: direction, amount = d[0], int(d[1:]) for", "+ 1)), 'L': (lambda x: (x[0], x[1] - 1)), 'U':", "line1, line2 = f.readlines() route1 = build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(','))", "# 2019 advent day 3 MOVES = { 'R': (lambda", "f.readlines() route1 = build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1, route2))) if", "-> int: return min((abs(p[0]) + abs(p[1])) for p in points)", "(x[0] + 1, x[1])), 'D': (lambda x: (x[0] - 1,", "-> list: current_location = (0, 0) route = [] for", "direction, amount = d[0], int(d[1:]) for _ in range(amount): current_location", "'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main(): #route1 = build_route(R1.split(',')) #route2", "set: return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set) -> int: return min((abs(p[0])", "set) -> int: return min((abs(p[0]) + abs(p[1])) for p in", "(x[0] - 1, x[1])), } def build_route(directions: list) -> list:", "current_location = (0, 0) route = [] for d in", "= 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main(): #route1 = build_route(R1.split(',')) #route2 = build_route(R2.split(','))", "- 1)), 'U': (lambda x: (x[0] + 1, x[1])), 'D':", "(lambda x: (x[0], x[1] + 1)), 'L': (lambda x: (x[0],", "MOVES = { 'R': (lambda x: (x[0], x[1] + 1)),", "#R2 = 'U62,R66,U55,R34,D71,R55,D58,R83' #R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def", "min((abs(p[0]) + abs(p[1])) for p in points) #R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72'", "#R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main(): #route1 = build_route(R1.split(',')) #route2 =", "1)), 'L': (lambda x: (x[0], x[1] - 1)), 'U': (lambda", "for _ in range(amount): current_location = MOVES[direction](current_location) route.append(current_location) return route", "directions: direction, amount = d[0], int(d[1:]) for _ in range(amount):", "+ abs(p[1])) for p in points) #R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2", "'U': (lambda x: (x[0] + 1, x[1])), 'D': (lambda x:", "-> set: return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set) -> int: return", "main(): #route1 = build_route(R1.split(',')) #route2 = build_route(R2.split(',')) with open('day3input.txt') as", "build_route(R1.split(',')) #route2 = build_route(R2.split(',')) with open('day3input.txt') as f: line1, line2", "1, x[1])), 'D': (lambda x: (x[0] - 1, x[1])), }", "{ 'R': (lambda x: (x[0], x[1] + 1)), 'L': (lambda", "MOVES[direction](current_location) route.append(current_location) return route def find_intersections(r1: list, r2: list) ->", "#R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 = 'U62,R66,U55,R34,D71,R55,D58,R83' #R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2", "list, r2: list) -> set: return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set)", "(lambda x: (x[0], x[1] - 1)), 'U': (lambda x: (x[0]", "x: (x[0] - 1, x[1])), } def build_route(directions: list) ->", "build_route(R2.split(',')) with open('day3input.txt') as f: line1, line2 = f.readlines() route1", "x[1])), } def build_route(directions: list) -> list: current_location = (0,", "[] for d in directions: direction, amount = d[0], int(d[1:])", "in points) #R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 = 'U62,R66,U55,R34,D71,R55,D58,R83' #R1 =", "return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set) -> int: return min((abs(p[0]) +", "x: (x[0] + 1, x[1])), 'D': (lambda x: (x[0] -", "return route def find_intersections(r1: list, r2: list) -> set: return", "1)), 'U': (lambda x: (x[0] + 1, x[1])), 'D': (lambda", "def find_intersections(r1: list, r2: list) -> set: return set(r1).intersection(set(r2)) def", "int: return min((abs(p[0]) + abs(p[1])) for p in points) #R1", "3 MOVES = { 'R': (lambda x: (x[0], x[1] +", "with open('day3input.txt') as f: line1, line2 = f.readlines() route1 =", "0) route = [] for d in directions: direction, amount", "'D': (lambda x: (x[0] - 1, x[1])), } def build_route(directions:", "route = [] for d in directions: direction, amount =", "x[1] + 1)), 'L': (lambda x: (x[0], x[1] - 1)),", "#route1 = build_route(R1.split(',')) #route2 = build_route(R2.split(',')) with open('day3input.txt') as f:", "list) -> list: current_location = (0, 0) route = []", "= [] for d in directions: direction, amount = d[0],", "list: current_location = (0, 0) route = [] for d", "in directions: direction, amount = d[0], int(d[1:]) for _ in", "in range(amount): current_location = MOVES[direction](current_location) route.append(current_location) return route def find_intersections(r1:", "int(d[1:]) for _ in range(amount): current_location = MOVES[direction](current_location) route.append(current_location) return", "= 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main(): #route1 = build_route(R1.split(','))", "(0, 0) route = [] for d in directions: direction,", "find_shortest_manhattan_distance(points: set) -> int: return min((abs(p[0]) + abs(p[1])) for p", "} def build_route(directions: list) -> list: current_location = (0, 0)", "#route2 = build_route(R2.split(',')) with open('day3input.txt') as f: line1, line2 =", "range(amount): current_location = MOVES[direction](current_location) route.append(current_location) return route def find_intersections(r1: list,", "= build_route(R1.split(',')) #route2 = build_route(R2.split(',')) with open('day3input.txt') as f: line1,", "= d[0], int(d[1:]) for _ in range(amount): current_location = MOVES[direction](current_location)", "find_intersections(r1: list, r2: list) -> set: return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points:", "d[0], int(d[1:]) for _ in range(amount): current_location = MOVES[direction](current_location) route.append(current_location)", "list) -> set: return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set) -> int:", "route1 = build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1, route2))) if __name__", "= build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1, route2))) if __name__ ==", "set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set) -> int: return min((abs(p[0]) + abs(p[1]))", "1, x[1])), } def build_route(directions: list) -> list: current_location =", "= 'U62,R66,U55,R34,D71,R55,D58,R83' #R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main():", "'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main(): #route1 = build_route(R1.split(',')) #route2 = build_route(R2.split(',')) with", "(lambda x: (x[0] - 1, x[1])), } def build_route(directions: list)", "(lambda x: (x[0] + 1, x[1])), 'D': (lambda x: (x[0]", "= { 'R': (lambda x: (x[0], x[1] + 1)), 'L':", "def find_shortest_manhattan_distance(points: set) -> int: return min((abs(p[0]) + abs(p[1])) for", "open('day3input.txt') as f: line1, line2 = f.readlines() route1 = build_route(line1.strip().split(','))", "d in directions: direction, amount = d[0], int(d[1:]) for _", "build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1, route2))) if __name__ == \"__main__\":", "x[1])), 'D': (lambda x: (x[0] - 1, x[1])), } def", "amount = d[0], int(d[1:]) for _ in range(amount): current_location =", "2019 advent day 3 MOVES = { 'R': (lambda x:", "route.append(current_location) return route def find_intersections(r1: list, r2: list) -> set:", "x[1] - 1)), 'U': (lambda x: (x[0] + 1, x[1])),", "line2 = f.readlines() route1 = build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1,", "(x[0], x[1] - 1)), 'U': (lambda x: (x[0] + 1,", "'R': (lambda x: (x[0], x[1] + 1)), 'L': (lambda x:", "- 1, x[1])), } def build_route(directions: list) -> list: current_location", "'U62,R66,U55,R34,D71,R55,D58,R83' #R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main(): #route1", "current_location = MOVES[direction](current_location) route.append(current_location) return route def find_intersections(r1: list, r2:" ]
[ "= await asyncio.create_subprocess_shell(f\"dnsrecon -d {domain} -t crt\", stdout=asyncio.subprocess.PIPE) line =", "fields = line.split() if len(fields)>1 and fields[1]==\"open\": openPort = fields[0].split(\"/\")", "async def findOpenPorts(ip, ports, q): openPorts = [] proc =", "= (await proc.stdout.readline()).decode('utf-8') fields = line.split() if len(fields)>1 and fields[1]==\"A\":", "q.put(fields[2]) domains.append(fields[2]) return domains async def findOpenPorts(ip, ports, q): openPorts", "-d {domain} -t crt\", stdout=asyncio.subprocess.PIPE) line = True while line:", "if q: await q.put({\"ip\": ip, \"port\": openPort[0], \"protocol\": openPort[1]}) openPorts.append({\"port\":", "= [] proc = await asyncio.create_subprocess_shell(f\"nmap -p {ports} --open {ip}\",stdout=asyncio.subprocess.PIPE)", "asyncio.create_subprocess_shell(f\"dnsrecon -d {domain} -t crt\", stdout=asyncio.subprocess.PIPE) line = True while", "[] proc = await asyncio.create_subprocess_shell(f\"nmap -p {ports} --open {ip}\",stdout=asyncio.subprocess.PIPE) line", "line.split() if len(fields)>1 and fields[1]==\"A\": if q: await q.put(fields[2]) domains.append(fields[2])", "= [] proc = await asyncio.create_subprocess_shell(f\"dnsrecon -d {domain} -t crt\",", "openPorts = [] proc = await asyncio.create_subprocess_shell(f\"nmap -p {ports} --open", "ip, \"port\": openPort[0], \"protocol\": openPort[1]}) openPorts.append({\"port\": openPort[0], \"protocol\": openPort[1]}) return", "stdout=asyncio.subprocess.PIPE) line = True while line: line = (await proc.stdout.readline()).decode('utf-8')", "domains = [] proc = await asyncio.create_subprocess_shell(f\"dnsrecon -d {domain} -t", "def searchDomains(domain, q): domains = [] proc = await asyncio.create_subprocess_shell(f\"dnsrecon", "await asyncio.create_subprocess_shell(f\"dnsrecon -d {domain} -t crt\", stdout=asyncio.subprocess.PIPE) line = True", "--open {ip}\",stdout=asyncio.subprocess.PIPE) line = True while line: line = (await", "q): domains = [] proc = await asyncio.create_subprocess_shell(f\"dnsrecon -d {domain}", "ports, q): openPorts = [] proc = await asyncio.create_subprocess_shell(f\"nmap -p", "= True while line: line = (await proc.stdout.readline()).decode('utf-8') fields =", "if len(fields)>1 and fields[1]==\"open\": openPort = fields[0].split(\"/\") if q: await", "proc = await asyncio.create_subprocess_shell(f\"dnsrecon -d {domain} -t crt\", stdout=asyncio.subprocess.PIPE) line", "if len(fields)>1 and fields[1]==\"A\": if q: await q.put(fields[2]) domains.append(fields[2]) return", "[] proc = await asyncio.create_subprocess_shell(f\"dnsrecon -d {domain} -t crt\", stdout=asyncio.subprocess.PIPE)", "asyncio.create_subprocess_shell(f\"nmap -p {ports} --open {ip}\",stdout=asyncio.subprocess.PIPE) line = True while line:", "openPort = fields[0].split(\"/\") if q: await q.put({\"ip\": ip, \"port\": openPort[0],", "import asyncio async def searchDomains(domain, q): domains = [] proc", "{ports} --open {ip}\",stdout=asyncio.subprocess.PIPE) line = True while line: line =", "proc = await asyncio.create_subprocess_shell(f\"nmap -p {ports} --open {ip}\",stdout=asyncio.subprocess.PIPE) line =", "proc.stdout.readline()).decode('utf-8') fields = line.split() if len(fields)>1 and fields[1]==\"open\": openPort =", "await q.put(fields[2]) domains.append(fields[2]) return domains async def findOpenPorts(ip, ports, q):", "while line: line = (await proc.stdout.readline()).decode('utf-8') fields = line.split() if", "domains async def findOpenPorts(ip, ports, q): openPorts = [] proc", "= (await proc.stdout.readline()).decode('utf-8') fields = line.split() if len(fields)>1 and fields[1]==\"open\":", "len(fields)>1 and fields[1]==\"A\": if q: await q.put(fields[2]) domains.append(fields[2]) return domains", "= line.split() if len(fields)>1 and fields[1]==\"open\": openPort = fields[0].split(\"/\") if", "{domain} -t crt\", stdout=asyncio.subprocess.PIPE) line = True while line: line", "domains.append(fields[2]) return domains async def findOpenPorts(ip, ports, q): openPorts =", "return domains async def findOpenPorts(ip, ports, q): openPorts = []", "crt\", stdout=asyncio.subprocess.PIPE) line = True while line: line = (await", "asyncio async def searchDomains(domain, q): domains = [] proc =", "= await asyncio.create_subprocess_shell(f\"nmap -p {ports} --open {ip}\",stdout=asyncio.subprocess.PIPE) line = True", "async def searchDomains(domain, q): domains = [] proc = await", "fields[1]==\"A\": if q: await q.put(fields[2]) domains.append(fields[2]) return domains async def", "searchDomains(domain, q): domains = [] proc = await asyncio.create_subprocess_shell(f\"dnsrecon -d", "def findOpenPorts(ip, ports, q): openPorts = [] proc = await", "{ip}\",stdout=asyncio.subprocess.PIPE) line = True while line: line = (await proc.stdout.readline()).decode('utf-8')", "fields = line.split() if len(fields)>1 and fields[1]==\"A\": if q: await", "(await proc.stdout.readline()).decode('utf-8') fields = line.split() if len(fields)>1 and fields[1]==\"A\": if", "-p {ports} --open {ip}\",stdout=asyncio.subprocess.PIPE) line = True while line: line", "q.put({\"ip\": ip, \"port\": openPort[0], \"protocol\": openPort[1]}) openPorts.append({\"port\": openPort[0], \"protocol\": openPort[1]})", "proc.stdout.readline()).decode('utf-8') fields = line.split() if len(fields)>1 and fields[1]==\"A\": if q:", "await asyncio.create_subprocess_shell(f\"nmap -p {ports} --open {ip}\",stdout=asyncio.subprocess.PIPE) line = True while", "and fields[1]==\"open\": openPort = fields[0].split(\"/\") if q: await q.put({\"ip\": ip,", "= fields[0].split(\"/\") if q: await q.put({\"ip\": ip, \"port\": openPort[0], \"protocol\":", "line = True while line: line = (await proc.stdout.readline()).decode('utf-8') fields", "= line.split() if len(fields)>1 and fields[1]==\"A\": if q: await q.put(fields[2])", "q: await q.put({\"ip\": ip, \"port\": openPort[0], \"protocol\": openPort[1]}) openPorts.append({\"port\": openPort[0],", "line.split() if len(fields)>1 and fields[1]==\"open\": openPort = fields[0].split(\"/\") if q:", "if q: await q.put(fields[2]) domains.append(fields[2]) return domains async def findOpenPorts(ip,", "fields[1]==\"open\": openPort = fields[0].split(\"/\") if q: await q.put({\"ip\": ip, \"port\":", "fields[0].split(\"/\") if q: await q.put({\"ip\": ip, \"port\": openPort[0], \"protocol\": openPort[1]})", "q: await q.put(fields[2]) domains.append(fields[2]) return domains async def findOpenPorts(ip, ports,", "q): openPorts = [] proc = await asyncio.create_subprocess_shell(f\"nmap -p {ports}", "\"port\": openPort[0], \"protocol\": openPort[1]}) openPorts.append({\"port\": openPort[0], \"protocol\": openPort[1]}) return openPorts", "and fields[1]==\"A\": if q: await q.put(fields[2]) domains.append(fields[2]) return domains async", "await q.put({\"ip\": ip, \"port\": openPort[0], \"protocol\": openPort[1]}) openPorts.append({\"port\": openPort[0], \"protocol\":", "True while line: line = (await proc.stdout.readline()).decode('utf-8') fields = line.split()", "line = (await proc.stdout.readline()).decode('utf-8') fields = line.split() if len(fields)>1 and", "len(fields)>1 and fields[1]==\"open\": openPort = fields[0].split(\"/\") if q: await q.put({\"ip\":", "(await proc.stdout.readline()).decode('utf-8') fields = line.split() if len(fields)>1 and fields[1]==\"open\": openPort", "-t crt\", stdout=asyncio.subprocess.PIPE) line = True while line: line =", "line: line = (await proc.stdout.readline()).decode('utf-8') fields = line.split() if len(fields)>1", "findOpenPorts(ip, ports, q): openPorts = [] proc = await asyncio.create_subprocess_shell(f\"nmap" ]
[ "test_get_security_groups_acl(api, validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl(api) ) except Exception", "bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl(api, validator): try: assert", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", ") return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id(api, validator): try: assert is_valid_delete_security_groups_acl_by_id(", "hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return", "True def delete_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result", "substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS", "'text') assert hasattr(obj, 'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return True def delete_security_groups_acl_by_id(api): endpoint_result", "notice shall be included in all copies or substantial portions", "with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_update_security_groups_acl_by_id(json_schema_validate, obj): if", "test_update_security_groups_acl_by_id_default(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id_default(api) ) except Exception", "endpoint_result @pytest.mark.security_groups_acls def test_get_version_default(api, validator): try: assert is_valid_get_version( validator, get_version_default(api)", "{error}\".format(error=original_e)) raise original_e def update_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False, id='string',", "with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def create_security_groups_acl_default(api): endpoint_result", "modelled_content=None, name=None, payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id_default(api, validator):", "test_get_security_groups_acl_default(api, validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl_default(api) ) except Exception", "endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def test_get_version(api, validator):", "endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl_default(api,", "IN THE SOFTWARE. \"\"\" import pytest from fastjsonschema.exceptions import JsonSchemaException", "page=0, size=0, sortasc='string', sortdsc='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl(api,", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj):", "USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import pytest", "except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e", "IDENTITY_SERVICES_ENGINE_VERSION pytestmark = pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION != '3.1.0', reason='version does not match')", "TypeError)): raise original_e def is_valid_update_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return", ") return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl(", "def get_security_groups_acl(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter='value1,value2', filter_type='string', page=0, size=0, sortasc='string',", "MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id(", "assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id_default(api) ) except Exception as original_e: with", "validator, create_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)):", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import", "def create_security_groups_acl(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( aclcontent='string', active_validation=False, description='string', generation_id='string', ip_version='string',", "its affiliates. Permission is hereby granted, free of charge, to", "TypeError)): raise original_e def is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return", "generation_id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls", "Software without restriction, including without limitation the rights to use,", "with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj): if", "original_e def monitor_bulk_status_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result", "hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return", "'text') assert hasattr(obj, 'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return True def monitor_bulk_status_security_groups_acl(api): endpoint_result", ") return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl(api, validator): try: assert is_valid_create_security_groups_acl(", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_create_security_groups_acl(json_schema_validate, obj):", "'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return True def get_security_groups_acl(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter='value1,value2',", "original_e def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj): if not obj: return False assert", "endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id_default(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id_default(api)", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "copies of the Software, and to permit persons to whom", "sortasc=None, sortdsc=None ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_default(api, validator): try:", "hereby granted, free of charge, to any person obtaining a", "to deal in the Software without restriction, including without limitation", "id='string', aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None, payload=None )", "endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id_default(api,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id(api) ) except Exception as original_e: with", "pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_default(api): endpoint_result =", ") except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e))", "as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_get_security_groups_acl(json_schema_validate,", "original_e def update_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False, id='string', aclcontent=None, description=None,", "get_version(api): endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def test_get_version(api,", "test_monitor_bulk_status_security_groups_acl_default(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl_default(api) ) except Exception", "monitor_bulk_status_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)):", "@pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id(api) )", "get_version_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)):", "'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return True", "as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_delete_security_groups_acl_by_id(json_schema_validate,", "endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id_default(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id_default(api)", "assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return True def", "portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",", "name=None, payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl_default(api, validator): try:", "validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl(api) ) except Exception as", "test_delete_security_groups_acl_by_id(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id(api) ) except Exception", "api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type=None, payload=None, resource_media_type=None ) return endpoint_result @pytest.mark.security_groups_acls def", "validator, delete_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest,", "active_validation=False, operation_type=None, payload=None, resource_media_type=None ) return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl_default(api,", "pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def create_security_groups_acl_default(api): endpoint_result =", "is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj): if not obj: return False assert hasattr(obj, 'headers')", "is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert hasattr(obj, 'headers')", "def test_monitor_bulk_status_security_groups_acl_default(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl_default(api) ) except", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "return True def get_security_groups_acl(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter='value1,value2', filter_type='string', page=0,", "'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return True", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "DEALINGS IN THE SOFTWARE. \"\"\" import pytest from fastjsonschema.exceptions import", "pytestmark = pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION != '3.1.0', reason='version does not match') def", "'text') assert hasattr(obj, 'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return True def update_security_groups_acl_by_id(api): endpoint_result", "is_read_only=True, modelled_content={}, name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl(api,", "test_create_security_groups_acl(api, validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl(api) ) except Exception", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj):", "try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl(api) ) except Exception as original_e:", "modify, merge, publish, distribute, sublicense, and/or sell copies of the", ") return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl_default(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl(", "MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def monitor_bulk_status_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl(", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "@pytest.mark.security_groups_acls def test_create_security_groups_acl(api, validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl(api) )", ") return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl(", "try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id_default(api) ) except Exception as original_e:", "endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_default(api, validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl_default(api)", "persons to whom the Software is furnished to do so,", "from fastjsonschema.exceptions import JsonSchemaException from ciscoisesdk.exceptions import MalformedRequest from ciscoisesdk.exceptions", "test_delete_security_groups_acl_by_id_default(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id_default(api) ) except Exception", "limitation the rights to use, copy, modify, merge, publish, distribute,", "subject to the following conditions: The above copyright notice and", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "JsonSchemaException from ciscoisesdk.exceptions import MalformedRequest from ciscoisesdk.exceptions import ciscoisesdkException from", "pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj): if not", "return True def get_version(api): endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result", "is_valid_create_security_groups_acl( validator, create_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "hasattr(obj, 'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return True def get_security_groups_acl(api): endpoint_result = api.security_groups_acls.get_security_groups_acl(", "tests.environment import IDENTITY_SERVICES_ENGINE_VERSION pytestmark = pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION != '3.1.0', reason='version does", "assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response)", "{error}\".format(error=original_e)) raise original_e def create_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( active_validation=False, aclcontent=None,", "MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl(", "size=0, sortasc='string', sortdsc='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl(api, validator):", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_get_version(json_schema_validate, obj):", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A", "pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION != '3.1.0', reason='version does not match') def is_valid_get_security_groups_acl_by_id(json_schema_validate, obj):", "@pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id(api) )", "is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "not match') def is_valid_get_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False", "if not obj: return False assert hasattr(obj, 'headers') assert hasattr(obj,", "'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return True", "Software is furnished to do so, subject to the following", "'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return True def delete_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string'", "MalformedRequest, TypeError)): raise original_e def is_valid_get_version(json_schema_validate, obj): if not obj:", "Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "import pytest from fastjsonschema.exceptions import JsonSchemaException from ciscoisesdk.exceptions import MalformedRequest", "fixtures and tests. Copyright (c) 2021 Cisco and/or its affiliates.", ") return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl_default(api, validator): try: assert is_valid_create_security_groups_acl(", "sell copies of the Software, and to permit persons to", "raise original_e def get_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return", "= api.security_groups_acls.create_security_groups_acl( active_validation=False, aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None,", "included in all copies or substantial portions of the Software.", "= api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id(api, validator):", "original_e def get_version_default(api): endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls", "pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_get_security_groups_acl(json_schema_validate, obj): if not", "print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter=None,", "raise original_e def bulk_request_for_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type=None, payload=None,", "@pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl_default(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl_default(api) )", "obj: return False assert hasattr(obj, 'headers') assert hasattr(obj, 'content') assert", "as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_create_security_groups_acl(json_schema_validate,", "\"\"\"IdentityServicesEngineAPI security_groups_acls API fixtures and tests. Copyright (c) 2021 Cisco", "copy, modify, merge, publish, distribute, sublicense, and/or sell copies of", "get_security_groups_acl(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter='value1,value2', filter_type='string', page=0, size=0, sortasc='string', sortdsc='string'", "try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id_default(api) ) except Exception as original_e:", "validator, get_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)):", "validator, update_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest,", ") return endpoint_result @pytest.mark.security_groups_acls def test_get_version(api, validator): try: assert is_valid_get_version(", "assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response)", "monitor_bulk_status_security_groups_acl(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def", "name=None, payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id_default(api, validator): try:", "\"\"\" import pytest from fastjsonschema.exceptions import JsonSchemaException from ciscoisesdk.exceptions import", "furnished to do so, subject to the following conditions: The", "or substantial portions of the Software. THE SOFTWARE IS PROVIDED", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "operation_type='string', payload=None, resource_media_type='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl(api, validator):", "assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl_default(api) ) except Exception as original_e: with", "<reponame>CiscoISE/ciscoisesdk # -*- coding: utf-8 -*- \"\"\"IdentityServicesEngineAPI security_groups_acls API fixtures", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl(api, validator): try:", "publish, distribute, sublicense, and/or sell copies of the Software, and", "return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl(api, validator): try: assert is_valid_create_security_groups_acl( validator,", "def get_version_default(api): endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def", "import IDENTITY_SERVICES_ENGINE_VERSION pytestmark = pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION != '3.1.0', reason='version does not", "\"Software\"), to deal in the Software without restriction, including without", "create_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( active_validation=False, aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None,", "return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl(api, validator): try: assert is_valid_get_security_groups_acl( validator,", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "obj): if not obj: return False assert hasattr(obj, 'headers') assert", "endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string', active_validation=False, description='string', generation_id='string', id='string', ip_version='string', is_read_only=True,", "with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj): if", "-*- coding: utf-8 -*- \"\"\"IdentityServicesEngineAPI security_groups_acls API fixtures and tests.", "be included in all copies or substantial portions of the", "create_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)):", "print(\"ERROR: {error}\".format(error=original_e)) raise original_e def monitor_bulk_status_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string'", "assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return True def", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def", "@pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl(api) )", "endpoint_result = api.security_groups_acls.create_security_groups_acl( aclcontent='string', active_validation=False, description='string', generation_id='string', ip_version='string', is_read_only=True, modelled_content={},", "is_valid_get_version(json_schema_validate, obj): if not obj: return False assert hasattr(obj, 'headers')", "return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator,", "return endpoint_result @pytest.mark.security_groups_acls def test_get_version(api, validator): try: assert is_valid_get_version( validator,", "True def get_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result", "with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def update_security_groups_acl_by_id_default(api): endpoint_result", "'headers') assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response')", "try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id(api) ) except Exception as original_e:", "description='string', generation_id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None ) return endpoint_result", "= api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type=None, payload=None, resource_media_type=None ) return endpoint_result @pytest.mark.security_groups_acls", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_by_id_default(api):", ") except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise", "as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_bulk_request_for_security_groups_acl(json_schema_validate,", "try: assert is_valid_get_version( validator, get_version(api) ) except Exception as original_e:", "'text') assert hasattr(obj, 'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return True def get_version(api): endpoint_result", "page=None, size=None, sortasc=None, sortdsc=None ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_default(api,", "the following conditions: The above copyright notice and this permission", "files (the \"Software\"), to deal in the Software without restriction,", "pytest from fastjsonschema.exceptions import JsonSchemaException from ciscoisesdk.exceptions import MalformedRequest from", "validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl(api) ) except Exception as", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF", "json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return True def bulk_request_for_security_groups_acl(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type='string',", "is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "return True def monitor_bulk_status_security_groups_acl(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return", "the rights to use, copy, modify, merge, publish, distribute, sublicense,", "filter='value1,value2', filter_type='string', page=0, size=0, sortasc='string', sortdsc='string' ) return endpoint_result @pytest.mark.security_groups_acls", "software and associated documentation files (the \"Software\"), to deal in", "modelled_content={}, name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id(api, validator):", "SOFTWARE. \"\"\" import pytest from fastjsonschema.exceptions import JsonSchemaException from ciscoisesdk.exceptions", "notice and this permission notice shall be included in all", "@pytest.mark.security_groups_acls def test_create_security_groups_acl_default(api, validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl_default(api) )", "pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_update_security_groups_acl_by_id(json_schema_validate, obj): if not", "is hereby granted, free of charge, to any person obtaining", "api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def test_get_version_default(api, validator): try: assert", "import MalformedRequest from ciscoisesdk.exceptions import ciscoisesdkException from tests.environment import IDENTITY_SERVICES_ENGINE_VERSION", "assert hasattr(obj, 'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return True def update_security_groups_acl_by_id(api): endpoint_result =", "print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string'", "coding: utf-8 -*- \"\"\"IdentityServicesEngineAPI security_groups_acls API fixtures and tests. Copyright", "does not match') def is_valid_get_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return", "ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls def", "pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def update_security_groups_acl_by_id_default(api): endpoint_result =", "endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl(api)", "endpoint_result = api.security_groups_acls.get_security_groups_acl( filter='value1,value2', filter_type='string', page=0, size=0, sortasc='string', sortdsc='string' )", "validator, get_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest,", "def delete_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls", "True def get_security_groups_acl(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter='value1,value2', filter_type='string', page=0, size=0,", "to the following conditions: The above copyright notice and this", "conditions: The above copyright notice and this permission notice shall", "assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl(api) ) except Exception as original_e: with", "the Software without restriction, including without limitation the rights to", "Cisco and/or its affiliates. Permission is hereby granted, free of", "get_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR:", "THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj): if not obj: return False assert hasattr(obj,", "def test_bulk_request_for_security_groups_acl(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl(api) ) except", "raise original_e def update_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False, id='string', aclcontent=None,", "is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj): if not obj: return False assert hasattr(obj, 'headers')", "and/or sell copies of the Software, and to permit persons", "try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl_default(api) ) except Exception as original_e:", "permit persons to whom the Software is furnished to do", "with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_default(api): endpoint_result", "raise original_e def get_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter=None, filter_type=None, page=None,", "do so, subject to the following conditions: The above copyright", "payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl(api, validator): try: assert", "import ciscoisesdkException from tests.environment import IDENTITY_SERVICES_ENGINE_VERSION pytestmark = pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION !=", "!= '3.1.0', reason='version does not match') def is_valid_get_security_groups_acl_by_id(json_schema_validate, obj): if", "any person obtaining a copy of this software and associated", "is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "endpoint_result @pytest.mark.security_groups_acls def test_get_version(api, validator): try: assert is_valid_get_version( validator, get_version(api)", "as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_update_security_groups_acl_by_id(json_schema_validate,", "get_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR:", "'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return True def monitor_bulk_status_security_groups_acl(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string'", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "is_read_only=True, modelled_content={}, name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id(api,", "json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return True def create_security_groups_acl(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( aclcontent='string', active_validation=False,", "= api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def test_get_version(api, validator): try:", "test_bulk_request_for_security_groups_acl_default(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl_default(api) ) except Exception", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_default(api):", "raise original_e def is_valid_get_security_groups_acl(json_schema_validate, obj): if not obj: return False", "payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id_default(api, validator): try: assert", "try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl_default(api) ) except Exception as original_e:", "hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return True def get_security_groups_acl_by_id(api):", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def bulk_request_for_security_groups_acl_default(api):", "try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl(api) ) except Exception as original_e:", "False assert hasattr(obj, 'headers') assert hasattr(obj, 'content') assert hasattr(obj, 'text')", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return True def get_version(api): endpoint_result = api.security_groups_acls.get_version( )", "hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return True def create_security_groups_acl(api):", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id(api, validator): try:", "json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return True def update_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string', active_validation=False,", "return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator,", "= api.security_groups_acls.create_security_groups_acl( aclcontent='string', active_validation=False, description='string', generation_id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string',", "copy of this software and associated documentation files (the \"Software\"),", "validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl_default(api) ) except Exception as", "'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return True", "test_monitor_bulk_status_security_groups_acl(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl(api) ) except Exception", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_get_security_groups_acl(json_schema_validate, obj):", "payload=None, resource_media_type=None ) return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl_default(api, validator): try:", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "TypeError)): raise original_e def is_valid_get_version(json_schema_validate, obj): if not obj: return", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_version_default(api):", "OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import pytest from", "original_e def bulk_request_for_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type=None, payload=None, resource_media_type=None", "including without limitation the rights to use, copy, modify, merge,", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl_default(api) ) except Exception as", "hasattr(obj, 'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return True def get_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id(", "MalformedRequest, TypeError)): raise original_e def is_valid_update_security_groups_acl_by_id(json_schema_validate, obj): if not obj:", "ciscoisesdk.exceptions import MalformedRequest from ciscoisesdk.exceptions import ciscoisesdkException from tests.environment import", ") return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_default(api, validator): try: assert is_valid_get_security_groups_acl(", "validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl(api) ) except Exception as", "assert is_valid_get_security_groups_acl( validator, get_security_groups_acl_default(api) ) except Exception as original_e: with", "json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return True def monitor_bulk_status_security_groups_acl(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' )", "try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id(api) ) except Exception as original_e:", "TypeError)): raise original_e def is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj): if not obj: return", "with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def bulk_request_for_security_groups_acl_default(api): endpoint_result", "'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return True", "def update_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string', active_validation=False, description='string', generation_id='string', id='string',", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "'text') assert hasattr(obj, 'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return True def create_security_groups_acl(api): endpoint_result", "validator, create_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest,", "@pytest.mark.security_groups_acls def test_get_version(api, validator): try: assert is_valid_get_version( validator, get_version(api) )", "api.security_groups_acls.get_security_groups_acl( filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None ) return endpoint_result", "original_e def is_valid_update_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert", "@pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id(api) )", "'text') assert hasattr(obj, 'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return True def get_security_groups_acl(api): endpoint_result", "test_create_security_groups_acl_default(api, validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl_default(api) ) except Exception", "api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id_default(api, validator): try:", "raise original_e def is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False", "without limitation the rights to use, copy, modify, merge, publish,", "try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl_default(api) ) except Exception as original_e:", "MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def delete_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id(", "get_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def", "delete_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR:", "= pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION != '3.1.0', reason='version does not match') def is_valid_get_security_groups_acl_by_id(json_schema_validate,", "update_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string', active_validation=False, description='string', generation_id='string', id='string', ip_version='string',", "filter_type=None, page=None, size=None, sortasc=None, sortdsc=None ) return endpoint_result @pytest.mark.security_groups_acls def", "api.security_groups_acls.get_security_groups_acl( filter='value1,value2', filter_type='string', page=0, size=0, sortasc='string', sortdsc='string' ) return endpoint_result", "restriction, including without limitation the rights to use, copy, modify,", "pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def delete_security_groups_acl_by_id_default(api): endpoint_result =", "is_valid_get_security_groups_acl( validator, get_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "assert hasattr(obj, 'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return True def get_version(api): endpoint_result =", "name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id(api, validator): try:", "is_read_only=None, modelled_content=None, name=None, payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl_default(api,", "hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return", "{error}\".format(error=original_e)) raise original_e def get_version_default(api): endpoint_result = api.security_groups_acls.get_version( ) return", "to permit persons to whom the Software is furnished to", "{error}\".format(error=original_e)) raise original_e def get_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter=None, filter_type=None,", "get_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None", "assert is_valid_create_security_groups_acl( validator, create_security_groups_acl_default(api) ) except Exception as original_e: with", "endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id(api)", "hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return", "assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return True def", "assert hasattr(obj, 'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return True def delete_security_groups_acl_by_id(api): endpoint_result =", "validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id_default(api) ) except Exception as", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id_default(api, validator): try: assert", "hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return True def bulk_request_for_security_groups_acl(api):", "as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def", "assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return True def", "bulk_request_for_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR:", "assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response)", "original_e def is_valid_get_security_groups_acl(json_schema_validate, obj): if not obj: return False assert", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "sortasc='string', sortdsc='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl(api, validator): try:", "deal in the Software without restriction, including without limitation the", "endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type=None, payload=None, resource_media_type=None ) return endpoint_result", "generation_id='string', id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None ) return endpoint_result", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def update_security_groups_acl_by_id_default(api):", "assert hasattr(obj, 'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return True def create_security_groups_acl(api): endpoint_result =", "api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False, id='string', aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None,", "raise original_e def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj): if not obj: return False", "@pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl(api) )", "ciscoisesdk.exceptions import ciscoisesdkException from tests.environment import IDENTITY_SERVICES_ENGINE_VERSION pytestmark = pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR", "def create_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( active_validation=False, aclcontent=None, description=None, generation_id=None, ip_version=None,", "pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_version_default(api): endpoint_result =", "is_valid_get_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert hasattr(obj, 'headers')", "return False assert hasattr(obj, 'headers') assert hasattr(obj, 'content') assert hasattr(obj,", "assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response)", "ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_create_security_groups_acl(json_schema_validate, obj): if not", "return True def bulk_request_for_security_groups_acl(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type='string', payload=None,", "distribute, sublicense, and/or sell copies of the Software, and to", "id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id(api, validator): try: assert", "aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None, payload=None ) return", "raise original_e def is_valid_get_version(json_schema_validate, obj): if not obj: return False", "security_groups_acls API fixtures and tests. Copyright (c) 2021 Cisco and/or", "validator): try: assert is_valid_get_version( validator, get_version(api) ) except Exception as", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR", "MalformedRequest, TypeError)): raise original_e def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj): if not obj:", "'text') assert hasattr(obj, 'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return True def get_security_groups_acl_by_id(api): endpoint_result", "bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl_default(api, validator): try: assert", "assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl(api) ) except Exception as original_e: with", "True def get_version(api): endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls", "'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return True", "raise original_e def is_valid_update_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False", "validator, update_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)):", "validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl(api) ) except Exception as", "try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id(api) ) except Exception as original_e:", "# -*- coding: utf-8 -*- \"\"\"IdentityServicesEngineAPI security_groups_acls API fixtures and", "def test_get_security_groups_acl_default(api, validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl_default(api) ) except", "original_e def create_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( active_validation=False, aclcontent=None, description=None, generation_id=None,", "the Software, and to permit persons to whom the Software", "ciscoisesdkException from tests.environment import IDENTITY_SERVICES_ENGINE_VERSION pytestmark = pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION != '3.1.0',", "api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id(api, validator): try:", "update_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)):", "and associated documentation files (the \"Software\"), to deal in the", "raise original_e def delete_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return", "the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "to whom the Software is furnished to do so, subject", "validator, get_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)):", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "def test_get_version(api, validator): try: assert is_valid_get_version( validator, get_version(api) ) except", "resource_media_type='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl(api, validator): try: assert", "endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl_default(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl_default(api)", "except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise", "raise original_e def get_version_default(api): endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result", "{error}\".format(error=original_e)) raise original_e def delete_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' )", "= api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def test_get_version_default(api, validator): try:", "assert hasattr(obj, 'headers') assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert", "MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_version_default(api): endpoint_result = api.security_groups_acls.get_version(", "affiliates. Permission is hereby granted, free of charge, to any", "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT", "is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id(api)", "MalformedRequest, TypeError)): raise original_e def is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj): if not obj:", "TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return True def bulk_request_for_security_groups_acl(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False,", "assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response)", "from tests.environment import IDENTITY_SERVICES_ENGINE_VERSION pytestmark = pytest.mark.skipif(IDENTITY_SERVICES_ENGINE_VERSION != '3.1.0', reason='version", "of the Software, and to permit persons to whom the", "this software and associated documentation files (the \"Software\"), to deal", "-*- \"\"\"IdentityServicesEngineAPI security_groups_acls API fixtures and tests. Copyright (c) 2021", "all copies or substantial portions of the Software. THE SOFTWARE", "hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return", "test_get_version_default(api, validator): try: assert is_valid_get_version( validator, get_version_default(api) ) except Exception", "endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl(api,", "endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl(api, validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl(api)", "(the \"Software\"), to deal in the Software without restriction, including", "is_valid_create_security_groups_acl(json_schema_validate, obj): if not obj: return False assert hasattr(obj, 'headers')", "print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_version_default(api): endpoint_result = api.security_groups_acls.get_version( )", "and/or its affiliates. Permission is hereby granted, free of charge,", "merge, publish, distribute, sublicense, and/or sell copies of the Software,", ") return endpoint_result @pytest.mark.security_groups_acls def test_get_version_default(api, validator): try: assert is_valid_get_version(", "so, subject to the following conditions: The above copyright notice", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "MalformedRequest, TypeError)): raise original_e def is_valid_get_security_groups_acl(json_schema_validate, obj): if not obj:", "{error}\".format(error=original_e)) raise original_e def get_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' )", "charge, to any person obtaining a copy of this software", "to do so, subject to the following conditions: The above", "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl_default(api, validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl_default(api)", "following conditions: The above copyright notice and this permission notice", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_update_security_groups_acl_by_id(json_schema_validate, obj):", "return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_default(api, validator): try: assert is_valid_get_security_groups_acl( validator,", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return True def get_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' )", "@pytest.mark.security_groups_acls def test_get_security_groups_acl(api, validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl(api) )", "pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def bulk_request_for_security_groups_acl_default(api): endpoint_result =", "in the Software without restriction, including without limitation the rights", "permission notice shall be included in all copies or substantial", ") return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id(api, validator): try: assert is_valid_get_security_groups_acl_by_id(", "endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl(api, validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl(api)", "json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return True def get_version(api): endpoint_result = api.security_groups_acls.get_version( ) return", "modelled_content=None, name=None, payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl_default(api, validator):", "endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False, id='string', aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None,", "monitor_bulk_status_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR:", "endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id_default(api,", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_get_version(json_schema_validate, obj): if not", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "def test_get_version_default(api, validator): try: assert is_valid_get_version( validator, get_version_default(api) ) except", "endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type='string', payload=None, resource_media_type='string' ) return endpoint_result", "{error}\".format(error=original_e)) raise original_e def monitor_bulk_status_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' )", "original_e def delete_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result", "return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator,", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS", "is_valid_get_version( validator, get_version(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "original_e def is_valid_get_version(json_schema_validate, obj): if not obj: return False assert", "generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None, payload=None ) return endpoint_result @pytest.mark.security_groups_acls", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "= api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl(api, validator):", "get_version(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR:", "description='string', generation_id='string', id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None ) return", "'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return True", "copyright notice and this permission notice shall be included in", "= api.security_groups_acls.get_security_groups_acl( filter='value1,value2', filter_type='string', page=0, size=0, sortasc='string', sortdsc='string' ) return", "ip_version=None, is_read_only=None, modelled_content=None, name=None, payload=None ) return endpoint_result @pytest.mark.security_groups_acls def", "= api.security_groups_acls.get_security_groups_acl( filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None ) return", "return True def create_security_groups_acl(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( aclcontent='string', active_validation=False, description='string',", "return True def delete_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return", "assert is_valid_get_version( validator, get_version(api) ) except Exception as original_e: with", "get_version_default(api): endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def test_get_version_default(api,", "raise original_e def is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj): if not obj: return False", "is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj):", "MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def create_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.create_security_groups_acl(", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"", "validator, get_version_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest,", "@pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id_default(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id_default(api) )", "payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id(api, validator): try: assert", "fastjsonschema.exceptions import JsonSchemaException from ciscoisesdk.exceptions import MalformedRequest from ciscoisesdk.exceptions import", "api.security_groups_acls.create_security_groups_acl( active_validation=False, aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None, payload=None", "and to permit persons to whom the Software is furnished", "bulk_request_for_security_groups_acl(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type='string', payload=None, resource_media_type='string' ) return", "def test_delete_security_groups_acl_by_id_default(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id_default(api) ) except", "copies or substantial portions of the Software. THE SOFTWARE IS", "return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator,", "OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "{error}\".format(error=original_e)) raise original_e def bulk_request_for_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type=None,", "active_validation=False, aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None, payload=None )", "filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None ) return endpoint_result @pytest.mark.security_groups_acls", "aclcontent='string', active_validation=False, description='string', generation_id='string', id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None", "assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response)", "(c) 2021 Cisco and/or its affiliates. Permission is hereby granted,", "def monitor_bulk_status_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls", "@pytest.mark.security_groups_acls def test_get_version_default(api, validator): try: assert is_valid_get_version( validator, get_version_default(api) )", "assert hasattr(obj, 'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return True def monitor_bulk_status_security_groups_acl(api): endpoint_result =", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "def is_valid_update_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert hasattr(obj,", "def get_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter=None, filter_type=None, page=None, size=None, sortasc=None,", "@pytest.mark.security_groups_acls def test_get_security_groups_acl_default(api, validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl_default(api) )", "delete_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)):", "from ciscoisesdk.exceptions import ciscoisesdkException from tests.environment import IDENTITY_SERVICES_ENGINE_VERSION pytestmark =", "Copyright (c) 2021 Cisco and/or its affiliates. Permission is hereby", "whom the Software is furnished to do so, subject to", "assert hasattr(obj, 'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return True def bulk_request_for_security_groups_acl(api): endpoint_result =", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def delete_security_groups_acl_by_id_default(api):", "api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id_default(api, validator): try:", "MalformedRequest, TypeError)): raise original_e def is_valid_create_security_groups_acl(json_schema_validate, obj): if not obj:", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "is_read_only=None, modelled_content=None, name=None, payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id_default(api,", "hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return", "assert is_valid_create_security_groups_acl( validator, create_security_groups_acl(api) ) except Exception as original_e: with", "hasattr(obj, 'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return True def get_version(api): endpoint_result = api.security_groups_acls.get_version(", "endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl(api)", "= api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id(api, validator):", "in all copies or substantial portions of the Software. THE", "delete_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def", "obtaining a copy of this software and associated documentation files", "validator, bulk_request_for_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest,", "assert hasattr(obj, 'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return True def get_security_groups_acl(api): endpoint_result =", "def test_monitor_bulk_status_security_groups_acl(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl(api) ) except", "try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id_default(api) ) except Exception as original_e:", "api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def test_get_version(api, validator): try: assert", "is_valid_update_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert hasattr(obj, 'headers')", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "def test_delete_security_groups_acl_by_id(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id(api) ) except", "validator, get_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest,", "assert is_valid_get_security_groups_acl( validator, get_security_groups_acl(api) ) except Exception as original_e: with", "= api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string', active_validation=False, description='string', generation_id='string', id='string', ip_version='string', is_read_only=True, modelled_content={},", "'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return True", "json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return True def delete_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' )", "test_get_security_groups_acl_by_id(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id(api) ) except Exception", "of this software and associated documentation files (the \"Software\"), to", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "a copy of this software and associated documentation files (the", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "not obj: return False assert hasattr(obj, 'headers') assert hasattr(obj, 'content')", "active_validation=False, description='string', generation_id='string', id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None )", "hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return True def delete_security_groups_acl_by_id(api):", "return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator,", "create_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR:", "filter_type='string', page=0, size=0, sortasc='string', sortdsc='string' ) return endpoint_result @pytest.mark.security_groups_acls def", "test_update_security_groups_acl_by_id(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id(api) ) except Exception", "size=None, sortasc=None, sortdsc=None ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_default(api, validator):", "sublicense, and/or sell copies of the Software, and to permit", "return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id_default(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator,", "raise original_e def monitor_bulk_status_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return", "is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "def bulk_request_for_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type=None, payload=None, resource_media_type=None )", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR", "assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response)", "validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id(api) ) except Exception as", "= api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False, id='string', aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None,", "validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id_default(api) ) except Exception as", "return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id_default(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator,", "import JsonSchemaException from ciscoisesdk.exceptions import MalformedRequest from ciscoisesdk.exceptions import ciscoisesdkException", "is_valid_create_security_groups_acl( validator, create_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "def is_valid_create_security_groups_acl(json_schema_validate, obj): if not obj: return False assert hasattr(obj,", "def test_bulk_request_for_security_groups_acl_default(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl_default(api) ) except", "original_e def is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert", "pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj): if not", "is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "is_valid_get_version( validator, get_version_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return True def update_security_groups_acl_by_id(api):", "description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None, payload=None ) return endpoint_result", "test_get_security_groups_acl_by_id_default(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id_default(api) ) except Exception", "MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def update_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id(", "this permission notice shall be included in all copies or", "with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def delete_security_groups_acl_by_id_default(api): endpoint_result", "api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type='string', payload=None, resource_media_type='string' ) return endpoint_result @pytest.mark.security_groups_acls def", "def monitor_bulk_status_security_groups_acl(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "'text') assert hasattr(obj, 'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return True def bulk_request_for_security_groups_acl(api): endpoint_result", "validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl_default(api) ) except Exception as", "try: assert is_valid_get_version( validator, get_version_default(api) ) except Exception as original_e:", "try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl(api) ) except Exception as original_e:", "above copyright notice and this permission notice shall be included", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "delete_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def", "assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return True def", "hasattr(obj, 'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return True def update_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id(", "assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id_default(api) ) except Exception as original_e: with", "assert hasattr(obj, 'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return True def get_security_groups_acl_by_id(api): endpoint_result =", "json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return True def get_security_groups_acl(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter='value1,value2', filter_type='string',", "def test_create_security_groups_acl(api, validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl(api) ) except", "def is_valid_get_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert hasattr(obj,", "def delete_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls", "endpoint_result = api.security_groups_acls.get_security_groups_acl( filter=None, filter_type=None, page=None, size=None, sortasc=None, sortdsc=None )", "and tests. Copyright (c) 2021 Cisco and/or its affiliates. Permission", "@pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id_default(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id_default(api) )", "update_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False, id='string', aclcontent=None, description=None, generation_id=None, ip_version=None,", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,", "def bulk_request_for_security_groups_acl(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type='string', payload=None, resource_media_type='string' )", "API fixtures and tests. Copyright (c) 2021 Cisco and/or its", "validator, monitor_bulk_status_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest,", "'3.1.0', reason='version does not match') def is_valid_get_security_groups_acl_by_id(json_schema_validate, obj): if not", "print(\"ERROR: {error}\".format(error=original_e)) raise original_e def bulk_request_for_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False,", "as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate,", "with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def monitor_bulk_status_security_groups_acl_default(api): endpoint_result", "endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id(api,", "return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl_default(api, validator): try: assert is_valid_create_security_groups_acl( validator,", "assert is_valid_get_version( validator, get_version_default(api) ) except Exception as original_e: with", "def get_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING", "= api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id_default(api, validator):", "KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "is furnished to do so, subject to the following conditions:", "validator, get_version(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)):", "create_security_groups_acl(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( aclcontent='string', active_validation=False, description='string', generation_id='string', ip_version='string', is_read_only=True,", "pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj): if not", "assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response)", "True def update_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string', active_validation=False, description='string', generation_id='string',", "True def bulk_request_for_security_groups_acl(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type='string', payload=None, resource_media_type='string'", "from ciscoisesdk.exceptions import MalformedRequest from ciscoisesdk.exceptions import ciscoisesdkException from tests.environment", "def get_version(api): endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def", "to any person obtaining a copy of this software and", "with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_version_default(api): endpoint_result", "name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl(api, validator): try:", "def test_get_security_groups_acl_by_id_default(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id_default(api) ) except", "modelled_content={}, name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl(api, validator):", "api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl_default(api, validator): try:", "return endpoint_result @pytest.mark.security_groups_acls def test_get_version_default(api, validator): try: assert is_valid_get_version( validator,", "return True def get_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return", "shall be included in all copies or substantial portions of", "person obtaining a copy of this software and associated documentation", "FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string', active_validation=False, description='string', generation_id='string', id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string',", "THE SOFTWARE. \"\"\" import pytest from fastjsonschema.exceptions import JsonSchemaException from", "with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_get_version(json_schema_validate, obj): if", "tests. Copyright (c) 2021 Cisco and/or its affiliates. Permission is", "and this permission notice shall be included in all copies", "with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_by_id_default(api): endpoint_result", "id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id(api, validator): try: assert", "validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id_default(api) ) except Exception as", "utf-8 -*- \"\"\"IdentityServicesEngineAPI security_groups_acls API fixtures and tests. Copyright (c)", "endpoint_result = api.security_groups_acls.get_version( ) return endpoint_result @pytest.mark.security_groups_acls def test_get_version_default(api, validator):", "Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e", "is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return True def create_security_groups_acl(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( aclcontent='string',", "validator): try: assert is_valid_get_version( validator, get_version_default(api) ) except Exception as", "def is_valid_get_version(json_schema_validate, obj): if not obj: return False assert hasattr(obj,", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT", "def update_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False, id='string', aclcontent=None, description=None, generation_id=None,", "api.security_groups_acls.create_security_groups_acl( aclcontent='string', active_validation=False, description='string', generation_id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None", ") return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl(api, validator): try: assert is_valid_get_security_groups_acl(", "= api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl_default(api, validator):", "original_e def is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj): if not obj: return False assert", "original_e def get_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl( filter=None, filter_type=None, page=None, size=None,", "payload=None, resource_media_type='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl(api, validator): try:", "return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl_default(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator,", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def monitor_bulk_status_security_groups_acl_default(api):", "return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl_default(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator,", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", ") return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id_default(api, validator): try: assert is_valid_delete_security_groups_acl_by_id(", "pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def monitor_bulk_status_security_groups_acl_default(api): endpoint_result =", "free of charge, to any person obtaining a copy of", "def is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert hasattr(obj,", "True def create_security_groups_acl(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( aclcontent='string', active_validation=False, description='string', generation_id='string',", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "test_bulk_request_for_security_groups_acl(api, validator): try: assert is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl(api) ) except Exception", "assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id(api) ) except Exception as original_e: with", "id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None ) return endpoint_result @pytest.mark.security_groups_acls", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def get_security_groups_acl_by_id_default(api): endpoint_result =", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id_default(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator,", "the Software is furnished to do so, subject to the", "Software, and to permit persons to whom the Software is", "def test_get_security_groups_acl_by_id(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id(api) ) except", "reason='version does not match') def is_valid_get_security_groups_acl_by_id(json_schema_validate, obj): if not obj:", "get_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)):", "resource_media_type=None ) return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl_default(api, validator): try: assert", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "hasattr(obj, 'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return True def monitor_bulk_status_security_groups_acl(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl(", "True def monitor_bulk_status_security_groups_acl(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result", "hasattr(obj, 'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return True def create_security_groups_acl(api): endpoint_result = api.security_groups_acls.create_security_groups_acl(", "endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id(api,", "is_valid_get_security_groups_acl( validator, get_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "match') def is_valid_get_security_groups_acl_by_id(json_schema_validate, obj): if not obj: return False assert", "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or", "validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id(api) ) except Exception as", "active_validation=False, id='string', aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None, name=None, payload=None", "bulk_request_for_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type=None, payload=None, resource_media_type=None ) return", "MalformedRequest, TypeError)): raise original_e def is_valid_delete_security_groups_acl_by_id(json_schema_validate, obj): if not obj:", "print(\"ERROR: {error}\".format(error=original_e)) raise original_e def create_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( active_validation=False,", "documentation files (the \"Software\"), to deal in the Software without", "sortdsc=None ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_default(api, validator): try: assert", "monitor_bulk_status_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.monitor_bulk_status_security_groups_acl( bulkid='string' ) return endpoint_result @pytest.mark.security_groups_acls def", "hasattr(obj, 'response') json_schema_validate('jsd_b0a2bea8bfec52b68663ef3f7ac6d7a7_v3_1_0').validate(obj.response) return True def delete_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id(", "with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_get_security_groups_acl(json_schema_validate, obj): if", "hasattr(obj, 'headers') assert hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj,", "with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj): if", "without restriction, including without limitation the rights to use, copy,", "aclcontent='string', active_validation=False, description='string', generation_id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None )", "def test_update_security_groups_acl_by_id(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id(api) ) except", "active_validation=False, description='string', generation_id='string', ip_version='string', is_read_only=True, modelled_content={}, name='string', payload=None ) return", "try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl_default(api) ) except Exception as original_e:", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id(api)", "'response') json_schema_validate('jsd_a50d1bd34d5f593aadf8eb02083c67b0_v3_1_0').validate(obj.response) return True def get_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string'", "get_security_groups_acl_by_id_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)):", ") return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id_default(api, validator): try: assert is_valid_update_security_groups_acl_by_id(", "TypeError)): raise original_e def is_valid_get_security_groups_acl(json_schema_validate, obj): if not obj: return", "hasattr(obj, 'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return True def bulk_request_for_security_groups_acl(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl(", "= api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id_default(api, validator):", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id(api) ) except Exception as", "endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id_default(api, validator): try: assert is_valid_delete_security_groups_acl_by_id( validator, delete_security_groups_acl_by_id_default(api)", "assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_9ab61f24bdaf508590f7686e1130913f_v3_1_0').validate(obj.response) return True def", "hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_7da250e23ac05e6a8dcf32a81effcee9_v3_1_0').validate(obj.response) return", ") return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id_default(api, validator): try: assert is_valid_get_security_groups_acl_by_id(", "TypeError)): raise original_e def is_valid_monitor_bulk_status_security_groups_acl(json_schema_validate, obj): if not obj: return", "def test_create_security_groups_acl_default(api, validator): try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl_default(api) ) except", "original_e def get_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def bulk_request_for_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.bulk_request_for_security_groups_acl(", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies", "def test_get_security_groups_acl(api, validator): try: assert is_valid_get_security_groups_acl( validator, get_security_groups_acl(api) ) except", "hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return True def monitor_bulk_status_security_groups_acl(api):", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "MalformedRequest from ciscoisesdk.exceptions import ciscoisesdkException from tests.environment import IDENTITY_SERVICES_ENGINE_VERSION pytestmark", "is_valid_get_security_groups_acl(json_schema_validate, obj): if not obj: return False assert hasattr(obj, 'headers')", "bulk_request_for_security_groups_acl_default(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)):", "@pytest.mark.security_groups_acls def test_get_security_groups_acl_by_id_default(api, validator): try: assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id_default(api) )", "granted, free of charge, to any person obtaining a copy", "validator, delete_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)):", "is_valid_bulk_request_for_security_groups_acl( validator, bulk_request_for_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException,", "2021 Cisco and/or its affiliates. Permission is hereby granted, free", "assert is_valid_get_security_groups_acl_by_id( validator, get_security_groups_acl_by_id_default(api) ) except Exception as original_e: with", "id='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_delete_security_groups_acl_by_id_default(api, validator): try: assert", "active_validation=False, operation_type='string', payload=None, resource_media_type='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl(api,", "def test_update_security_groups_acl_by_id_default(api, validator): try: assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id_default(api) ) except", "validator, bulk_request_for_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)):", "assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return True def", "of charge, to any person obtaining a copy of this", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_999b22d6ad9f595ab7e3eee5cf44de8a_v3_1_0').validate(obj.response) return True def get_security_groups_acl(api):", "hasattr(obj, 'content') assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_07af5ee576605a5a915d888924c1e804_v3_1_0').validate(obj.response) return", "endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl_default(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl_default(api)", "Permission is hereby granted, free of charge, to any person", "def is_valid_bulk_request_for_security_groups_acl(json_schema_validate, obj): if not obj: return False assert hasattr(obj,", "assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl_default(api) ) except Exception as original_e: with", "OTHER DEALINGS IN THE SOFTWARE. \"\"\" import pytest from fastjsonschema.exceptions", "TypeError)): raise original_e def is_valid_create_security_groups_acl(json_schema_validate, obj): if not obj: return", "return True def update_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string', active_validation=False, description='string',", "raise original_e def is_valid_create_security_groups_acl(json_schema_validate, obj): if not obj: return False", "The above copyright notice and this permission notice shall be", "assert is_valid_update_security_groups_acl_by_id( validator, update_security_groups_acl_by_id(api) ) except Exception as original_e: with", "with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_create_security_groups_acl(json_schema_validate, obj): if", "print(\"ERROR: {error}\".format(error=original_e)) raise original_e def update_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( active_validation=False,", "sortdsc='string' ) return endpoint_result @pytest.mark.security_groups_acls def test_get_security_groups_acl(api, validator): try: assert", "payload=None ) return endpoint_result @pytest.mark.security_groups_acls def test_create_security_groups_acl_default(api, validator): try: assert", ") return endpoint_result @pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl_default(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl(", "original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR: {error}\".format(error=original_e)) raise original_e def create_security_groups_acl_default(api):", "validator, monitor_bulk_status_security_groups_acl(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)):", "'response') json_schema_validate('jsd_afc81cd1e25c50319f75606b97c23b3d_v3_1_0').validate(obj.response) return True def update_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.update_security_groups_acl_by_id( aclcontent='string',", "print(\"ERROR: {error}\".format(error=original_e)) raise original_e def delete_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.delete_security_groups_acl_by_id( id='string'", "= api.security_groups_acls.bulk_request_for_security_groups_acl( active_validation=False, operation_type='string', payload=None, resource_media_type='string' ) return endpoint_result @pytest.mark.security_groups_acls", "test_get_version(api, validator): try: assert is_valid_get_version( validator, get_version(api) ) except Exception", "raise original_e def create_security_groups_acl_default(api): endpoint_result = api.security_groups_acls.create_security_groups_acl( active_validation=False, aclcontent=None, description=None,", ") return endpoint_result @pytest.mark.security_groups_acls def test_update_security_groups_acl_by_id(api, validator): try: assert is_valid_update_security_groups_acl_by_id(", "def is_valid_get_security_groups_acl(json_schema_validate, obj): if not obj: return False assert hasattr(obj,", "hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return True def get_version(api):", "associated documentation files (the \"Software\"), to deal in the Software", "original_e def is_valid_create_security_groups_acl(json_schema_validate, obj): if not obj: return False assert", "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "try: assert is_valid_create_security_groups_acl( validator, create_security_groups_acl(api) ) except Exception as original_e:", "as original_e: with pytest.raises((JsonSchemaException, MalformedRequest, TypeError)): raise original_e def is_valid_get_version(json_schema_validate,", "operation_type=None, payload=None, resource_media_type=None ) return endpoint_result @pytest.mark.security_groups_acls def test_bulk_request_for_security_groups_acl_default(api, validator):", "update_security_groups_acl_by_id(api) ) except Exception as original_e: with pytest.raises((JsonSchemaException, MalformedRequest)): print(\"ERROR:", "@pytest.mark.security_groups_acls def test_monitor_bulk_status_security_groups_acl_default(api, validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl_default(api) )", "assert hasattr(obj, 'text') assert hasattr(obj, 'response') json_schema_validate('jsd_6704e67a1131578aa794d8377da9a1de_v3_1_0').validate(obj.response) return True def", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "def get_security_groups_acl_by_id(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls", "get_security_groups_acl_by_id_default(api): endpoint_result = api.security_groups_acls.get_security_groups_acl_by_id( id='string' ) return endpoint_result @pytest.mark.security_groups_acls def", "validator): try: assert is_valid_monitor_bulk_status_security_groups_acl( validator, monitor_bulk_status_security_groups_acl_default(api) ) except Exception as", "endpoint_result = api.security_groups_acls.create_security_groups_acl( active_validation=False, aclcontent=None, description=None, generation_id=None, ip_version=None, is_read_only=None, modelled_content=None,", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING" ]
[ "is None: raise ValueError('Specify an end point or an initial", "---------- initial_point : array-like, shape=[n_samples, dimension] end_point : array-like, shape=[n_samples,", "path def squared_dist(self, point_a, point_b): \"\"\"Squared geodesic distance between two", "for i in range(n_points - 1): dist_to_neighbors = self.dist(points[i, :],", "dimension] or shape=[1, dimension] Returns ------- inner_product : array-like, shape=[n_samples,]", "aux = gs.squeeze(aux, axis=0) einsum_str_b = 'k,nk->n' elif n_tangent_vec_b ==", "dimension > 0 super().__init__(dimension=dimension) self.signature = signature def inner_product_matrix(self, base_point=None):", "a function parameterizing the geodesic. Parameters ---------- t : parameter", "return variance def mean(self, points, weights=None, n_max_iterations=32, epsilon=EPSILON, point_type='vector', mean_method='default',", "gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat) n_auxs, _ = gs.shape(aux) if n_tangent_vec_b !=", "end_point is None and initial_tangent_vec is None: raise ValueError('Specify an", "= gs.to_ndarray(mean, to_ndim=2) if point_type == 'matrix': mean = gs.to_ndarray(mean,", "1], optional verbose : bool, optional Returns ------- mean :", "m, v, sq), loop_vars=[iteration, mean, variance, sq_dist], maximum_iterations=n_max_iterations) if last_iteration", "variance = gs.array([[0.]]) last_iteration, mean, variance, sq_dist = gs.while_loop( lambda", "expressed as the squared geodesic distance between the prediction and", "gs.to_ndarray(variance, to_ndim=2, axis=1) return variance def mean(self, points, weights=None, n_max_iterations=32,", "'nk,nk->n' inner_prod = gs.einsum(einsum_str_b, aux, tangent_vec_b) inner_prod = gs.to_ndarray(inner_prod, to_ndim=2,", "Parameters ---------- initial_point : array-like, shape=[n_samples, dimension] end_point : array-like,", "TODO(Xavier): This function assumes that all points are lists #", "gs.einsum('il,nkm->ikm', t, new_initial_tangent_vec) point_at_time_t = self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point) return point_at_time_t return", "n_tangent_vec_b == 1: tangent_vec_b = gs.squeeze(tangent_vec_b, axis=0) einsum_str_b = 'nk,k->n'", "return grad class RiemannianMetric(Connection): \"\"\"Class for Riemannian and pseudo-Riemannian metrics.\"\"\"", "= - 2. * tangent_vec inner_prod_mat = metric.inner_product_matrix(base_point=y_pred) grad =", "gs.array([[0.]]) last_iteration, mean, variance, sq_dist = gs.while_loop( lambda i, m,", "if n_auxs == 1: aux = gs.squeeze(aux, axis=0) einsum_str_b =", "code to study performance, # i.e. what to do with", "dist def variance(self, points, weights=None, base_point=None, point_type='vector'): \"\"\"Variance of (weighted)", "point_type == 'matrix': points = gs.to_ndarray(points, to_ndim=3) n_points = gs.shape(points)[0]", "return cometric_matrix def inner_product_derivative_matrix(self, base_point=None): \"\"\"Compute derivative of the inner", "array-like, shape=[n_samples, dimension], optional initial_tangent_vec : array-like, shape=[n_samples, dimension], optional", "tangent mean at x) rather than the mean-square-distance (MSD) because", ": array-like, shape=[n_samples, dimension] Returns ------- norm : array-like, shape=[n_samples,]", "that all points are lists # of vectors and not", "base_point: array-like, shape=[n_samples, dimension] or shape=[1, dimension] Returns ------- inner_product", "1: tangent_vec_b = gs.squeeze(tangent_vec_b, axis=0) einsum_str_b = 'nk,k->n' else: raise", "return [iteration, mean, variance, sq_dist] if point_type == 'vector': points", "is None: weights = gs.ones((n_points, 1)) weights = gs.array(weights) weights", "closest_neighbor_index(self, point, neighbors): \"\"\"Closest neighbor of point among neighbors. Parameters", "* current_tangent_mean, to_ndim=2) next_mean = self.exp( tangent_vec=shooting_vector, base_point=current_mean) logs =", "autograd.jacobian(self.inner_product_matrix) return metric_derivative(base_point) def christoffels(self, base_point): \"\"\"Compute Christoffel symbols associated", "term_3 = - gs.einsum('nim,nklm->nikl', cometric_mat_at_point, metric_derivative_at_point) christoffels = 0.5 *", "term_2 = gs.einsum('nim,nmlk->nilk', cometric_mat_at_point, metric_derivative_at_point) term_3 = - gs.einsum('nim,nklm->nikl', cometric_mat_at_point,", "point_type='vector'): \"\"\"Variance of (weighted) points wrt a base point. Parameters", "= gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) n_init = len(init_points)", "point_ndim = 2 initial_point = gs.to_ndarray(initial_point, to_ndim=point_ndim + 1) if", "as gs from geomstats.geometry.connection import Connection EPSILON = 1e-4 N_CENTERS", "neighbor of point among neighbors. Parameters ---------- point neighbors Returns", "array-like, shape=[n_samples, dimension, dimension, dimension] \"\"\" cometric_mat_at_point = self.inner_product_inverse_matrix(base_point) metric_derivative_at_point", "0 sq_dist = gs.array([[0.]]) variance = gs.array([[0.]]) last_iteration, mean, variance,", "reached. The ' 'mean may be inaccurate'.format(n_max_iterations)) return barycenter def", "this code to study performance, # i.e. what to do", "n_points = gs.shape(points)[0] if weights is None: weights = gs.ones((n_points,", "tangent_vec_a: array-like, shape=[n_samples, dimension] or shape=[1, dimension] tangent_vec_b: array-like, shape=[n_samples,", "\"norm_current_tangent_mean = {2}\".format( iter, tau, norm_current_tangent_mean)) if norm_next_tangent_mean < norm_current_tangent_mean:", "gs.to_ndarray(t, to_ndim=1) t = gs.to_ndarray(t, to_ndim=2, axis=1) new_initial_point = gs.to_ndarray(", "array-like, shape=[n_samples, 1], optional \"\"\" if point_type == 'vector': points", "points using adaptive time-steps The loss function optimized is ||M_1(x)||_x", "inner_product_derivative_matrix(self, base_point=None): \"\"\"Compute derivative of the inner prod matrix at", "< n_max_iterations): iteration = iteration + 1 shooting_vector = gs.to_ndarray(", ": array-like, shape=[n_samples, dimension] Returns ------- dist : array-like, shape=[n_samples,]", "is not None: end_point = gs.to_ndarray(end_point, to_ndim=point_ndim + 1) shooting_tangent_vec", "lambda i, m, v, sq: while_loop_body(i, m, v, sq), loop_vars=[iteration,", "tolerance for stopping the gradient descent verbose: verbose mode printing", "= math.inf barycenter = points.mean(0, keepdims=True) * 0 while convergence", "variance /= sum_weights variance = gs.to_ndarray(variance, to_ndim=1) variance = gs.to_ndarray(variance,", "points) variance += gs.einsum('nk,nj->j', weights, sq_dists) variance = gs.array(variance) variance", "= gs.sum(weights) n_init = len(init_points) if n_init == 0: current_mean", "mean_next = self.exp( tangent_vec=tangent_mean, base_point=mean) sq_dist = self.squared_dist(mean_next, mean) sq_dists_between_iterates.append(sq_dist)", "base_point) term_1 = gs.einsum('nim,nmkl->nikl', cometric_mat_at_point, metric_derivative_at_point) term_2 = gs.einsum('nim,nmlk->nilk', cometric_mat_at_point,", "def path(t): \"\"\"Generate a function parameterizing the geodesic. Parameters ----------", "base_point=None, point_type='vector'): \"\"\"Variance of (weighted) points wrt a base point.", "= gs.repeat(barycenter, points.shape[0], 0) grad_tangent = 2 * self.log(points, expand_barycenter)", "> epsilon and iteration < n_max_iterations): iteration = iteration +", "optional Returns ------- mean : array-like the Frechet mean of", "mean, variance, sq_dist], maximum_iterations=n_max_iterations) if last_iteration == n_max_iterations: print('Maximum number", "point neighbors Returns ------- closest_neighbor_index \"\"\" dist = self.dist(point, neighbors)", "norm(self, vector, base_point=None): \"\"\"Compute norm of a vector. Norm of", "is returned as a function parameterized by t. Parameters ----------", "* grad_tangent.sum(0, keepdims=True), barycenter) convergence = self.dist(cc_barycenter, barycenter).max().item() barycenter =", "= 1 if point_type == 'matrix': point_ndim = 2 initial_point", "2, inner_prod.shape return inner_prod def squared_norm(self, vector, base_point=None): \"\"\"Compute the", "function given by a Riemannian metric, expressed as the squared", "to_ndim=point_ndim + 1) shooting_tangent_vec = self.log(point=end_point, base_point=initial_point) if initial_tangent_vec is", "the two points that are farthest away from each other", "- 1): dist_to_neighbors = self.dist(points[i, :], points[i + 1:, :])", "is None: base_point = self.mean(points, weights) variance = 0. sq_dists", "t = gs.to_ndarray(t, to_ndim=2, axis=1) new_initial_point = gs.to_ndarray( initial_point, to_ndim=point_ndim", "if end_point is None and initial_tangent_vec is None: raise ValueError('Specify", "other in points. Parameters ---------- points Returns ------- diameter \"\"\"", "norm_current_tangent_mean = norm_next_tangent_mean tau = max(1.0, 1.0511111 * tau) else:", "shape=[n_samples, dimension] weights : array-like, shape=[n_samples, 1], optional verbose :", "shape=[1, dimension] tangent_vec_b: array-like, shape=[n_samples, dimension] or shape=[1, dimension] base_point:", "as the squared geodesic distance between the prediction and the", "== 'matrix': point_ndim = 2 initial_point = gs.to_ndarray(initial_point, to_ndim=point_ndim +", "= 2 initial_point = gs.to_ndarray(initial_point, to_ndim=point_ndim + 1) if end_point", "else: raise ValueError('Shape mismatch for einsum.') else: einsum_str_a = 'nj,njk->nk'", "self.inner_product_derivative_matrix( base_point) term_1 = gs.einsum('nim,nmkl->nikl', cometric_mat_at_point, metric_derivative_at_point) term_2 = gs.einsum('nim,nmlk->nilk',", "= metric.squared_dist(y_pred, y_true) return loss def grad(y_pred, y_true, metric): \"\"\"Closed-form", "gs.to_ndarray(tangent_vec_a, to_ndim=2) tangent_vec_b = gs.to_ndarray(tangent_vec_b, to_ndim=2) n_tangent_vec_a = gs.shape(tangent_vec_a)[0] n_tangent_vec_b", "dimension], optional \"\"\" raise NotImplementedError( 'The computation of the inner", "gs.shape(aux) if n_tangent_vec_b != n_auxs: if n_auxs == 1: aux", "elif n_tangent_vec_b == 1: tangent_vec_b = gs.squeeze(tangent_vec_b, axis=0) einsum_str_b =", "point and an end point. The geodesic is returned as", "shape=[n_samples, dimension] point_b : array-like, shape=[n_samples, dimension] Returns ------- dist", "iteration + 1 shooting_vector = gs.to_ndarray( tau * current_tangent_mean, to_ndim=2)", "if n_points == 1: return gs.to_ndarray(points[0], to_ndim=2) if weights is", "points.mean(0, keepdims=True) * 0 while convergence > tau and n_max_iterations", "+= gs.einsum('nk,nj->j', weights, sq_dists) variance = gs.array(variance) variance /= sum_weights", "of (weighted) points using adaptive time-steps. Frechet mean of (weighted)", "to the inner product at the tangent space at a", "gs.sum(weights) n_init = len(init_points) if n_init == 0: current_mean =", "dimension == math.inf assert dimension > 0 super().__init__(dimension=dimension) self.signature =", "base point. Parameters ---------- points: array-like, shape=[n_samples, dimension] weights: array-like,", "import geomstats.backend as gs from geomstats.geometry.connection import Connection EPSILON =", "gradient of the loss function.\"\"\" tangent_vec = metric.log(base_point=y_pred, point=y_true) grad_vec", "inner_product : array-like, shape=[n_samples,] \"\"\" tangent_vec_a = gs.to_ndarray(tangent_vec_a, to_ndim=2) tangent_vec_b", "points[0] else: current_mean = init_points[0] tau = 1.0 iteration =", "axes=(0, 2, 1))) return grad class RiemannianMetric(Connection): \"\"\"Class for Riemannian", "distance between the prediction and the ground truth. Parameters ----------", "shape=[n_samples, dimension] Returns ------- sq_dist : array-like, shape=[n_samples,] \"\"\" log", "tau = 5e-3 if len(points) == 1: return points iteration", "associated with the connection. Parameters ---------- base_point: array-like, shape=[n_samples, dimension]", "final dist: {}'.format( last_iteration, variance, sq_dist)) mean = gs.to_ndarray(mean, to_ndim=2)", "initial_tangent_vec) initial_tangent_vec = shooting_tangent_vec initial_tangent_vec = gs.array(initial_tangent_vec) initial_tangent_vec = gs.to_ndarray(initial_tangent_vec,", "array-like, shape=[n_samples, dimension], optional \"\"\" metric_derivative = autograd.jacobian(self.inner_product_matrix) return metric_derivative(base_point)", "n_max_iterations): iteration = iteration + 1 shooting_vector = gs.to_ndarray( tau", "(where M_1(x) is the tangent mean at x) rather than", "= gs.to_ndarray(points, to_ndim=2) if point_type == 'matrix': points = gs.to_ndarray(points,", "inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3) n_mats = gs.shape(inner_prod_mat)[0] if n_tangent_vec_a !=", "sum_weights = gs.sum(weights) if base_point is None: base_point = self.mean(points,", "= gs.to_ndarray(mean, to_ndim=3) if n_points == 1: return mean sq_dists_between_iterates", "norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean) while (norm_current_tangent_mean > epsilon and iteration <", "self.inner_product(vector, vector, base_point) return sq_norm def norm(self, vector, base_point=None): \"\"\"Compute", "return mean sq_dists_between_iterates = [] iteration = 0 sq_dist =", "mean_method == 'frechet-poincare-ball': lr = 1e-3 tau = 5e-3 if", "a base point. Parameters ---------- vector : array-like, shape=[n_samples, dimension]", "points that are farthest away from each other in points.", "\"\"\" tangent_vec_a = gs.to_ndarray(tangent_vec_a, to_ndim=2) tangent_vec_b = gs.to_ndarray(tangent_vec_b, to_ndim=2) n_tangent_vec_a", "base_point) return sq_norm def norm(self, vector, base_point=None): \"\"\"Compute norm of", "to_ndim=2) next_mean = self.exp( tangent_vec=shooting_vector, base_point=current_mean) logs = self.log(point=points, base_point=next_mean)", "return christoffels def inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None): \"\"\"Inner product between", "i in range(n_points - 1): dist_to_neighbors = self.dist(points[i, :], points[i", "base_point=mean_next) mean = mean_next iteration += 1 return [iteration, mean,", "return point_at_time_t return path def squared_dist(self, point_a, point_b): \"\"\"Squared geodesic", "dimension, signature=None): assert isinstance(dimension, int) or dimension == math.inf assert", "self.mean(points, weights) variance = 0. sq_dists = self.squared_dist(base_point, points) variance", "i, m, v, sq: while_loop_cond(i, m, v, sq), lambda i,", "product matrix at the tangent space at a base point.", "dimension] point_b : array-like, shape=[n_samples, dimension] Returns ------- dist :", "connection. Parameters ---------- base_point: array-like, shape=[n_samples, dimension] Returns ------- christoffels:", "self.exp( tangent_vec=tangent_mean, base_point=mean) sq_dist = self.squared_dist(mean_next, mean) sq_dists_between_iterates.append(sq_dist) variance =", "initial point and an end point. The geodesic is returned", "weights: array-like, shape=[n_samples, 1], optional \"\"\" if point_type == 'vector':", "points, weights=None, base_point=None, point_type='vector'): \"\"\"Variance of (weighted) points wrt a", "to_ndim=2) if point_type == 'matrix': points = gs.to_ndarray(points, to_ndim=3) n_points", "else: raise ValueError('Shape mismatch for einsum.') else: einsum_str_b = 'nk,nk->n'", "\" \"norm_current_tangent_mean = {2}\".format( iter, tau, norm_current_tangent_mean)) if norm_next_tangent_mean <", "= [] iteration = 0 sq_dist = gs.array([[0.]]) variance =", "\"\"\"Compute the square of the norm of a vector. Squared", "point_b): \"\"\"Geodesic distance between two points. Note: It only works", "sum_weights = gs.sum(weights) n_init = len(init_points) if n_init == 0:", "= self.squared_dist(point_a, point_b) dist = gs.sqrt(sq_dist) return dist def variance(self,", "0: current_mean = points[0] else: current_mean = init_points[0] tau =", "new_initial_point = gs.to_ndarray( initial_point, to_ndim=point_ndim + 1) new_initial_tangent_vec = gs.to_ndarray(", "base_point): \"\"\"Compute Christoffel symbols associated with the connection. Parameters ----------", "return gs.to_ndarray(current_mean, to_ndim=2) def diameter(self, points): \"\"\"Give the distance between", "n_tangent_vec_a != n_mats: if n_tangent_vec_a == 1: tangent_vec_a = gs.squeeze(tangent_vec_a,", "variance, sq_dist)) mean = gs.to_ndarray(mean, to_ndim=2) return mean if mean_method", "tangent_mean = gs.einsum('nk,nj->j', weights, logs) tangent_mean /= sum_weights mean_next =", "gs.squeeze(inner_prod_mat, axis=0) einsum_str_a = 'nj,jk->nk' else: raise ValueError('Shape mismatch for", "geodesic.') if end_point is not None: end_point = gs.to_ndarray(end_point, to_ndim=point_ndim", "= self.inner_product_matrix(base_point) cometric_matrix = gs.linalg.inv(metric_matrix) return cometric_matrix def inner_product_derivative_matrix(self, base_point=None):", "gs.cast(t, gs.float32) t = gs.to_ndarray(t, to_ndim=1) t = gs.to_ndarray(t, to_ndim=2,", "Norm of a vector associated to the inner product at", "' is not implemented.') def inner_product_inverse_matrix(self, base_point=None): \"\"\"Inner product matrix", "Returns ------- mean : array-like the Frechet mean of points,", "initial_tangent_vec, to_ndim=point_ndim + 1) if point_type == 'vector': tangent_vecs =", "gs.einsum('nim,nklm->nikl', cometric_mat_at_point, metric_derivative_at_point) christoffels = 0.5 * (term_1 + term_2", "of the inner product matrix' ' is not implemented.') def", "'Maximum number of iterations {} reached. The ' 'mean may", "point. Parameters ---------- points: array-like, shape=[n_samples, dimension] weights: array-like, shape=[n_samples,", "gs.to_ndarray(inner_prod_mat, to_ndim=3) n_mats = gs.shape(inner_prod_mat)[0] if n_tangent_vec_a != n_mats: if", "tau = 1.0 iteration = 0 logs = self.log(point=points, base_point=current_mean)", "= gs.einsum('il,nkm->ikm', t, new_initial_tangent_vec) point_at_time_t = self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point) return point_at_time_t", "self.log(points, expand_barycenter) cc_barycenter = self.exp(lr * grad_tangent.sum(0, keepdims=True), barycenter) convergence", "= 'k,nk->n' elif n_tangent_vec_b == 1: tangent_vec_b = gs.squeeze(tangent_vec_b, axis=0)", "gs.array(weights) weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) if", "sq_dists) variance = gs.array(variance) variance /= sum_weights variance = gs.to_ndarray(variance,", "self.variance(points=points, weights=weights, base_point=mean_next) mean = mean_next iteration += 1 return", "inaccurate'.format(n_max_iterations)) return barycenter def adaptive_gradientdescent_mean(self, points, weights=None, n_max_iterations=40, epsilon=1e-12, init_points=[],", "at x) rather than the mean-square-distance (MSD) because this saves", "= gs.einsum('nk,nj->j', weights, logs) current_tangent_mean /= sum_weights norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean)", "logs) tangent_mean /= sum_weights mean_next = self.exp( tangent_vec=tangent_mean, base_point=mean) sq_dist", "variance = gs.array(variance) variance /= sum_weights variance = gs.to_ndarray(variance, to_ndim=1)", "\"\"\"Closed-form for the gradient of the loss function.\"\"\" tangent_vec =", "base_point=next_mean) next_tangent_mean = gs.einsum('nk,nj->j', weights, logs) next_tangent_mean /= sum_weights norm_next_tangent_mean", "= gs.amax(dist_to_neighbors) diameter = gs.maximum(diameter, dist_to_farthest_neighbor) return diameter def closest_neighbor_index(self,", "metrics.\"\"\" def __init__(self, dimension, signature=None): assert isinstance(dimension, int) or dimension", "n_max_iterations > iteration: iteration += 1 expand_barycenter = gs.repeat(barycenter, points.shape[0],", "of a vector associated to the inner product at the", "if point_type == 'matrix': mean = gs.to_ndarray(mean, to_ndim=3) if n_points", "gs.einsum('nim,nmkl->nikl', cometric_mat_at_point, metric_derivative_at_point) term_2 = gs.einsum('nim,nmlk->nilk', cometric_mat_at_point, metric_derivative_at_point) term_3 =", "math.inf barycenter = points.mean(0, keepdims=True) * 0 while convergence >", "\"\"\"Class for Riemannian and pseudo-Riemannian metrics.\"\"\" def __init__(self, dimension, signature=None):", "(weighted) points wrt a base point. Parameters ---------- points: array-like,", "end_point=None, initial_tangent_vec=None, point_type='vector'): \"\"\"Return the geodesic as function of t.", "---------- points: array-like, shape=[n_samples, dimension] weights: array-like, shape=[n_samples, 1], optional", "truth. Parameters ---------- y_pred y_true metric Returns ------- loss \"\"\"", "base_point=None): \"\"\"Compute the square of the norm of a vector.", "base_point : array-like, shape=[n_samples, dimension], optional \"\"\" metric_derivative = autograd.jacobian(self.inner_product_matrix)", "next_mean = self.exp( tangent_vec=shooting_vector, base_point=current_mean) logs = self.log(point=points, base_point=next_mean) next_tangent_mean", "= points[0] else: current_mean = init_points[0] tau = 1.0 iteration", "= gs.maximum(diameter, dist_to_farthest_neighbor) return diameter def closest_neighbor_index(self, point, neighbors): \"\"\"Closest", "mean = gs.to_ndarray(mean, to_ndim=3) if n_points == 1: return mean", "shape=[n_samples, dimension] weights: array-like, shape=[n_samples, 1], optional \"\"\" if point_type", "between two points. Parameters ---------- point_a : array-like, shape=[n_samples, dimension]", "== 1: tangent_vec_a = gs.squeeze(tangent_vec_a, axis=0) einsum_str_a = 'j,njk->nk' elif", "for einsum.') else: einsum_str_a = 'nj,njk->nk' aux = gs.einsum(einsum_str_a, tangent_vec_a,", "gs from geomstats.geometry.connection import Connection EPSILON = 1e-4 N_CENTERS =", "shape=[n_samples, dimension] Returns ------- sq_norm : array-like, shape=[n_samples,] \"\"\" sq_norm", "base_point : array-like, shape=[n_samples, dimension], optional \"\"\" metric_matrix = self.inner_product_matrix(base_point)", "gs.less_equal(sq_dist, epsilon * variance)) return result[0, 0] or iteration ==", "epsilon: tolerance for stopping the gradient descent verbose: verbose mode", "def geodesic(self, initial_point, end_point=None, initial_tangent_vec=None, point_type='vector'): \"\"\"Return the geodesic as", "epsilon=EPSILON, point_type='vector', mean_method='default', verbose=False): \"\"\"Frechet mean of (weighted) points. Parameters", "assert gs.allclose(shooting_tangent_vec, initial_tangent_vec) initial_tangent_vec = shooting_tangent_vec initial_tangent_vec = gs.array(initial_tangent_vec) initial_tangent_vec", "point_a : array-like, shape=[n_samples, dimension] point_b : array-like, shape=[n_samples, dimension]", "of t. Geodesic curve defined by either: - an initial", "\"\"\"Variance of (weighted) points wrt a base point. Parameters ----------", "import warnings import autograd import geomstats.backend as gs from geomstats.geometry.connection", "christoffels(self, base_point): \"\"\"Compute Christoffel symbols associated with the connection. Parameters", "Returns ------- christoffels: array-like, shape=[n_samples, dimension, dimension, dimension] \"\"\" cometric_mat_at_point", "= self.log(point=end_point, base_point=initial_point) if initial_tangent_vec is not None: assert gs.allclose(shooting_tangent_vec,", "= iteration + 1 shooting_vector = gs.to_ndarray( tau * current_tangent_mean,", ": array-like, shape=[n_samples, dimension], optional initial_tangent_vec : array-like, shape=[n_samples, dimension],", "Connection EPSILON = 1e-4 N_CENTERS = 10 TOLERANCE = 1e-5", "\"\"\"Compute Christoffel symbols associated with the connection. Parameters ---------- base_point:", "iter, tau, norm_current_tangent_mean)) if norm_next_tangent_mean < norm_current_tangent_mean: current_mean = next_mean", "are lists # of vectors and not of matrices n_points", "\"\"\"Compute norm of a vector. Norm of a vector associated", "* variance)) return result[0, 0] or iteration == 0 def", "tangent_vec_a = gs.squeeze(tangent_vec_a, axis=0) einsum_str_a = 'j,njk->nk' elif n_mats ==", ": array-like, shape=[n_samples, dimension], optional \"\"\" metric_matrix = self.inner_product_matrix(base_point) cometric_matrix", "using adaptive time-steps. Frechet mean of (weighted) points using adaptive", "shape=[n_init, dimension] epsilon: tolerance for stopping the gradient descent verbose:", "adaptive time-steps The loss function optimized is ||M_1(x)||_x (where M_1(x)", "if point_type == 'vector': points = gs.to_ndarray(points, to_ndim=2) if point_type", "dimension] point_b : array-like, shape=[n_samples, dimension] Returns ------- sq_dist :", "'mean may be inaccurate'.format(n_max_iterations)) return barycenter def adaptive_gradientdescent_mean(self, points, weights=None,", "between two tangent vectors at a base point. Parameters ----------", "Parameters ---------- base_point : array-like, shape=[n_samples, dimension], optional \"\"\" metric_derivative", "' 'vector to define the geodesic.') if end_point is not", "a Riemannian metric, expressed as the squared geodesic distance between", "\"\"\"Closest neighbor of point among neighbors. Parameters ---------- point neighbors", "shape=[n_samples, 1], optional \"\"\" if point_type == 'vector': points =", "v, sq), loop_vars=[iteration, mean, variance, sq_dist], maximum_iterations=n_max_iterations) if last_iteration ==", "== math.inf assert dimension > 0 super().__init__(dimension=dimension) self.signature = signature", "shape=[n_samples, 1], optional verbose : bool, optional Returns ------- mean", "of a vector. Squared norm of a vector associated to", "1], optional init_points: array-like, shape=[n_init, dimension] epsilon: tolerance for stopping", "gs.sqrt(sq_norm) return norm def geodesic(self, initial_point, end_point=None, initial_tangent_vec=None, point_type='vector'): \"\"\"Return", "axis=1) new_initial_point = gs.to_ndarray( initial_point, to_ndim=point_ndim + 1) new_initial_tangent_vec =", "ValueError('Shape mismatch for einsum.') else: einsum_str_b = 'nk,nk->n' inner_prod =", "tangent_mean /= sum_weights mean_next = self.exp( tangent_vec=tangent_mean, base_point=mean) sq_dist =", "array-like, shape=[n_samples,] \"\"\" sq_dist = self.squared_dist(point_a, point_b) dist = gs.sqrt(sq_dist)", "points.shape[0] for i in range(n_points - 1): dist_to_neighbors = self.dist(points[i,", "shape=[n_samples, dimension], optional initial_tangent_vec : array-like, shape=[n_samples, dimension], optional point_type", "'vector': tangent_vecs = gs.einsum('il,nk->ik', t, new_initial_tangent_vec) elif point_type == 'matrix':", "to_ndim=2) return mean if mean_method == 'frechet-poincare-ball': lr = 1e-3", "0 def while_loop_body(iteration, mean, variance, sq_dist): logs = self.log(point=points, base_point=mean)", "= gs.einsum(einsum_str_b, aux, tangent_vec_b) inner_prod = gs.to_ndarray(inner_prod, to_ndim=2, axis=1) assert", "iterations {} reached. The ' 'mean may be inaccurate'.format(n_max_iterations)) return", "positive definite Riemannian metrics. Parameters ---------- point_a : array-like, shape=[n_samples,", ": array-like, shape=[n_samples, dimension], optional \"\"\" metric_derivative = autograd.jacobian(self.inner_product_matrix) return", "'vector': mean = gs.to_ndarray(mean, to_ndim=2) if point_type == 'matrix': mean", "else: tau = tau * 0.8 if iteration == n_max_iterations:", "metric.inner_product_matrix(base_point=y_pred) grad = gs.einsum('ni,nij->ni', grad_vec, gs.transpose(inner_prod_mat, axes=(0, 2, 1))) return", "inner_prod def squared_norm(self, vector, base_point=None): \"\"\"Compute the square of the", "or dimension == math.inf assert dimension > 0 super().__init__(dimension=dimension) self.signature", "function assumes that all points are lists # of vectors", "base_point : array-like, shape=[n_samples, dimension], optional \"\"\" raise NotImplementedError( 'The", "geodesic Returns ------- point_at_time_t : callable \"\"\" t = gs.cast(t,", "to_ndim=2, axis=1) sum_weights = gs.sum(weights) if base_point is None: base_point", "a vector associated to the inner product at the tangent", "iterations {} reached.' 'The mean may be inaccurate'.format(n_max_iterations)) return gs.to_ndarray(current_mean,", "TOLERANCE = 1e-5 N_REPETITIONS = 20 N_MAX_ITERATIONS = 50000 N_STEPS", "gradient descent verbose: verbose mode printing the surrogate value epsilon:", "= self.log(point=points, base_point=next_mean) next_tangent_mean = gs.einsum('nk,nj->j', weights, logs) next_tangent_mean /=", "current_mean = next_mean current_tangent_mean = next_tangent_mean norm_current_tangent_mean = norm_next_tangent_mean tau", "self.log(point=point_b, base_point=point_a) sq_dist = self.squared_norm(vector=log, base_point=point_a) return sq_dist def dist(self,", "closest_neighbor_index \"\"\" dist = self.dist(point, neighbors) closest_neighbor_index = gs.argmin(dist) return", "among neighbors. Parameters ---------- point neighbors Returns ------- closest_neighbor_index \"\"\"", "of (weighted) points. Parameters ---------- points : array-like, shape=[n_samples, dimension]", "\"\"\" log = self.log(point=point_b, base_point=point_a) sq_dist = self.squared_norm(vector=log, base_point=point_a) return", "gs.sqrt(sq_dist) return dist def variance(self, points, weights=None, base_point=None, point_type='vector'): \"\"\"Variance", "Riemannian metrics and inner products. Parameters ---------- vector : array-like,", "1], optional \"\"\" if point_type == 'vector': points = gs.to_ndarray(points,", "lr = 1e-3 tau = 5e-3 if len(points) == 1:", "== n_max_iterations: warnings.warn( 'Maximum number of iterations {} reached. The", "gs.to_ndarray(current_mean, to_ndim=2) def diameter(self, points): \"\"\"Give the distance between two", "sum_weights norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean) if verbose: print( \"Iter {0}: tau=", "away from each other in points. Parameters ---------- points Returns", "as function of t. Geodesic curve defined by either: -", "\"\"\" point_ndim = 1 if point_type == 'matrix': point_ndim =", "initial_point, to_ndim=point_ndim + 1) new_initial_tangent_vec = gs.to_ndarray( initial_tangent_vec, to_ndim=point_ndim +", "this saves computation time. Parameters ---------- points: array-like, shape=[n_samples, dimension]", "sq_dist = gs.while_loop( lambda i, m, v, sq: while_loop_cond(i, m,", "weights: array-like, shape=[n_samples, 1], optional init_points: array-like, shape=[n_init, dimension] epsilon:", "optional \"\"\" metric_derivative = autograd.jacobian(self.inner_product_matrix) return metric_derivative(base_point) def christoffels(self, base_point):", "sq), lambda i, m, v, sq: while_loop_body(i, m, v, sq),", "grad_vec, gs.transpose(inner_prod_mat, axes=(0, 2, 1))) return grad class RiemannianMetric(Connection): \"\"\"Class", "tangent vectors at a base point. Parameters ---------- tangent_vec_a: array-like,", "return norm def geodesic(self, initial_point, end_point=None, initial_tangent_vec=None, point_type='vector'): \"\"\"Return the", "shape=[n_samples,] \"\"\" sq_norm = self.squared_norm(vector, base_point) norm = gs.sqrt(sq_norm) return", "are farthest away from each other in points. Parameters ----------", ": callable \"\"\" t = gs.cast(t, gs.float32) t = gs.to_ndarray(t,", "= self.log(point=point_b, base_point=point_a) sq_dist = self.squared_norm(vector=log, base_point=point_a) return sq_dist def", "elif n_mats == 1: inner_prod_mat = gs.squeeze(inner_prod_mat, axis=0) einsum_str_a =", "mean of (weighted) points using adaptive time-steps The loss function", "the inner product matrix' ' is not implemented.') def inner_product_inverse_matrix(self,", "if n_tangent_vec_a == 1: tangent_vec_a = gs.squeeze(tangent_vec_a, axis=0) einsum_str_a =", "an initial point and an initial tangent vector, or -", "saves computation time. Parameters ---------- points: array-like, shape=[n_samples, dimension] weights:", "dist_to_neighbors = self.dist(points[i, :], points[i + 1:, :]) dist_to_farthest_neighbor =", "array-like, shape=[n_samples, dimension] or shape=[1, dimension] base_point: array-like, shape=[n_samples, dimension]", "a base point. Parameters ---------- points: array-like, shape=[n_samples, dimension] weights:", "sq_dist = self.squared_norm(vector=log, base_point=point_a) return sq_dist def dist(self, point_a, point_b):", "\"\"\" # TODO(Xavier): This function assumes that all points are", "else: current_mean = init_points[0] tau = 1.0 iteration = 0", "points using adaptive time-steps. Frechet mean of (weighted) points using", "def inner_product_derivative_matrix(self, base_point=None): \"\"\"Compute derivative of the inner prod matrix", "def norm(self, vector, base_point=None): \"\"\"Compute norm of a vector. Norm", "= points.shape[0] for i in range(n_points - 1): dist_to_neighbors =", "self.squared_norm(vector, base_point) norm = gs.sqrt(sq_norm) return norm def geodesic(self, initial_point,", "= gs.squeeze(aux, axis=0) einsum_str_b = 'k,nk->n' elif n_tangent_vec_b == 1:", "point_at_time_t = self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point) return point_at_time_t return path def squared_dist(self,", "---------- tangent_vec_a: array-like, shape=[n_samples, dimension] or shape=[1, dimension] tangent_vec_b: array-like,", "init_points: array-like, shape=[n_init, dimension] epsilon: tolerance for stopping the gradient", "is ||M_1(x)||_x (where M_1(x) is the tangent mean at x)", ": array-like, shape=[n_samples,] \"\"\" tangent_vec_a = gs.to_ndarray(tangent_vec_a, to_ndim=2) tangent_vec_b =", "end_point : array-like, shape=[n_samples, dimension], optional initial_tangent_vec : array-like, shape=[n_samples,", "= self.exp( tangent_vec=shooting_vector, base_point=current_mean) logs = self.log(point=points, base_point=next_mean) next_tangent_mean =", "[iteration, mean, variance, sq_dist] if point_type == 'vector': points =", "neighbors Returns ------- closest_neighbor_index \"\"\" dist = self.dist(point, neighbors) closest_neighbor_index", "an initial tangent vector, or - an initial point and", "gs.sum(weights) mean = points[0] if point_type == 'vector': mean =", "gs.isclose(variance, 0.), gs.less_equal(sq_dist, epsilon * variance)) return result[0, 0] or", "= gs.to_ndarray( tau * current_tangent_mean, to_ndim=2) next_mean = self.exp( tangent_vec=shooting_vector,", "array-like the Frechet mean of points, a point on the", "the geodesic. Parameters ---------- t : parameter value of the", "iteration = 0 convergence = math.inf barycenter = points.mean(0, keepdims=True)", "and iteration < n_max_iterations): iteration = iteration + 1 shooting_vector", "* tangent_vec inner_prod_mat = metric.inner_product_matrix(base_point=y_pred) grad = gs.einsum('ni,nij->ni', grad_vec, gs.transpose(inner_prod_mat,", "return dist def variance(self, points, weights=None, base_point=None, point_type='vector'): \"\"\"Variance of", "v, sq: while_loop_body(i, m, v, sq), loop_vars=[iteration, mean, variance, sq_dist],", "points iteration = 0 convergence = math.inf barycenter = points.mean(0,", "prediction and the ground truth. Parameters ---------- y_pred y_true metric", "* 0.8 if iteration == n_max_iterations: warnings.warn( 'Maximum number of", "= {2}\".format( iter, tau, norm_current_tangent_mean)) if norm_next_tangent_mean < norm_current_tangent_mean: current_mean", "self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point) return point_at_time_t return path def squared_dist(self, point_a, point_b):", "space at a base point. Parameters ---------- base_point : array-like,", "\"\"\"Generate a function parameterizing the geodesic. Parameters ---------- t :", "\"\"\"Compute loss function between prediction and ground truth. Loss function", "Squared norm of a vector associated to the inner product", "isinstance(dimension, int) or dimension == math.inf assert dimension > 0", "t, new_initial_tangent_vec) elif point_type == 'matrix': tangent_vecs = gs.einsum('il,nkm->ikm', t,", "loss = metric.squared_dist(y_pred, y_true) return loss def grad(y_pred, y_true, metric):", "= 0.0 n_points = points.shape[0] for i in range(n_points -", "metric_matrix = self.inner_product_matrix(base_point) cometric_matrix = gs.linalg.inv(metric_matrix) return cometric_matrix def inner_product_derivative_matrix(self,", "logs = self.log(point=points, base_point=next_mean) next_tangent_mean = gs.einsum('nk,nj->j', weights, logs) next_tangent_mean", "m, v, sq: while_loop_cond(i, m, v, sq), lambda i, m,", "iteration = 0 logs = self.log(point=points, base_point=current_mean) current_tangent_mean = gs.einsum('nk,nj->j',", "neighbors): \"\"\"Closest neighbor of point among neighbors. Parameters ---------- point", "Returns ------- sq_norm : array-like, shape=[n_samples,] \"\"\" sq_norm = self.inner_product(vector,", "gs.float32) t = gs.to_ndarray(t, to_ndim=1) t = gs.to_ndarray(t, to_ndim=2, axis=1)", "gs.to_ndarray(inner_prod, to_ndim=2, axis=1) assert gs.ndim(inner_prod) == 2, inner_prod.shape return inner_prod", "diameter \"\"\" diameter = 0.0 n_points = points.shape[0] for i", "metric.log(base_point=y_pred, point=y_true) grad_vec = - 2. * tangent_vec inner_prod_mat =", "||M_1(x)||_x (where M_1(x) is the tangent mean at x) rather", "return path def squared_dist(self, point_a, point_b): \"\"\"Squared geodesic distance between", "inner_prod_mat = gs.squeeze(inner_prod_mat, axis=0) einsum_str_a = 'nj,jk->nk' else: raise ValueError('Shape", "'The computation of the inner product matrix' ' is not", "in range(n_points - 1): dist_to_neighbors = self.dist(points[i, :], points[i +", "{} reached.' 'The mean may be inaccurate'.format(n_max_iterations)) if verbose: print('n_iter:", "points): \"\"\"Give the distance between two farthest points. Distance between", "m, v, sq), lambda i, m, v, sq: while_loop_body(i, m,", "n_max_iterations=40, epsilon=1e-12, init_points=[], verbose=False): \"\"\"Compute Frechet mean of (weighted) points", "norm : array-like, shape=[n_samples,] \"\"\" sq_norm = self.squared_norm(vector, base_point) norm", "to_ndim=point_ndim + 1) if end_point is None and initial_tangent_vec is", "if n_points == 1: return mean sq_dists_between_iterates = [] iteration", "{1}, \" \"norm_current_tangent_mean = {2}\".format( iter, tau, norm_current_tangent_mean)) if norm_next_tangent_mean", "or iteration == 0 def while_loop_body(iteration, mean, variance, sq_dist): logs", "axis=0) einsum_str_b = 'k,nk->n' elif n_tangent_vec_b == 1: tangent_vec_b =", "tau = max(1.0, 1.0511111 * tau) else: tau = tau", "n_init == 0: current_mean = points[0] else: current_mean = init_points[0]", "n_tangent_vec_a == 1: tangent_vec_a = gs.squeeze(tangent_vec_a, axis=0) einsum_str_a = 'j,njk->nk'", "vector. Squared norm of a vector associated to the inner", "dimension], optional initial_tangent_vec : array-like, shape=[n_samples, dimension], optional point_type :", "point or an initial tangent ' 'vector to define the", "dimension] weights : array-like, shape=[n_samples, 1], optional verbose : bool,", "tau = tau * 0.8 if iteration == n_max_iterations: warnings.warn(", "next_mean current_tangent_mean = next_tangent_mean norm_current_tangent_mean = norm_next_tangent_mean tau = max(1.0,", "norm of a vector associated to the inner product at", "variance, sq_dist] if point_type == 'vector': points = gs.to_ndarray(points, to_ndim=2)", "else: einsum_str_a = 'nj,njk->nk' aux = gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat) n_auxs,", "study performance, # i.e. what to do with sq_dists_between_iterates. def", "wrt a base point. Parameters ---------- points: array-like, shape=[n_samples, dimension]", "is the tangent mean at x) rather than the mean-square-distance", "distance between two points. Parameters ---------- point_a : array-like, shape=[n_samples,", "init_points[0] tau = 1.0 iteration = 0 logs = self.log(point=points,", "array-like, shape=[n_samples,] \"\"\" sq_norm = self.inner_product(vector, vector, base_point) return sq_norm", "of iterations {} reached. The ' 'mean may be inaccurate'.format(n_max_iterations))", "gs.ones((n_points, 1)) weights = gs.array(weights) weights = gs.to_ndarray(weights, to_ndim=2, axis=1)", ": array-like, shape=[n_samples, 1], optional verbose : bool, optional Returns", "epsilon: tolerance for stopping the gradient descent \"\"\" # TODO(Xavier):", "raise NotImplementedError( 'The computation of the inner product matrix' '", "None: weights = gs.ones((n_points, 1)) weights = gs.array(weights) weights =", "sq_norm : array-like, shape=[n_samples,] \"\"\" sq_norm = self.inner_product(vector, vector, base_point)", "1) shooting_tangent_vec = self.log(point=end_point, base_point=initial_point) if initial_tangent_vec is not None:", "Profile this code to study performance, # i.e. what to", "inner_prod_mat) n_auxs, _ = gs.shape(aux) if n_tangent_vec_b != n_auxs: if", "Parameters ---------- points : array-like, shape=[n_samples, dimension] weights : array-like,", "= points.mean(0, keepdims=True) * 0 while convergence > tau and", "------- inner_product : array-like, shape=[n_samples,] \"\"\" tangent_vec_a = gs.to_ndarray(tangent_vec_a, to_ndim=2)", "weights is None: weights = gs.ones((n_points, 1)) weights = gs.array(weights)", "curve defined by either: - an initial point and an", "+ term_3) return christoffels def inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None): \"\"\"Inner", "---------- point neighbors Returns ------- closest_neighbor_index \"\"\" dist = self.dist(point,", "1 shooting_vector = gs.to_ndarray( tau * current_tangent_mean, to_ndim=2) next_mean =", "== 1: inner_prod_mat = gs.squeeze(inner_prod_mat, axis=0) einsum_str_a = 'nj,jk->nk' else:", "loss(y_pred, y_true, metric): \"\"\"Compute loss function between prediction and ground", "stopping the gradient descent \"\"\" # TODO(Xavier): This function assumes", "---------- points : array-like, shape=[n_samples, dimension] weights : array-like, shape=[n_samples,", "n_mats = gs.shape(inner_prod_mat)[0] if n_tangent_vec_a != n_mats: if n_tangent_vec_a ==", "= 1e-3 tau = 5e-3 if len(points) == 1: return", "= gs.to_ndarray(tangent_vec_a, to_ndim=2) tangent_vec_b = gs.to_ndarray(tangent_vec_b, to_ndim=2) n_tangent_vec_a = gs.shape(tangent_vec_a)[0]", "shape=[n_samples, dimension] Returns ------- dist : array-like, shape=[n_samples,] \"\"\" sq_dist", "= 0.5 * (term_1 + term_2 + term_3) return christoffels", "current_tangent_mean = next_tangent_mean norm_current_tangent_mean = norm_next_tangent_mean tau = max(1.0, 1.0511111", "for stopping the gradient descent verbose: verbose mode printing the", "to_ndim=3) if n_points == 1: return mean sq_dists_between_iterates = []", "sum_weights variance = gs.to_ndarray(variance, to_ndim=1) variance = gs.to_ndarray(variance, to_ndim=2, axis=1)", "!= n_mats: if n_tangent_vec_a == 1: tangent_vec_a = gs.squeeze(tangent_vec_a, axis=0)", "array-like, shape=[n_samples, dimension], optional point_type : str, optional Returns -------", "of the geodesic Returns ------- point_at_time_t : callable \"\"\" t", "base_point=None): \"\"\"Compute derivative of the inner prod matrix at base", "0.), gs.less_equal(sq_dist, epsilon * variance)) return result[0, 0] or iteration", "dimension] weights: array-like, shape=[n_samples, 1], optional \"\"\" if point_type ==", "cc_barycenter = self.exp(lr * grad_tangent.sum(0, keepdims=True), barycenter) convergence = self.dist(cc_barycenter,", "def diameter(self, points): \"\"\"Give the distance between two farthest points.", "manifold \"\"\" if mean_method == 'default': # TODO(nina): Profile this", "of a vector. Norm of a vector associated to the", "tangent_vec_a, inner_prod_mat) n_auxs, _ = gs.shape(aux) if n_tangent_vec_b != n_auxs:", "tangent_vec_b: array-like, shape=[n_samples, dimension] or shape=[1, dimension] base_point: array-like, shape=[n_samples,", "return result[0, 0] or iteration == 0 def while_loop_body(iteration, mean,", "at a base point. Parameters ---------- tangent_vec_a: array-like, shape=[n_samples, dimension]", "'matrix': point_ndim = 2 initial_point = gs.to_ndarray(initial_point, to_ndim=point_ndim + 1)", "weights=None, n_max_iterations=40, epsilon=1e-12, init_points=[], verbose=False): \"\"\"Compute Frechet mean of (weighted)", "gs.repeat(barycenter, points.shape[0], 0) grad_tangent = 2 * self.log(points, expand_barycenter) cc_barycenter", "the gradient of the loss function.\"\"\" tangent_vec = metric.log(base_point=y_pred, point=y_true)", "def while_loop_body(iteration, mean, variance, sq_dist): logs = self.log(point=points, base_point=mean) tangent_mean", "'matrix': mean = gs.to_ndarray(mean, to_ndim=3) if n_points == 1: return", "weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) n_init =", "= 1e-4 N_CENTERS = 10 TOLERANCE = 1e-5 N_REPETITIONS =", "array-like, shape=[n_samples, dimension] Returns ------- norm : array-like, shape=[n_samples,] \"\"\"", "adaptive time-steps. Frechet mean of (weighted) points using adaptive time-steps", "if n_tangent_vec_b != n_auxs: if n_auxs == 1: aux =", "= gs.to_ndarray(points, to_ndim=3) n_points = gs.shape(points)[0] if weights is None:", ": array-like, shape=[n_samples, dimension] base_point : array-like, shape=[n_samples, dimension] Returns", "because this saves computation time. Parameters ---------- points: array-like, shape=[n_samples,", "1))) return grad class RiemannianMetric(Connection): \"\"\"Class for Riemannian and pseudo-Riemannian", "to_ndim=2) if weights is None: weights = gs.ones((n_points, 1)) weights", "+ 1) new_initial_tangent_vec = gs.to_ndarray( initial_tangent_vec, to_ndim=point_ndim + 1) if", "weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) mean =", "n_points = gs.shape(points)[0] if n_points == 1: return gs.to_ndarray(points[0], to_ndim=2)", "by either: - an initial point and an initial tangent", "import math import warnings import autograd import geomstats.backend as gs", "# i.e. what to do with sq_dists_between_iterates. def while_loop_cond(iteration, mean,", "'k,nk->n' elif n_tangent_vec_b == 1: tangent_vec_b = gs.squeeze(tangent_vec_b, axis=0) einsum_str_b", "n_points == 1: return gs.to_ndarray(points[0], to_ndim=2) if weights is None:", "points. Parameters ---------- points Returns ------- diameter \"\"\" diameter =", "if mean_method == 'default': # TODO(nina): Profile this code to", "= 'nk,nk->n' inner_prod = gs.einsum(einsum_str_b, aux, tangent_vec_b) inner_prod = gs.to_ndarray(inner_prod,", "truth. Loss function given by a Riemannian metric, expressed as", "shape=[n_samples,] \"\"\" tangent_vec_a = gs.to_ndarray(tangent_vec_a, to_ndim=2) tangent_vec_b = gs.to_ndarray(tangent_vec_b, to_ndim=2)", "shape=[1, dimension] base_point: array-like, shape=[n_samples, dimension] or shape=[1, dimension] Returns", ": array-like, shape=[n_samples, dimension] end_point : array-like, shape=[n_samples, dimension], optional", "path : callable \"\"\" point_ndim = 1 if point_type ==", "return barycenter def adaptive_gradientdescent_mean(self, points, weights=None, n_max_iterations=40, epsilon=1e-12, init_points=[], verbose=False):", "None: raise ValueError('Specify an end point or an initial tangent", "- gs.einsum('nim,nklm->nikl', cometric_mat_at_point, metric_derivative_at_point) christoffels = 0.5 * (term_1 +", "tangent_vec=shooting_vector, base_point=current_mean) logs = self.log(point=points, base_point=next_mean) next_tangent_mean = gs.einsum('nk,nj->j', weights,", "n_max_iterations: warnings.warn( 'Maximum number of iterations {} reached.' 'The mean", "to_ndim=point_ndim + 1) if point_type == 'vector': tangent_vecs = gs.einsum('il,nk->ik',", "either: - an initial point and an initial tangent vector,", ": array-like, shape=[n_samples,] \"\"\" sq_norm = self.inner_product(vector, vector, base_point) return", "if iteration == n_max_iterations: warnings.warn( 'Maximum number of iterations {}", "== n_max_iterations: warnings.warn( 'Maximum number of iterations {} reached.' 'The", "(weighted) points. Parameters ---------- points : array-like, shape=[n_samples, dimension] weights", "Returns ------- point_at_time_t : callable \"\"\" t = gs.cast(t, gs.float32)", "v, sq: while_loop_cond(i, m, v, sq), lambda i, m, v,", "mean = gs.to_ndarray(mean, to_ndim=2) return mean if mean_method == 'frechet-poincare-ball':", "point among neighbors. Parameters ---------- point neighbors Returns ------- closest_neighbor_index", "tangent vector, or - an initial point and an end", "the gradient descent \"\"\" # TODO(Xavier): This function assumes that", "for the gradient of the loss function.\"\"\" tangent_vec = metric.log(base_point=y_pred,", "raise ValueError('Shape mismatch for einsum.') else: einsum_str_a = 'nj,njk->nk' aux", "\"\"\"Inner product matrix at the tangent space at a base", "not None: end_point = gs.to_ndarray(end_point, to_ndim=point_ndim + 1) shooting_tangent_vec =", "epsilon * variance)) return result[0, 0] or iteration == 0", "to_ndim=2, axis=1) return variance def mean(self, points, weights=None, n_max_iterations=32, epsilon=EPSILON,", "gs.array(weights) weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) n_init", "dimension] weights: array-like, shape=[n_samples, 1], optional init_points: array-like, shape=[n_init, dimension]", "\"\"\"Frechet mean of (weighted) points. Parameters ---------- points : array-like,", "= gs.to_ndarray(tangent_vec_b, to_ndim=2) n_tangent_vec_a = gs.shape(tangent_vec_a)[0] n_tangent_vec_b = gs.shape(tangent_vec_b)[0] inner_prod_mat", "> tau and n_max_iterations > iteration: iteration += 1 expand_barycenter", "= self.log(point=points, base_point=mean) tangent_mean = gs.einsum('nk,nj->j', weights, logs) tangent_mean /=", "return metric_derivative(base_point) def christoffels(self, base_point): \"\"\"Compute Christoffel symbols associated with", "n_max_iterations: print('Maximum number of iterations {} reached.' 'The mean may", "= self.inner_product_derivative_matrix( base_point) term_1 = gs.einsum('nim,nmkl->nikl', cometric_mat_at_point, metric_derivative_at_point) term_2 =", "einsum_str_b = 'k,nk->n' elif n_tangent_vec_b == 1: tangent_vec_b = gs.squeeze(tangent_vec_b,", "convergence = math.inf barycenter = points.mean(0, keepdims=True) * 0 while", "+ 1 shooting_vector = gs.to_ndarray( tau * current_tangent_mean, to_ndim=2) next_mean", "point_type='vector'): \"\"\"Return the geodesic as function of t. Geodesic curve", "points[i + 1:, :]) dist_to_farthest_neighbor = gs.amax(dist_to_neighbors) diameter = gs.maximum(diameter,", "\"\"\" cometric_mat_at_point = self.inner_product_inverse_matrix(base_point) metric_derivative_at_point = self.inner_product_derivative_matrix( base_point) term_1 =", "callable \"\"\" point_ndim = 1 if point_type == 'matrix': point_ndim", "= gs.to_ndarray( initial_point, to_ndim=point_ndim + 1) new_initial_tangent_vec = gs.to_ndarray( initial_tangent_vec,", "dimension] Returns ------- inner_product : array-like, shape=[n_samples,] \"\"\" tangent_vec_a =", ": parameter value of the geodesic Returns ------- point_at_time_t :", "= gs.linalg.norm(next_tangent_mean) if verbose: print( \"Iter {0}: tau= {1}, \"", "end_point is not None: end_point = gs.to_ndarray(end_point, to_ndim=point_ndim + 1)", "array-like, shape=[n_samples, dimension] Returns ------- dist : array-like, shape=[n_samples,] \"\"\"", "point on the manifold \"\"\" if mean_method == 'default': #", "------- mean : array-like the Frechet mean of points, a", "---------- base_point : array-like, shape=[n_samples, dimension], optional \"\"\" metric_derivative =", "'vector to define the geodesic.') if end_point is not None:", "and ground truth. Loss function given by a Riemannian metric,", "20 N_MAX_ITERATIONS = 50000 N_STEPS = 10 def loss(y_pred, y_true,", "\"\"\" t = gs.cast(t, gs.float32) t = gs.to_ndarray(t, to_ndim=1) t", "distance between two points. Note: It only works for positive", "sq_dist = self.squared_dist(point_a, point_b) dist = gs.sqrt(sq_dist) return dist def", "the tangent mean at x) rather than the mean-square-distance (MSD)", "mean_method == 'default': # TODO(nina): Profile this code to study", "loss \"\"\" loss = metric.squared_dist(y_pred, y_true) return loss def grad(y_pred,", "metric_derivative = autograd.jacobian(self.inner_product_matrix) return metric_derivative(base_point) def christoffels(self, base_point): \"\"\"Compute Christoffel", "i.e. what to do with sq_dists_between_iterates. def while_loop_cond(iteration, mean, variance,", "base_point=None): \"\"\"Inner product between two tangent vectors at a base", "point_type == 'matrix': tangent_vecs = gs.einsum('il,nkm->ikm', t, new_initial_tangent_vec) point_at_time_t =", "\"Iter {0}: tau= {1}, \" \"norm_current_tangent_mean = {2}\".format( iter, tau,", "= gs.squeeze(tangent_vec_a, axis=0) einsum_str_a = 'j,njk->nk' elif n_mats == 1:", "works for positive definite Riemannian metrics. Parameters ---------- point_a :", "squared_norm(self, vector, base_point=None): \"\"\"Compute the square of the norm of", "only works for positive-definite Riemannian metrics and inner products. Parameters", "m, v, sq: while_loop_body(i, m, v, sq), loop_vars=[iteration, mean, variance,", "in points. Parameters ---------- points Returns ------- diameter \"\"\" diameter", "gs.einsum(einsum_str_b, aux, tangent_vec_b) inner_prod = gs.to_ndarray(inner_prod, to_ndim=2, axis=1) assert gs.ndim(inner_prod)", "base_point=None): \"\"\"Compute norm of a vector. Norm of a vector", "= gs.sum(weights) mean = points[0] if point_type == 'vector': mean", "== 'vector': points = gs.to_ndarray(points, to_ndim=2) if point_type == 'matrix':", "sq_dists_between_iterates. def while_loop_cond(iteration, mean, variance, sq_dist): result = ~gs.logical_or( gs.isclose(variance,", "implemented.') def inner_product_inverse_matrix(self, base_point=None): \"\"\"Inner product matrix at the tangent", "to_ndim=3) n_points = gs.shape(points)[0] if weights is None: weights =", "point. Parameters ---------- tangent_vec_a: array-like, shape=[n_samples, dimension] or shape=[1, dimension]", "mean, variance, sq_dist = gs.while_loop( lambda i, m, v, sq:", "gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) mean = points[0] if", "einsum_str_a = 'nj,jk->nk' else: raise ValueError('Shape mismatch for einsum.') else:", "= next_tangent_mean norm_current_tangent_mean = norm_next_tangent_mean tau = max(1.0, 1.0511111 *", "time-steps The loss function optimized is ||M_1(x)||_x (where M_1(x) is", "last_iteration, variance, sq_dist)) mean = gs.to_ndarray(mean, to_ndim=2) return mean if", "= norm_next_tangent_mean tau = max(1.0, 1.0511111 * tau) else: tau", "gs.einsum('il,nk->ik', t, new_initial_tangent_vec) elif point_type == 'matrix': tangent_vecs = gs.einsum('il,nkm->ikm',", "== 1: return mean sq_dists_between_iterates = [] iteration = 0", "- 2. * tangent_vec inner_prod_mat = metric.inner_product_matrix(base_point=y_pred) grad = gs.einsum('ni,nij->ni',", "= self.squared_dist(mean_next, mean) sq_dists_between_iterates.append(sq_dist) variance = self.variance(points=points, weights=weights, base_point=mean_next) mean", "array-like, shape=[n_samples, 1], optional init_points: array-like, shape=[n_init, dimension] epsilon: tolerance", "\"\"\"Squared geodesic distance between two points. Parameters ---------- point_a :", "# TODO(Xavier): This function assumes that all points are lists", "---------- t : parameter value of the geodesic Returns -------", "str, optional Returns ------- path : callable \"\"\" point_ndim =", "dist_to_farthest_neighbor = gs.amax(dist_to_neighbors) diameter = gs.maximum(diameter, dist_to_farthest_neighbor) return diameter def", "norm_current_tangent_mean)) if norm_next_tangent_mean < norm_current_tangent_mean: current_mean = next_mean current_tangent_mean =", "shape=[n_samples, dimension] point_b : array-like, shape=[n_samples, dimension] Returns ------- sq_dist", "+ term_2 + term_3) return christoffels def inner_product(self, tangent_vec_a, tangent_vec_b,", "---------- base_point: array-like, shape=[n_samples, dimension] Returns ------- christoffels: array-like, shape=[n_samples,", "iteration == n_max_iterations: warnings.warn( 'Maximum number of iterations {} reached.'", "= gs.array(weights) weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights)", "time. Parameters ---------- points: array-like, shape=[n_samples, dimension] weights: array-like, shape=[n_samples,", "= gs.to_ndarray(t, to_ndim=1) t = gs.to_ndarray(t, to_ndim=2, axis=1) new_initial_point =", "'The mean may be inaccurate'.format(n_max_iterations)) if verbose: print('n_iter: {}, final", "t, new_initial_tangent_vec) point_at_time_t = self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point) return point_at_time_t return path", "matrix at the tangent space at a base point. Parameters", "adaptive_gradientdescent_mean(self, points, weights=None, n_max_iterations=40, epsilon=1e-12, init_points=[], verbose=False): \"\"\"Compute Frechet mean", "to_ndim=1) t = gs.to_ndarray(t, to_ndim=2, axis=1) new_initial_point = gs.to_ndarray( initial_point,", "farthest away from each other in points. Parameters ---------- points", "return points iteration = 0 convergence = math.inf barycenter =", "point. Parameters ---------- vector : array-like, shape=[n_samples, dimension] base_point :", "if point_type == 'matrix': points = gs.to_ndarray(points, to_ndim=3) n_points =", "if verbose: print( \"Iter {0}: tau= {1}, \" \"norm_current_tangent_mean =", "variance(self, points, weights=None, base_point=None, point_type='vector'): \"\"\"Variance of (weighted) points wrt", "math.inf assert dimension > 0 super().__init__(dimension=dimension) self.signature = signature def", "= tau * 0.8 if iteration == n_max_iterations: warnings.warn( 'Maximum", "Frechet mean of (weighted) points using adaptive time-steps The loss", "optional Returns ------- path : callable \"\"\" point_ndim = 1", "point_type='vector', mean_method='default', verbose=False): \"\"\"Frechet mean of (weighted) points. Parameters ----------", "= init_points[0] tau = 1.0 iteration = 0 logs =", "last_iteration == n_max_iterations: print('Maximum number of iterations {} reached.' 'The", "last_iteration, mean, variance, sq_dist = gs.while_loop( lambda i, m, v,", "Parameters ---------- y_pred y_true metric Returns ------- loss \"\"\" loss", "dimension] Returns ------- dist : array-like, shape=[n_samples,] \"\"\" sq_dist =", "iteration = 0 sq_dist = gs.array([[0.]]) variance = gs.array([[0.]]) last_iteration,", "------- norm : array-like, shape=[n_samples,] \"\"\" sq_norm = self.squared_norm(vector, base_point)", "> iteration: iteration += 1 expand_barycenter = gs.repeat(barycenter, points.shape[0], 0)", "------- sq_norm : array-like, shape=[n_samples,] \"\"\" sq_norm = self.inner_product(vector, vector,", "metric.squared_dist(y_pred, y_true) return loss def grad(y_pred, y_true, metric): \"\"\"Closed-form for", "variance = gs.to_ndarray(variance, to_ndim=2, axis=1) return variance def mean(self, points,", ": array-like, shape=[n_samples, dimension], optional point_type : str, optional Returns", "inner_prod = gs.to_ndarray(inner_prod, to_ndim=2, axis=1) assert gs.ndim(inner_prod) == 2, inner_prod.shape", "\"\"\" diameter = 0.0 n_points = points.shape[0] for i in", "point and an initial tangent vector, or - an initial", "= 1e-5 N_REPETITIONS = 20 N_MAX_ITERATIONS = 50000 N_STEPS =", "to_ndim=2, axis=1) sum_weights = gs.sum(weights) mean = points[0] if point_type", ": array-like, shape=[n_samples, dimension] weights : array-like, shape=[n_samples, 1], optional", "end point. The geodesic is returned as a function parameterized", "1.0 iteration = 0 logs = self.log(point=points, base_point=current_mean) current_tangent_mean =", "tangent_vec_b = gs.squeeze(tangent_vec_b, axis=0) einsum_str_b = 'nk,k->n' else: raise ValueError('Shape", "dimension] end_point : array-like, shape=[n_samples, dimension], optional initial_tangent_vec : array-like,", "next_tangent_mean norm_current_tangent_mean = norm_next_tangent_mean tau = max(1.0, 1.0511111 * tau)", "variance, sq_dist): logs = self.log(point=points, base_point=mean) tangent_mean = gs.einsum('nk,nj->j', weights,", "weights=None, base_point=None, point_type='vector'): \"\"\"Variance of (weighted) points wrt a base", "iteration == 0 def while_loop_body(iteration, mean, variance, sq_dist): logs =", "the connection. Parameters ---------- base_point: array-like, shape=[n_samples, dimension] Returns -------", "gs.array(initial_tangent_vec) initial_tangent_vec = gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim + 1) def path(t): \"\"\"Generate", "shape=[n_samples, dimension] Returns ------- christoffels: array-like, shape=[n_samples, dimension, dimension, dimension]", "points.shape[0], 0) grad_tangent = 2 * self.log(points, expand_barycenter) cc_barycenter =", "that are farthest away from each other in points. Parameters", "metric, expressed as the squared geodesic distance between the prediction", "positive-definite Riemannian metrics and inner products. Parameters ---------- vector :", "= gs.sqrt(sq_norm) return norm def geodesic(self, initial_point, end_point=None, initial_tangent_vec=None, point_type='vector'):", "be inaccurate'.format(n_max_iterations)) if verbose: print('n_iter: {}, final variance: {}, final", "def inner_product_matrix(self, base_point=None): \"\"\"Inner product matrix at the tangent space", "def mean(self, points, weights=None, n_max_iterations=32, epsilon=EPSILON, point_type='vector', mean_method='default', verbose=False): \"\"\"Frechet", "sq_norm = self.inner_product(vector, vector, base_point) return sq_norm def norm(self, vector,", "def while_loop_cond(iteration, mean, variance, sq_dist): result = ~gs.logical_or( gs.isclose(variance, 0.),", "{}'.format( last_iteration, variance, sq_dist)) mean = gs.to_ndarray(mean, to_ndim=2) return mean", "max(1.0, 1.0511111 * tau) else: tau = tau * 0.8", "/= sum_weights norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean) while (norm_current_tangent_mean > epsilon and", "new_initial_tangent_vec) point_at_time_t = self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point) return point_at_time_t return path def", "= metric.log(base_point=y_pred, point=y_true) grad_vec = - 2. * tangent_vec inner_prod_mat", "= gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) if base_point is", "gs.array([[0.]]) variance = gs.array([[0.]]) last_iteration, mean, variance, sq_dist = gs.while_loop(", "current_tangent_mean = gs.einsum('nk,nj->j', weights, logs) current_tangent_mean /= sum_weights norm_current_tangent_mean =", "dimension, dimension] \"\"\" cometric_mat_at_point = self.inner_product_inverse_matrix(base_point) metric_derivative_at_point = self.inner_product_derivative_matrix( base_point)", "inner products. Parameters ---------- vector : array-like, shape=[n_samples, dimension] base_point", "= 20 N_MAX_ITERATIONS = 50000 N_STEPS = 10 def loss(y_pred,", "base point. Note: This only works for positive-definite Riemannian metrics", "vectors and not of matrices n_points = gs.shape(points)[0] if n_points", "array-like, shape=[n_samples, dimension] end_point : array-like, shape=[n_samples, dimension], optional initial_tangent_vec", "gs.ndim(inner_prod) == 2, inner_prod.shape return inner_prod def squared_norm(self, vector, base_point=None):", "sq_dist : array-like, shape=[n_samples,] \"\"\" log = self.log(point=point_b, base_point=point_a) sq_dist", "(weighted) points using adaptive time-steps. Frechet mean of (weighted) points", "== 'matrix': points = gs.to_ndarray(points, to_ndim=3) n_points = gs.shape(points)[0] if", "== 0: current_mean = points[0] else: current_mean = init_points[0] tau", "array-like, shape=[n_samples, dimension] weights: array-like, shape=[n_samples, 1], optional \"\"\" if", "1 return [iteration, mean, variance, sq_dist] if point_type == 'vector':", ":], points[i + 1:, :]) dist_to_farthest_neighbor = gs.amax(dist_to_neighbors) diameter =", "= 'j,njk->nk' elif n_mats == 1: inner_prod_mat = gs.squeeze(inner_prod_mat, axis=0)", "array-like, shape=[n_samples, dimension], optional \"\"\" raise NotImplementedError( 'The computation of", "computation of the inner product matrix' ' is not implemented.')", "None and initial_tangent_vec is None: raise ValueError('Specify an end point", "axis=0) einsum_str_b = 'nk,k->n' else: raise ValueError('Shape mismatch for einsum.')", "base_point=mean) tangent_mean = gs.einsum('nk,nj->j', weights, logs) tangent_mean /= sum_weights mean_next", "n_max_iterations: warnings.warn( 'Maximum number of iterations {} reached. The '", "mean_method='default', verbose=False): \"\"\"Frechet mean of (weighted) points. Parameters ---------- points", "'The mean may be inaccurate'.format(n_max_iterations)) return gs.to_ndarray(current_mean, to_ndim=2) def diameter(self,", "geodesic distance between two points. Parameters ---------- point_a : array-like,", "keepdims=True) * 0 while convergence > tau and n_max_iterations >", "einsum_str_a = 'nj,njk->nk' aux = gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat) n_auxs, _", "This only works for positive-definite Riemannian metrics and inner products.", "base_point : array-like, shape=[n_samples, dimension] Returns ------- norm : array-like,", "parameterizing the geodesic. Parameters ---------- t : parameter value of", "{} reached.' 'The mean may be inaccurate'.format(n_max_iterations)) return gs.to_ndarray(current_mean, to_ndim=2)", "loss function between prediction and ground truth. Loss function given", "== 'matrix': mean = gs.to_ndarray(mean, to_ndim=3) if n_points == 1:", "array-like, shape=[n_samples, dimension] weights: array-like, shape=[n_samples, 1], optional init_points: array-like,", "value of the geodesic Returns ------- point_at_time_t : callable \"\"\"", "stopping the gradient descent verbose: verbose mode printing the surrogate", "for positive-definite Riemannian metrics and inner products. Parameters ---------- vector", "from each other in points. Parameters ---------- points Returns -------", "def loss(y_pred, y_true, metric): \"\"\"Compute loss function between prediction and", "prediction and ground truth. Loss function given by a Riemannian", "M_1(x) is the tangent mean at x) rather than the", "at base point. Parameters ---------- base_point : array-like, shape=[n_samples, dimension],", "= self.dist(cc_barycenter, barycenter).max().item() barycenter = cc_barycenter if iteration == n_max_iterations:", "ground truth. Loss function given by a Riemannian metric, expressed", "shape=[n_samples, dimension] base_point : array-like, shape=[n_samples, dimension] Returns ------- sq_norm", "= 'nj,jk->nk' else: raise ValueError('Shape mismatch for einsum.') else: einsum_str_a", "None: assert gs.allclose(shooting_tangent_vec, initial_tangent_vec) initial_tangent_vec = shooting_tangent_vec initial_tangent_vec = gs.array(initial_tangent_vec)", "if norm_next_tangent_mean < norm_current_tangent_mean: current_mean = next_mean current_tangent_mean = next_tangent_mean", "einsum.') else: einsum_str_b = 'nk,nk->n' inner_prod = gs.einsum(einsum_str_b, aux, tangent_vec_b)", "base point. Parameters ---------- vector : array-like, shape=[n_samples, dimension] base_point", "shape=[n_samples, dimension], optional \"\"\" metric_matrix = self.inner_product_matrix(base_point) cometric_matrix = gs.linalg.inv(metric_matrix)", "logs = self.log(point=points, base_point=mean) tangent_mean = gs.einsum('nk,nj->j', weights, logs) tangent_mean", "the tangent space at a base point. Parameters ---------- vector", "\"\"\" if point_type == 'vector': points = gs.to_ndarray(points, to_ndim=2) if", "point_type == 'vector': points = gs.to_ndarray(points, to_ndim=2) if point_type ==", "\"\"\"Inner product between two tangent vectors at a base point.", "if n_tangent_vec_a != n_mats: if n_tangent_vec_a == 1: tangent_vec_a =", "n_mats == 1: inner_prod_mat = gs.squeeze(inner_prod_mat, axis=0) einsum_str_a = 'nj,jk->nk'", "point_type == 'vector': tangent_vecs = gs.einsum('il,nk->ik', t, new_initial_tangent_vec) elif point_type", "tangent_vec=tangent_mean, base_point=mean) sq_dist = self.squared_dist(mean_next, mean) sq_dists_between_iterates.append(sq_dist) variance = self.variance(points=points,", "------- path : callable \"\"\" point_ndim = 1 if point_type", "two points. Parameters ---------- point_a : array-like, shape=[n_samples, dimension] point_b", "points, weights=None, n_max_iterations=32, epsilon=EPSILON, point_type='vector', mean_method='default', verbose=False): \"\"\"Frechet mean of", "Parameters ---------- t : parameter value of the geodesic Returns", "gs.maximum(diameter, dist_to_farthest_neighbor) return diameter def closest_neighbor_index(self, point, neighbors): \"\"\"Closest neighbor", "gs.einsum('nim,nmlk->nilk', cometric_mat_at_point, metric_derivative_at_point) term_3 = - gs.einsum('nim,nklm->nikl', cometric_mat_at_point, metric_derivative_at_point) christoffels", "/= sum_weights norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean) if verbose: print( \"Iter {0}:", "variance: {}, final dist: {}'.format( last_iteration, variance, sq_dist)) mean =", "the square of the norm of a vector. Squared norm", "y_true) return loss def grad(y_pred, y_true, metric): \"\"\"Closed-form for the", "the distance between two farthest points. Distance between the two", "+= 1 return [iteration, mean, variance, sq_dist] if point_type ==", "each other in points. Parameters ---------- points Returns ------- diameter", ": callable \"\"\" point_ndim = 1 if point_type == 'matrix':", "optional \"\"\" metric_matrix = self.inner_product_matrix(base_point) cometric_matrix = gs.linalg.inv(metric_matrix) return cometric_matrix", "# of vectors and not of matrices n_points = gs.shape(points)[0]", "n_init = len(init_points) if n_init == 0: current_mean = points[0]", "class RiemannianMetric(Connection): \"\"\"Class for Riemannian and pseudo-Riemannian metrics.\"\"\" def __init__(self,", "= self.inner_product_matrix(base_point) inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3) n_mats = gs.shape(inner_prod_mat)[0] if", "tangent_vec_b, base_point=None): \"\"\"Inner product between two tangent vectors at a", "1) if end_point is None and initial_tangent_vec is None: raise", "= 0 convergence = math.inf barycenter = points.mean(0, keepdims=True) *", "range(n_points - 1): dist_to_neighbors = self.dist(points[i, :], points[i + 1:,", "iteration: iteration += 1 expand_barycenter = gs.repeat(barycenter, points.shape[0], 0) grad_tangent", "while (norm_current_tangent_mean > epsilon and iteration < n_max_iterations): iteration =", "= gs.shape(tangent_vec_b)[0] inner_prod_mat = self.inner_product_matrix(base_point) inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3) n_mats", "Parameters ---------- points Returns ------- diameter \"\"\" diameter = 0.0", "gs.amax(dist_to_neighbors) diameter = gs.maximum(diameter, dist_to_farthest_neighbor) return diameter def closest_neighbor_index(self, point,", "parameter value of the geodesic Returns ------- point_at_time_t : callable", "== 0 def while_loop_body(iteration, mean, variance, sq_dist): logs = self.log(point=points,", "N_STEPS = 10 def loss(y_pred, y_true, metric): \"\"\"Compute loss function", "is not None: assert gs.allclose(shooting_tangent_vec, initial_tangent_vec) initial_tangent_vec = shooting_tangent_vec initial_tangent_vec", "shape=[n_samples,] \"\"\" sq_norm = self.inner_product(vector, vector, base_point) return sq_norm def", "of point among neighbors. Parameters ---------- point neighbors Returns -------", "to_ndim=2) tangent_vec_b = gs.to_ndarray(tangent_vec_b, to_ndim=2) n_tangent_vec_a = gs.shape(tangent_vec_a)[0] n_tangent_vec_b =", "raise ValueError('Specify an end point or an initial tangent '", "\"\"\" metric_matrix = self.inner_product_matrix(base_point) cometric_matrix = gs.linalg.inv(metric_matrix) return cometric_matrix def", "logs) next_tangent_mean /= sum_weights norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean) if verbose: print(", "points wrt a base point. Parameters ---------- points: array-like, shape=[n_samples,", "metrics and inner products. Parameters ---------- vector : array-like, shape=[n_samples,", "if point_type == 'vector': tangent_vecs = gs.einsum('il,nk->ik', t, new_initial_tangent_vec) elif", "products. Parameters ---------- vector : array-like, shape=[n_samples, dimension] base_point :", "= 50000 N_STEPS = 10 def loss(y_pred, y_true, metric): \"\"\"Compute", "not of matrices n_points = gs.shape(points)[0] if n_points == 1:", "= gs.squeeze(inner_prod_mat, axis=0) einsum_str_a = 'nj,jk->nk' else: raise ValueError('Shape mismatch", "tau) else: tau = tau * 0.8 if iteration ==", "tau * current_tangent_mean, to_ndim=2) next_mean = self.exp( tangent_vec=shooting_vector, base_point=current_mean) logs", "(weighted) points using adaptive time-steps The loss function optimized is", "to_ndim=2, axis=1) new_initial_point = gs.to_ndarray( initial_point, to_ndim=point_ndim + 1) new_initial_tangent_vec", "mean = mean_next iteration += 1 return [iteration, mean, variance,", "the norm of a vector. Squared norm of a vector", "v, sq), lambda i, m, v, sq: while_loop_body(i, m, v,", "point_ndim = 1 if point_type == 'matrix': point_ndim = 2", "sq: while_loop_body(i, m, v, sq), loop_vars=[iteration, mean, variance, sq_dist], maximum_iterations=n_max_iterations)", "------- dist : array-like, shape=[n_samples,] \"\"\" sq_dist = self.squared_dist(point_a, point_b)", "to_ndim=3) n_mats = gs.shape(inner_prod_mat)[0] if n_tangent_vec_a != n_mats: if n_tangent_vec_a", ": array-like, shape=[n_samples, dimension] point_b : array-like, shape=[n_samples, dimension] Returns", "for stopping the gradient descent \"\"\" # TODO(Xavier): This function", "variance = gs.to_ndarray(variance, to_ndim=1) variance = gs.to_ndarray(variance, to_ndim=2, axis=1) return", "weights : array-like, shape=[n_samples, 1], optional verbose : bool, optional", "gs.sum(weights) if base_point is None: base_point = self.mean(points, weights) variance", "inner_product_inverse_matrix(self, base_point=None): \"\"\"Inner product matrix at the tangent space at", "return gs.to_ndarray(points[0], to_ndim=2) if weights is None: weights = gs.ones((n_points,", "while_loop_cond(i, m, v, sq), lambda i, m, v, sq: while_loop_body(i,", "surrogate value epsilon: tolerance for stopping the gradient descent \"\"\"", "point_type == 'matrix': point_ndim = 2 initial_point = gs.to_ndarray(initial_point, to_ndim=point_ndim", "+ 1:, :]) dist_to_farthest_neighbor = gs.amax(dist_to_neighbors) diameter = gs.maximum(diameter, dist_to_farthest_neighbor)", "gs.shape(tangent_vec_b)[0] inner_prod_mat = self.inner_product_matrix(base_point) inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3) n_mats =", "for Riemannian and pseudo-Riemannian metrics.\"\"\" def __init__(self, dimension, signature=None): assert", "diameter def closest_neighbor_index(self, point, neighbors): \"\"\"Closest neighbor of point among", "array-like, shape=[n_samples, dimension] weights : array-like, shape=[n_samples, 1], optional verbose", "a point on the manifold \"\"\" if mean_method == 'default':", "return loss def grad(y_pred, y_true, metric): \"\"\"Closed-form for the gradient", "self.inner_product_matrix(base_point) inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3) n_mats = gs.shape(inner_prod_mat)[0] if n_tangent_vec_a", "warnings import autograd import geomstats.backend as gs from geomstats.geometry.connection import", "Returns ------- sq_dist : array-like, shape=[n_samples,] \"\"\" log = self.log(point=point_b,", "gs.einsum('nk,nj->j', weights, logs) next_tangent_mean /= sum_weights norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean) if", "return diameter def closest_neighbor_index(self, point, neighbors): \"\"\"Closest neighbor of point", "'j,njk->nk' elif n_mats == 1: inner_prod_mat = gs.squeeze(inner_prod_mat, axis=0) einsum_str_a", "of iterations {} reached.' 'The mean may be inaccurate'.format(n_max_iterations)) return", "The ' 'mean may be inaccurate'.format(n_max_iterations)) return barycenter def adaptive_gradientdescent_mean(self,", "gs.to_ndarray(points[0], to_ndim=2) if weights is None: weights = gs.ones((n_points, 1))", "math import warnings import autograd import geomstats.backend as gs from", "inner product at the tangent space at a base point.", "= gs.array([[0.]]) last_iteration, mean, variance, sq_dist = gs.while_loop( lambda i,", "self.inner_product_matrix(base_point) cometric_matrix = gs.linalg.inv(metric_matrix) return cometric_matrix def inner_product_derivative_matrix(self, base_point=None): \"\"\"Compute", "current_mean = init_points[0] tau = 1.0 iteration = 0 logs", "= self.squared_norm(vector, base_point) norm = gs.sqrt(sq_norm) return norm def geodesic(self,", "convergence > tau and n_max_iterations > iteration: iteration += 1", "geomstats.geometry.connection import Connection EPSILON = 1e-4 N_CENTERS = 10 TOLERANCE", "NotImplementedError( 'The computation of the inner product matrix' ' is", "may be inaccurate'.format(n_max_iterations)) return gs.to_ndarray(current_mean, to_ndim=2) def diameter(self, points): \"\"\"Give", "grad_tangent.sum(0, keepdims=True), barycenter) convergence = self.dist(cc_barycenter, barycenter).max().item() barycenter = cc_barycenter", "\"\"\"Return the geodesic as function of t. Geodesic curve defined", "gs.squeeze(tangent_vec_a, axis=0) einsum_str_a = 'j,njk->nk' elif n_mats == 1: inner_prod_mat", "shape=[n_samples, 1], optional init_points: array-like, shape=[n_init, dimension] epsilon: tolerance for", "\"\"\" if mean_method == 'default': # TODO(nina): Profile this code", "dist : array-like, shape=[n_samples,] \"\"\" sq_dist = self.squared_dist(point_a, point_b) dist", "super().__init__(dimension=dimension) self.signature = signature def inner_product_matrix(self, base_point=None): \"\"\"Inner product matrix", "base point. Parameters ---------- base_point : array-like, shape=[n_samples, dimension], optional", "norm of a vector. Squared norm of a vector associated", "gs.einsum('nk,nj->j', weights, logs) current_tangent_mean /= sum_weights norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean) while", "sq_dist)) mean = gs.to_ndarray(mean, to_ndim=2) return mean if mean_method ==", "cometric_mat_at_point, metric_derivative_at_point) term_3 = - gs.einsum('nim,nklm->nikl', cometric_mat_at_point, metric_derivative_at_point) christoffels =", "sq: while_loop_cond(i, m, v, sq), lambda i, m, v, sq:", "points: array-like, shape=[n_samples, dimension] weights: array-like, shape=[n_samples, 1], optional \"\"\"", "gs.array(weights) weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) mean", "{} reached. The ' 'mean may be inaccurate'.format(n_max_iterations)) return barycenter", "print('Maximum number of iterations {} reached.' 'The mean may be", "elif point_type == 'matrix': tangent_vecs = gs.einsum('il,nkm->ikm', t, new_initial_tangent_vec) point_at_time_t", "not None: assert gs.allclose(shooting_tangent_vec, initial_tangent_vec) initial_tangent_vec = shooting_tangent_vec initial_tangent_vec =", "mean at x) rather than the mean-square-distance (MSD) because this", "may be inaccurate'.format(n_max_iterations)) return barycenter def adaptive_gradientdescent_mean(self, points, weights=None, n_max_iterations=40,", "points. Parameters ---------- points : array-like, shape=[n_samples, dimension] weights :", "epsilon and iteration < n_max_iterations): iteration = iteration + 1", "norm of a vector. Norm of a vector associated to", "= gs.squeeze(tangent_vec_b, axis=0) einsum_str_b = 'nk,k->n' else: raise ValueError('Shape mismatch", "[] iteration = 0 sq_dist = gs.array([[0.]]) variance = gs.array([[0.]])", "to_ndim=1) variance = gs.to_ndarray(variance, to_ndim=2, axis=1) return variance def mean(self,", "+ 1) if end_point is None and initial_tangent_vec is None:", "1e-3 tau = 5e-3 if len(points) == 1: return points", "def squared_dist(self, point_a, point_b): \"\"\"Squared geodesic distance between two points.", "or shape=[1, dimension] base_point: array-like, shape=[n_samples, dimension] or shape=[1, dimension]", "1): dist_to_neighbors = self.dist(points[i, :], points[i + 1:, :]) dist_to_farthest_neighbor", ": str, optional Returns ------- path : callable \"\"\" point_ndim", "(norm_current_tangent_mean > epsilon and iteration < n_max_iterations): iteration = iteration", "verbose=False): \"\"\"Frechet mean of (weighted) points. Parameters ---------- points :", "axis=1) sum_weights = gs.sum(weights) n_init = len(init_points) if n_init ==", "norm = gs.sqrt(sq_norm) return norm def geodesic(self, initial_point, end_point=None, initial_tangent_vec=None,", "tau * 0.8 if iteration == n_max_iterations: warnings.warn( 'Maximum number", "function parameterized by t. Parameters ---------- initial_point : array-like, shape=[n_samples,", "mean : array-like the Frechet mean of points, a point", "def dist(self, point_a, point_b): \"\"\"Geodesic distance between two points. Note:", "initial_tangent_vec is None: raise ValueError('Specify an end point or an", "= gs.linalg.inv(metric_matrix) return cometric_matrix def inner_product_derivative_matrix(self, base_point=None): \"\"\"Compute derivative of", "= self.variance(points=points, weights=weights, base_point=mean_next) mean = mean_next iteration += 1", "lambda i, m, v, sq: while_loop_cond(i, m, v, sq), lambda", "------- point_at_time_t : callable \"\"\" t = gs.cast(t, gs.float32) t", "a base point. Parameters ---------- base_point : array-like, shape=[n_samples, dimension],", "= 5e-3 if len(points) == 1: return points iteration =", "printing the surrogate value epsilon: tolerance for stopping the gradient", "+= 1 expand_barycenter = gs.repeat(barycenter, points.shape[0], 0) grad_tangent = 2", "and initial_tangent_vec is None: raise ValueError('Specify an end point or", "gs.to_ndarray(mean, to_ndim=3) if n_points == 1: return mean sq_dists_between_iterates =", "= gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) mean = points[0]", "== 1: return gs.to_ndarray(points[0], to_ndim=2) if weights is None: weights", "self.squared_norm(vector=log, base_point=point_a) return sq_dist def dist(self, point_a, point_b): \"\"\"Geodesic distance", "shape=[n_samples, dimension] or shape=[1, dimension] Returns ------- inner_product : array-like,", "initial_tangent_vec = gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim + 1) def path(t): \"\"\"Generate a", "optional \"\"\" if point_type == 'vector': points = gs.to_ndarray(points, to_ndim=2)", "product at the tangent space at a base point. Note:", "warnings.warn( 'Maximum number of iterations {} reached.' 'The mean may", "array-like, shape=[n_samples, 1], optional verbose : bool, optional Returns -------", "symbols associated with the connection. Parameters ---------- base_point: array-like, shape=[n_samples,", "array-like, shape=[n_samples, dimension] or shape=[1, dimension] tangent_vec_b: array-like, shape=[n_samples, dimension]", "= 0. sq_dists = self.squared_dist(base_point, points) variance += gs.einsum('nk,nj->j', weights,", "and the ground truth. Parameters ---------- y_pred y_true metric Returns", "the inner prod matrix at base point. Parameters ---------- base_point", "barycenter).max().item() barycenter = cc_barycenter if iteration == n_max_iterations: warnings.warn( 'Maximum", "t. Parameters ---------- initial_point : array-like, shape=[n_samples, dimension] end_point :", "shape=[n_samples, dimension], optional \"\"\" metric_derivative = autograd.jacobian(self.inner_product_matrix) return metric_derivative(base_point) def", "gs.to_ndarray(end_point, to_ndim=point_ndim + 1) shooting_tangent_vec = self.log(point=end_point, base_point=initial_point) if initial_tangent_vec", "tangent ' 'vector to define the geodesic.') if end_point is", "Loss function given by a Riemannian metric, expressed as the", "sq_dist], maximum_iterations=n_max_iterations) if last_iteration == n_max_iterations: print('Maximum number of iterations", "given by a Riemannian metric, expressed as the squared geodesic", "squared geodesic distance between the prediction and the ground truth.", "to do with sq_dists_between_iterates. def while_loop_cond(iteration, mean, variance, sq_dist): result", "two points that are farthest away from each other in", "dist_to_farthest_neighbor) return diameter def closest_neighbor_index(self, point, neighbors): \"\"\"Closest neighbor of", "RiemannianMetric(Connection): \"\"\"Class for Riemannian and pseudo-Riemannian metrics.\"\"\" def __init__(self, dimension,", "the inner product at the tangent space at a base", "(MSD) because this saves computation time. Parameters ---------- points: array-like,", "'frechet-poincare-ball': lr = 1e-3 tau = 5e-3 if len(points) ==", "vectors at a base point. Parameters ---------- tangent_vec_a: array-like, shape=[n_samples,", "aux = gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat) n_auxs, _ = gs.shape(aux) if", "christoffels def inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None): \"\"\"Inner product between two", "iteration += 1 expand_barycenter = gs.repeat(barycenter, points.shape[0], 0) grad_tangent =", "points. Distance between the two points that are farthest away", "sq_dist = self.squared_dist(mean_next, mean) sq_dists_between_iterates.append(sq_dist) variance = self.variance(points=points, weights=weights, base_point=mean_next)", "self.exp( tangent_vec=shooting_vector, base_point=current_mean) logs = self.log(point=points, base_point=next_mean) next_tangent_mean = gs.einsum('nk,nj->j',", "Returns ------- path : callable \"\"\" point_ndim = 1 if", "cometric_mat_at_point = self.inner_product_inverse_matrix(base_point) metric_derivative_at_point = self.inner_product_derivative_matrix( base_point) term_1 = gs.einsum('nim,nmkl->nikl',", "base_point=None): \"\"\"Inner product matrix at the tangent space at a", "space at a base point. Parameters ---------- vector : array-like,", "array-like, shape=[n_samples,] \"\"\" tangent_vec_a = gs.to_ndarray(tangent_vec_a, to_ndim=2) tangent_vec_b = gs.to_ndarray(tangent_vec_b,", "and n_max_iterations > iteration: iteration += 1 expand_barycenter = gs.repeat(barycenter,", "tangent_vec = metric.log(base_point=y_pred, point=y_true) grad_vec = - 2. * tangent_vec", "t = gs.cast(t, gs.float32) t = gs.to_ndarray(t, to_ndim=1) t =", "= gs.to_ndarray(variance, to_ndim=1) variance = gs.to_ndarray(variance, to_ndim=2, axis=1) return variance", "christoffels = 0.5 * (term_1 + term_2 + term_3) return", "sq_dists_between_iterates.append(sq_dist) variance = self.variance(points=points, weights=weights, base_point=mean_next) mean = mean_next iteration", "metric_derivative_at_point) term_3 = - gs.einsum('nim,nklm->nikl', cometric_mat_at_point, metric_derivative_at_point) christoffels = 0.5", "the ground truth. Parameters ---------- y_pred y_true metric Returns -------", "inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None): \"\"\"Inner product between two tangent vectors", "dimension] Returns ------- christoffels: array-like, shape=[n_samples, dimension, dimension, dimension] \"\"\"", "cc_barycenter if iteration == n_max_iterations: warnings.warn( 'Maximum number of iterations", "Parameters ---------- tangent_vec_a: array-like, shape=[n_samples, dimension] or shape=[1, dimension] tangent_vec_b:", "grad class RiemannianMetric(Connection): \"\"\"Class for Riemannian and pseudo-Riemannian metrics.\"\"\" def", "= gs.einsum('nim,nmkl->nikl', cometric_mat_at_point, metric_derivative_at_point) term_2 = gs.einsum('nim,nmlk->nilk', cometric_mat_at_point, metric_derivative_at_point) term_3", "descent \"\"\" # TODO(Xavier): This function assumes that all points", "= self.inner_product_inverse_matrix(base_point) metric_derivative_at_point = self.inner_product_derivative_matrix( base_point) term_1 = gs.einsum('nim,nmkl->nikl', cometric_mat_at_point,", "between prediction and ground truth. Loss function given by a", "0.0 n_points = points.shape[0] for i in range(n_points - 1):", "= - gs.einsum('nim,nklm->nikl', cometric_mat_at_point, metric_derivative_at_point) christoffels = 0.5 * (term_1", "a function parameterized by t. Parameters ---------- initial_point : array-like,", "= gs.einsum('nk,nj->j', weights, logs) tangent_mean /= sum_weights mean_next = self.exp(", "gs.einsum('nk,nj->j', weights, logs) tangent_mean /= sum_weights mean_next = self.exp( tangent_vec=tangent_mean,", "== 2, inner_prod.shape return inner_prod def squared_norm(self, vector, base_point=None): \"\"\"Compute", "metric): \"\"\"Compute loss function between prediction and ground truth. Loss", "tangent_vec inner_prod_mat = metric.inner_product_matrix(base_point=y_pred) grad = gs.einsum('ni,nij->ni', grad_vec, gs.transpose(inner_prod_mat, axes=(0,", "end point or an initial tangent ' 'vector to define", "= cc_barycenter if iteration == n_max_iterations: warnings.warn( 'Maximum number of", "sq_dist): logs = self.log(point=points, base_point=mean) tangent_mean = gs.einsum('nk,nj->j', weights, logs)", "path(t): \"\"\"Generate a function parameterizing the geodesic. Parameters ---------- t", "'vector': points = gs.to_ndarray(points, to_ndim=2) if point_type == 'matrix': points", "Christoffel symbols associated with the connection. Parameters ---------- base_point: array-like,", "number of iterations {} reached.' 'The mean may be inaccurate'.format(n_max_iterations))", "n_max_iterations=32, epsilon=EPSILON, point_type='vector', mean_method='default', verbose=False): \"\"\"Frechet mean of (weighted) points.", "dimension] base_point : array-like, shape=[n_samples, dimension] Returns ------- sq_norm :", "be inaccurate'.format(n_max_iterations)) return barycenter def adaptive_gradientdescent_mean(self, points, weights=None, n_max_iterations=40, epsilon=1e-12,", "= 'nj,njk->nk' aux = gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat) n_auxs, _ =", "the gradient descent verbose: verbose mode printing the surrogate value", "than the mean-square-distance (MSD) because this saves computation time. Parameters", "variance def mean(self, points, weights=None, n_max_iterations=32, epsilon=EPSILON, point_type='vector', mean_method='default', verbose=False):", "and pseudo-Riemannian metrics.\"\"\" import math import warnings import autograd import", "initial_tangent_vec=None, point_type='vector'): \"\"\"Return the geodesic as function of t. Geodesic", "point_at_time_t : callable \"\"\" t = gs.cast(t, gs.float32) t =", "self.inner_product_inverse_matrix(base_point) metric_derivative_at_point = self.inner_product_derivative_matrix( base_point) term_1 = gs.einsum('nim,nmkl->nikl', cometric_mat_at_point, metric_derivative_at_point)", "* (term_1 + term_2 + term_3) return christoffels def inner_product(self,", "points[0] if point_type == 'vector': mean = gs.to_ndarray(mean, to_ndim=2) if", "array-like, shape=[n_samples, dimension] Returns ------- christoffels: array-like, shape=[n_samples, dimension, dimension,", "= 'nk,k->n' else: raise ValueError('Shape mismatch for einsum.') else: einsum_str_b", "/= sum_weights mean_next = self.exp( tangent_vec=tangent_mean, base_point=mean) sq_dist = self.squared_dist(mean_next,", "weights=weights, base_point=mean_next) mean = mean_next iteration += 1 return [iteration,", "N_REPETITIONS = 20 N_MAX_ITERATIONS = 50000 N_STEPS = 10 def", "not implemented.') def inner_product_inverse_matrix(self, base_point=None): \"\"\"Inner product matrix at the", "between two points. Note: It only works for positive definite", "= gs.shape(inner_prod_mat)[0] if n_tangent_vec_a != n_mats: if n_tangent_vec_a == 1:", "or shape=[1, dimension] tangent_vec_b: array-like, shape=[n_samples, dimension] or shape=[1, dimension]", "norm_next_tangent_mean < norm_current_tangent_mean: current_mean = next_mean current_tangent_mean = next_tangent_mean norm_current_tangent_mean", "n_auxs == 1: aux = gs.squeeze(aux, axis=0) einsum_str_b = 'k,nk->n'", "and pseudo-Riemannian metrics.\"\"\" def __init__(self, dimension, signature=None): assert isinstance(dimension, int)", "= gs.array(variance) variance /= sum_weights variance = gs.to_ndarray(variance, to_ndim=1) variance", "Parameters ---------- point_a : array-like, shape=[n_samples, dimension] point_b : array-like,", "using adaptive time-steps The loss function optimized is ||M_1(x)||_x (where", "optional \"\"\" raise NotImplementedError( 'The computation of the inner product", "initial tangent ' 'vector to define the geodesic.') if end_point", "N_CENTERS = 10 TOLERANCE = 1e-5 N_REPETITIONS = 20 N_MAX_ITERATIONS", "gs.to_ndarray(points, to_ndim=3) n_points = gs.shape(points)[0] if weights is None: weights", "is None and initial_tangent_vec is None: raise ValueError('Specify an end", "TODO(nina): Profile this code to study performance, # i.e. what", "if last_iteration == n_max_iterations: print('Maximum number of iterations {} reached.'", "50000 N_STEPS = 10 def loss(y_pred, y_true, metric): \"\"\"Compute loss", "logs = self.log(point=points, base_point=current_mean) current_tangent_mean = gs.einsum('nk,nj->j', weights, logs) current_tangent_mean", "the tangent space at a base point. Parameters ---------- base_point", "None: base_point = self.mean(points, weights) variance = 0. sq_dists =", "\"\"\" metric_derivative = autograd.jacobian(self.inner_product_matrix) return metric_derivative(base_point) def christoffels(self, base_point): \"\"\"Compute", "a vector. Squared norm of a vector associated to the", "Returns ------- loss \"\"\" loss = metric.squared_dist(y_pred, y_true) return loss", "Returns ------- diameter \"\"\" diameter = 0.0 n_points = points.shape[0]", "if mean_method == 'frechet-poincare-ball': lr = 1e-3 tau = 5e-3", "gs.linalg.norm(next_tangent_mean) if verbose: print( \"Iter {0}: tau= {1}, \" \"norm_current_tangent_mean", "y_true, metric): \"\"\"Closed-form for the gradient of the loss function.\"\"\"", "base_point=initial_point) if initial_tangent_vec is not None: assert gs.allclose(shooting_tangent_vec, initial_tangent_vec) initial_tangent_vec", "= gs.einsum('ni,nij->ni', grad_vec, gs.transpose(inner_prod_mat, axes=(0, 2, 1))) return grad class", "if point_type == 'matrix': point_ndim = 2 initial_point = gs.to_ndarray(initial_point,", "mean, variance, sq_dist] if point_type == 'vector': points = gs.to_ndarray(points,", "gs.to_ndarray(mean, to_ndim=2) if point_type == 'matrix': mean = gs.to_ndarray(mean, to_ndim=3)", "only works for positive definite Riemannian metrics. Parameters ---------- point_a", "dist = gs.sqrt(sq_dist) return dist def variance(self, points, weights=None, base_point=None,", "initial point and an initial tangent vector, or - an", "int) or dimension == math.inf assert dimension > 0 super().__init__(dimension=dimension)", "self.exp(lr * grad_tangent.sum(0, keepdims=True), barycenter) convergence = self.dist(cc_barycenter, barycenter).max().item() barycenter", "= metric.inner_product_matrix(base_point=y_pred) grad = gs.einsum('ni,nij->ni', grad_vec, gs.transpose(inner_prod_mat, axes=(0, 2, 1)))", "tangent space at a base point. Parameters ---------- vector :", "dimension], optional \"\"\" metric_matrix = self.inner_product_matrix(base_point) cometric_matrix = gs.linalg.inv(metric_matrix) return", "matrices n_points = gs.shape(points)[0] if n_points == 1: return gs.to_ndarray(points[0],", "Note: This only works for positive-definite Riemannian metrics and inner", "variance = self.variance(points=points, weights=weights, base_point=mean_next) mean = mean_next iteration +=", "geomstats.backend as gs from geomstats.geometry.connection import Connection EPSILON = 1e-4", "gs.allclose(shooting_tangent_vec, initial_tangent_vec) initial_tangent_vec = shooting_tangent_vec initial_tangent_vec = gs.array(initial_tangent_vec) initial_tangent_vec =", "gs.to_ndarray(initial_point, to_ndim=point_ndim + 1) if end_point is None and initial_tangent_vec", "at a base point. Parameters ---------- base_point : array-like, shape=[n_samples,", "optional initial_tangent_vec : array-like, shape=[n_samples, dimension], optional point_type : str,", "2. * tangent_vec inner_prod_mat = metric.inner_product_matrix(base_point=y_pred) grad = gs.einsum('ni,nij->ni', grad_vec,", "metric): \"\"\"Closed-form for the gradient of the loss function.\"\"\" tangent_vec", "shape=[n_samples, dimension], optional \"\"\" raise NotImplementedError( 'The computation of the", "expand_barycenter = gs.repeat(barycenter, points.shape[0], 0) grad_tangent = 2 * self.log(points,", "for positive definite Riemannian metrics. Parameters ---------- point_a : array-like,", "value epsilon: tolerance for stopping the gradient descent \"\"\" #", "\"\"\" sq_norm = self.inner_product(vector, vector, base_point) return sq_norm def norm(self,", "initial tangent vector, or - an initial point and an", "metric_derivative_at_point = self.inner_product_derivative_matrix( base_point) term_1 = gs.einsum('nim,nmkl->nikl', cometric_mat_at_point, metric_derivative_at_point) term_2", "verbose: verbose mode printing the surrogate value epsilon: tolerance for", "parameterized by t. Parameters ---------- initial_point : array-like, shape=[n_samples, dimension]", "Frechet mean of points, a point on the manifold \"\"\"", "function of t. Geodesic curve defined by either: - an", "assert isinstance(dimension, int) or dimension == math.inf assert dimension >", "variance = 0. sq_dists = self.squared_dist(base_point, points) variance += gs.einsum('nk,nj->j',", "point_type == 'matrix': mean = gs.to_ndarray(mean, to_ndim=3) if n_points ==", "vector, base_point=None): \"\"\"Compute norm of a vector. Norm of a", "diameter = 0.0 n_points = points.shape[0] for i in range(n_points", "y_true, metric): \"\"\"Compute loss function between prediction and ground truth.", "shooting_tangent_vec initial_tangent_vec = gs.array(initial_tangent_vec) initial_tangent_vec = gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim + 1)", "== 1: return points iteration = 0 convergence = math.inf", "N_MAX_ITERATIONS = 50000 N_STEPS = 10 def loss(y_pred, y_true, metric):", "of (weighted) points wrt a base point. Parameters ---------- points:", "result = ~gs.logical_or( gs.isclose(variance, 0.), gs.less_equal(sq_dist, epsilon * variance)) return", "mean may be inaccurate'.format(n_max_iterations)) return gs.to_ndarray(current_mean, to_ndim=2) def diameter(self, points):", "---------- point_a : array-like, shape=[n_samples, dimension] point_b : array-like, shape=[n_samples,", "' 'mean may be inaccurate'.format(n_max_iterations)) return barycenter def adaptive_gradientdescent_mean(self, points,", "0) grad_tangent = 2 * self.log(points, expand_barycenter) cc_barycenter = self.exp(lr", "loss def grad(y_pred, y_true, metric): \"\"\"Closed-form for the gradient of", "n_tangent_vec_b = gs.shape(tangent_vec_b)[0] inner_prod_mat = self.inner_product_matrix(base_point) inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3)", "christoffels: array-like, shape=[n_samples, dimension, dimension, dimension] \"\"\" cometric_mat_at_point = self.inner_product_inverse_matrix(base_point)", "if base_point is None: base_point = self.mean(points, weights) variance =", "= ~gs.logical_or( gs.isclose(variance, 0.), gs.less_equal(sq_dist, epsilon * variance)) return result[0,", "n_tangent_vec_a = gs.shape(tangent_vec_a)[0] n_tangent_vec_b = gs.shape(tangent_vec_b)[0] inner_prod_mat = self.inner_product_matrix(base_point) inner_prod_mat", "points: array-like, shape=[n_samples, dimension] weights: array-like, shape=[n_samples, 1], optional init_points:", "at the tangent space at a base point. Parameters ----------", "1) if point_type == 'vector': tangent_vecs = gs.einsum('il,nk->ik', t, new_initial_tangent_vec)", "number of iterations {} reached. The ' 'mean may be", "Geodesic curve defined by either: - an initial point and", "initial_point, end_point=None, initial_tangent_vec=None, point_type='vector'): \"\"\"Return the geodesic as function of", "\"\"\" sq_norm = self.squared_norm(vector, base_point) norm = gs.sqrt(sq_norm) return norm", "ValueError('Shape mismatch for einsum.') else: einsum_str_a = 'nj,njk->nk' aux =", "aux, tangent_vec_b) inner_prod = gs.to_ndarray(inner_prod, to_ndim=2, axis=1) assert gs.ndim(inner_prod) ==", "geodesic distance between the prediction and the ground truth. Parameters", "1 if point_type == 'matrix': point_ndim = 2 initial_point =", "computation time. Parameters ---------- points: array-like, shape=[n_samples, dimension] weights: array-like,", "dimension] Returns ------- sq_dist : array-like, shape=[n_samples,] \"\"\" log =", "------- sq_dist : array-like, shape=[n_samples,] \"\"\" log = self.log(point=point_b, base_point=point_a)", "reached.' 'The mean may be inaccurate'.format(n_max_iterations)) if verbose: print('n_iter: {},", "gs.to_ndarray(points, to_ndim=2) if point_type == 'matrix': points = gs.to_ndarray(points, to_ndim=3)", "= gs.einsum('il,nk->ik', t, new_initial_tangent_vec) elif point_type == 'matrix': tangent_vecs =", "by t. Parameters ---------- initial_point : array-like, shape=[n_samples, dimension] end_point", "* 0 while convergence > tau and n_max_iterations > iteration:", "weights=None, n_max_iterations=32, epsilon=EPSILON, point_type='vector', mean_method='default', verbose=False): \"\"\"Frechet mean of (weighted)", "\"\"\"Compute derivative of the inner prod matrix at base point.", "inner_prod.shape return inner_prod def squared_norm(self, vector, base_point=None): \"\"\"Compute the square", "1e-4 N_CENTERS = 10 TOLERANCE = 1e-5 N_REPETITIONS = 20", "1: tangent_vec_a = gs.squeeze(tangent_vec_a, axis=0) einsum_str_a = 'j,njk->nk' elif n_mats", "an end point. The geodesic is returned as a function", "Returns ------- inner_product : array-like, shape=[n_samples,] \"\"\" tangent_vec_a = gs.to_ndarray(tangent_vec_a,", "sum_weights norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean) while (norm_current_tangent_mean > epsilon and iteration", "if len(points) == 1: return points iteration = 0 convergence", "while_loop_body(iteration, mean, variance, sq_dist): logs = self.log(point=points, base_point=mean) tangent_mean =", "while_loop_cond(iteration, mean, variance, sq_dist): result = ~gs.logical_or( gs.isclose(variance, 0.), gs.less_equal(sq_dist,", "dimension] Returns ------- norm : array-like, shape=[n_samples,] \"\"\" sq_norm =", "the loss function.\"\"\" tangent_vec = metric.log(base_point=y_pred, point=y_true) grad_vec = -", "The geodesic is returned as a function parameterized by t.", "grad(y_pred, y_true, metric): \"\"\"Closed-form for the gradient of the loss", "mean_next iteration += 1 return [iteration, mean, variance, sq_dist] if", "vector associated to the inner product at the tangent space", "inner_prod = gs.einsum(einsum_str_b, aux, tangent_vec_b) inner_prod = gs.to_ndarray(inner_prod, to_ndim=2, axis=1)", "0] or iteration == 0 def while_loop_body(iteration, mean, variance, sq_dist):", "descent verbose: verbose mode printing the surrogate value epsilon: tolerance", "gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim + 1) def path(t): \"\"\"Generate a function parameterizing", "if n_init == 0: current_mean = points[0] else: current_mean =", "the prediction and the ground truth. Parameters ---------- y_pred y_true", "mismatch for einsum.') else: einsum_str_b = 'nk,nk->n' inner_prod = gs.einsum(einsum_str_b,", "inner_product_matrix(self, base_point=None): \"\"\"Inner product matrix at the tangent space at", "= gs.to_ndarray(variance, to_ndim=2, axis=1) return variance def mean(self, points, weights=None,", "current_mean = points[0] else: current_mean = init_points[0] tau = 1.0", "vector, or - an initial point and an end point.", "sq_dist = gs.array([[0.]]) variance = gs.array([[0.]]) last_iteration, mean, variance, sq_dist", "pseudo-Riemannian metrics.\"\"\" import math import warnings import autograd import geomstats.backend", "sum_weights mean_next = self.exp( tangent_vec=tangent_mean, base_point=mean) sq_dist = self.squared_dist(mean_next, mean)", "> 0 super().__init__(dimension=dimension) self.signature = signature def inner_product_matrix(self, base_point=None): \"\"\"Inner", "array-like, shape=[n_samples, dimension] point_b : array-like, shape=[n_samples, dimension] Returns -------", "logs) current_tangent_mean /= sum_weights norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean) while (norm_current_tangent_mean >", "two points. Note: It only works for positive definite Riemannian", "mean, variance, sq_dist): result = ~gs.logical_or( gs.isclose(variance, 0.), gs.less_equal(sq_dist, epsilon", "return mean if mean_method == 'frechet-poincare-ball': lr = 1e-3 tau", "between two farthest points. Distance between the two points that", "mismatch for einsum.') else: einsum_str_a = 'nj,njk->nk' aux = gs.einsum(einsum_str_a,", "Frechet mean of (weighted) points using adaptive time-steps. Frechet mean", "= gs.shape(tangent_vec_a)[0] n_tangent_vec_b = gs.shape(tangent_vec_b)[0] inner_prod_mat = self.inner_product_matrix(base_point) inner_prod_mat =", "dimension] base_point: array-like, shape=[n_samples, dimension] or shape=[1, dimension] Returns -------", "'matrix': points = gs.to_ndarray(points, to_ndim=3) n_points = gs.shape(points)[0] if weights", "base_point is None: base_point = self.mean(points, weights) variance = 0.", "bool, optional Returns ------- mean : array-like the Frechet mean", "\"\"\"Geodesic distance between two points. Note: It only works for", "point. Note: This only works for positive-definite Riemannian metrics and", "may be inaccurate'.format(n_max_iterations)) if verbose: print('n_iter: {}, final variance: {},", "points = gs.to_ndarray(points, to_ndim=2) if point_type == 'matrix': points =", "len(init_points) if n_init == 0: current_mean = points[0] else: current_mean", "gs.shape(points)[0] if n_points == 1: return gs.to_ndarray(points[0], to_ndim=2) if weights", "point_b): \"\"\"Squared geodesic distance between two points. Parameters ---------- point_a", "the tangent space at a base point. Note: This only", "import autograd import geomstats.backend as gs from geomstats.geometry.connection import Connection", "or an initial tangent ' 'vector to define the geodesic.')", "to_ndim=2, axis=1) sum_weights = gs.sum(weights) n_init = len(init_points) if n_init", "metric_derivative_at_point) term_2 = gs.einsum('nim,nmlk->nilk', cometric_mat_at_point, metric_derivative_at_point) term_3 = - gs.einsum('nim,nklm->nikl',", "tau and n_max_iterations > iteration: iteration += 1 expand_barycenter =", "= signature def inner_product_matrix(self, base_point=None): \"\"\"Inner product matrix at the", "verbose mode printing the surrogate value epsilon: tolerance for stopping", "shape=[n_samples, dimension] or shape=[1, dimension] tangent_vec_b: array-like, shape=[n_samples, dimension] or", "verbose: print('n_iter: {}, final variance: {}, final dist: {}'.format( last_iteration,", "all points are lists # of vectors and not of", "point_a, point_b): \"\"\"Squared geodesic distance between two points. Parameters ----------", "an initial tangent ' 'vector to define the geodesic.') if", "at a base point. Parameters ---------- vector : array-like, shape=[n_samples,", "an end point or an initial tangent ' 'vector to", "to_ndim=point_ndim + 1) def path(t): \"\"\"Generate a function parameterizing the", "at a base point. Note: This only works for positive-definite", "base_point : array-like, shape=[n_samples, dimension] Returns ------- sq_norm : array-like,", "to_ndim=2) if point_type == 'matrix': mean = gs.to_ndarray(mean, to_ndim=3) if", "mean of (weighted) points. Parameters ---------- points : array-like, shape=[n_samples,", "self.squared_dist(mean_next, mean) sq_dists_between_iterates.append(sq_dist) variance = self.variance(points=points, weights=weights, base_point=mean_next) mean =", "= gs.sqrt(sq_dist) return dist def variance(self, points, weights=None, base_point=None, point_type='vector'):", "!= n_auxs: if n_auxs == 1: aux = gs.squeeze(aux, axis=0)", "init_points=[], verbose=False): \"\"\"Compute Frechet mean of (weighted) points using adaptive", "loss function.\"\"\" tangent_vec = metric.log(base_point=y_pred, point=y_true) grad_vec = - 2.", "a base point. Note: This only works for positive-definite Riemannian", "initial_point : array-like, shape=[n_samples, dimension] end_point : array-like, shape=[n_samples, dimension],", "---------- points Returns ------- diameter \"\"\" diameter = 0.0 n_points", "metrics. Parameters ---------- point_a : array-like, shape=[n_samples, dimension] point_b :", "inner prod matrix at base point. Parameters ---------- base_point :", "Parameters ---------- base_point: array-like, shape=[n_samples, dimension] Returns ------- christoffels: array-like,", "optimized is ||M_1(x)||_x (where M_1(x) is the tangent mean at", "diameter = gs.maximum(diameter, dist_to_farthest_neighbor) return diameter def closest_neighbor_index(self, point, neighbors):", "as a function parameterized by t. Parameters ---------- initial_point :", "and an end point. The geodesic is returned as a", ": array-like, shape=[n_samples,] \"\"\" log = self.log(point=point_b, base_point=point_a) sq_dist =", "the Frechet mean of points, a point on the manifold", "= gs.to_ndarray(end_point, to_ndim=point_ndim + 1) shooting_tangent_vec = self.log(point=end_point, base_point=initial_point) if", "== 'matrix': tangent_vecs = gs.einsum('il,nkm->ikm', t, new_initial_tangent_vec) point_at_time_t = self.exp(tangent_vec=tangent_vecs,", "== 'vector': mean = gs.to_ndarray(mean, to_ndim=2) if point_type == 'matrix':", "self.log(point=end_point, base_point=initial_point) if initial_tangent_vec is not None: assert gs.allclose(shooting_tangent_vec, initial_tangent_vec)", "if weights is None: weights = gs.ones((n_points, 1)) weights =", "on the manifold \"\"\" if mean_method == 'default': # TODO(nina):", "loop_vars=[iteration, mean, variance, sq_dist], maximum_iterations=n_max_iterations) if last_iteration == n_max_iterations: print('Maximum", "sq_dist): result = ~gs.logical_or( gs.isclose(variance, 0.), gs.less_equal(sq_dist, epsilon * variance))", "point_b : array-like, shape=[n_samples, dimension] Returns ------- sq_dist : array-like,", "= gs.to_ndarray( initial_tangent_vec, to_ndim=point_ndim + 1) if point_type == 'vector':", "matrix at base point. Parameters ---------- base_point : array-like, shape=[n_samples,", "= gs.ones((n_points, 1)) weights = gs.array(weights) weights = gs.to_ndarray(weights, to_ndim=2,", "t. Geodesic curve defined by either: - an initial point", "function between prediction and ground truth. Loss function given by", "dimension], optional \"\"\" metric_derivative = autograd.jacobian(self.inner_product_matrix) return metric_derivative(base_point) def christoffels(self,", "tangent space at a base point. Parameters ---------- base_point :", "of the inner prod matrix at base point. Parameters ----------", "= 0 logs = self.log(point=points, base_point=current_mean) current_tangent_mean = gs.einsum('nk,nj->j', weights,", "self.log(point=points, base_point=current_mean) current_tangent_mean = gs.einsum('nk,nj->j', weights, logs) current_tangent_mean /= sum_weights", "norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean) if verbose: print( \"Iter {0}: tau= {1},", "{2}\".format( iter, tau, norm_current_tangent_mean)) if norm_next_tangent_mean < norm_current_tangent_mean: current_mean =", "base_point) norm = gs.sqrt(sq_norm) return norm def geodesic(self, initial_point, end_point=None,", "point_b : array-like, shape=[n_samples, dimension] Returns ------- dist : array-like,", "= next_mean current_tangent_mean = next_tangent_mean norm_current_tangent_mean = norm_next_tangent_mean tau =", "+ 1) def path(t): \"\"\"Generate a function parameterizing the geodesic.", "= 10 def loss(y_pred, y_true, metric): \"\"\"Compute loss function between", "signature def inner_product_matrix(self, base_point=None): \"\"\"Inner product matrix at the tangent", "time-steps. Frechet mean of (weighted) points using adaptive time-steps The", "iteration = iteration + 1 shooting_vector = gs.to_ndarray( tau *", "1) def path(t): \"\"\"Generate a function parameterizing the geodesic. Parameters", "= self.log(point=points, base_point=current_mean) current_tangent_mean = gs.einsum('nk,nj->j', weights, logs) current_tangent_mean /=", "distance between two farthest points. Distance between the two points", "= 0 sq_dist = gs.array([[0.]]) variance = gs.array([[0.]]) last_iteration, mean,", "1)) weights = gs.array(weights) weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights", "optional verbose : bool, optional Returns ------- mean : array-like", "point_a, point_b): \"\"\"Geodesic distance between two points. Note: It only", "gs.linalg.inv(metric_matrix) return cometric_matrix def inner_product_derivative_matrix(self, base_point=None): \"\"\"Compute derivative of the", "gs.to_ndarray( initial_point, to_ndim=point_ndim + 1) new_initial_tangent_vec = gs.to_ndarray( initial_tangent_vec, to_ndim=point_ndim", "Riemannian and pseudo-Riemannian metrics.\"\"\" def __init__(self, dimension, signature=None): assert isinstance(dimension,", "geodesic is returned as a function parameterized by t. Parameters", "axis=0) einsum_str_a = 'j,njk->nk' elif n_mats == 1: inner_prod_mat =", "base_point=point_a) return sq_dist def dist(self, point_a, point_b): \"\"\"Geodesic distance between", "if verbose: print('n_iter: {}, final variance: {}, final dist: {}'.format(", "shape=[n_samples,] \"\"\" sq_dist = self.squared_dist(point_a, point_b) dist = gs.sqrt(sq_dist) return", "n_points = points.shape[0] for i in range(n_points - 1): dist_to_neighbors", "sq_norm def norm(self, vector, base_point=None): \"\"\"Compute norm of a vector.", "and inner products. Parameters ---------- vector : array-like, shape=[n_samples, dimension]", "= gs.to_ndarray(initial_point, to_ndim=point_ndim + 1) if end_point is None and", "self.dist(cc_barycenter, barycenter).max().item() barycenter = cc_barycenter if iteration == n_max_iterations: warnings.warn(", "verbose: print( \"Iter {0}: tau= {1}, \" \"norm_current_tangent_mean = {2}\".format(", "to_ndim=2) def diameter(self, points): \"\"\"Give the distance between two farthest", "norm def geodesic(self, initial_point, end_point=None, initial_tangent_vec=None, point_type='vector'): \"\"\"Return the geodesic", "This function assumes that all points are lists # of", "the geodesic Returns ------- point_at_time_t : callable \"\"\" t =", "Distance between the two points that are farthest away from", "/= sum_weights variance = gs.to_ndarray(variance, to_ndim=1) variance = gs.to_ndarray(variance, to_ndim=2,", "inaccurate'.format(n_max_iterations)) if verbose: print('n_iter: {}, final variance: {}, final dist:", "base_point=mean) sq_dist = self.squared_dist(mean_next, mean) sq_dists_between_iterates.append(sq_dist) variance = self.variance(points=points, weights=weights,", "shooting_tangent_vec = self.log(point=end_point, base_point=initial_point) if initial_tangent_vec is not None: assert", "weights = gs.ones((n_points, 1)) weights = gs.array(weights) weights = gs.to_ndarray(weights,", "== 1: tangent_vec_b = gs.squeeze(tangent_vec_b, axis=0) einsum_str_b = 'nk,k->n' else:", "None: end_point = gs.to_ndarray(end_point, to_ndim=point_ndim + 1) shooting_tangent_vec = self.log(point=end_point,", "product at the tangent space at a base point. Parameters", "1: return mean sq_dists_between_iterates = [] iteration = 0 sq_dist", "sq_norm = self.squared_norm(vector, base_point) norm = gs.sqrt(sq_norm) return norm def", "---------- base_point : array-like, shape=[n_samples, dimension], optional \"\"\" raise NotImplementedError(", "It only works for positive definite Riemannian metrics. Parameters ----------", "of vectors and not of matrices n_points = gs.shape(points)[0] if", "initial_tangent_vec = gs.array(initial_tangent_vec) initial_tangent_vec = gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim + 1) def", "tangent_vec_a = gs.to_ndarray(tangent_vec_a, to_ndim=2) tangent_vec_b = gs.to_ndarray(tangent_vec_b, to_ndim=2) n_tangent_vec_a =", "= gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim + 1) def path(t): \"\"\"Generate a function", "final variance: {}, final dist: {}'.format( last_iteration, variance, sq_dist)) mean", "tau, norm_current_tangent_mean)) if norm_next_tangent_mean < norm_current_tangent_mean: current_mean = next_mean current_tangent_mean", "\"\"\" sq_dist = self.squared_dist(point_a, point_b) dist = gs.sqrt(sq_dist) return dist", "weights) variance = 0. sq_dists = self.squared_dist(base_point, points) variance +=", "1: inner_prod_mat = gs.squeeze(inner_prod_mat, axis=0) einsum_str_a = 'nj,jk->nk' else: raise", "mean = gs.to_ndarray(mean, to_ndim=2) if point_type == 'matrix': mean =", "matrix' ' is not implemented.') def inner_product_inverse_matrix(self, base_point=None): \"\"\"Inner product", "and an initial tangent vector, or - an initial point", "variance, sq_dist): result = ~gs.logical_or( gs.isclose(variance, 0.), gs.less_equal(sq_dist, epsilon *", "with the connection. Parameters ---------- base_point: array-like, shape=[n_samples, dimension] Returns", "= 2 * self.log(points, expand_barycenter) cc_barycenter = self.exp(lr * grad_tangent.sum(0,", "the surrogate value epsilon: tolerance for stopping the gradient descent", "gs.to_ndarray( initial_tangent_vec, to_ndim=point_ndim + 1) if point_type == 'vector': tangent_vecs", "= gs.einsum('nk,nj->j', weights, logs) next_tangent_mean /= sum_weights norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean)", "i, m, v, sq: while_loop_body(i, m, v, sq), loop_vars=[iteration, mean,", "= mean_next iteration += 1 return [iteration, mean, variance, sq_dist]", "function optimized is ||M_1(x)||_x (where M_1(x) is the tangent mean", "point, neighbors): \"\"\"Closest neighbor of point among neighbors. Parameters ----------", "ValueError('Specify an end point or an initial tangent ' 'vector", "geodesic. Parameters ---------- t : parameter value of the geodesic", "+ 1) shooting_tangent_vec = self.log(point=end_point, base_point=initial_point) if initial_tangent_vec is not", ": bool, optional Returns ------- mean : array-like the Frechet", ": array-like, shape=[n_samples,] \"\"\" sq_dist = self.squared_dist(point_a, point_b) dist =", "def inner_product_inverse_matrix(self, base_point=None): \"\"\"Inner product matrix at the tangent space", "cometric_matrix def inner_product_derivative_matrix(self, base_point=None): \"\"\"Compute derivative of the inner prod", "= gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat) n_auxs, _ = gs.shape(aux) if n_tangent_vec_b", "\"\"\" raise NotImplementedError( 'The computation of the inner product matrix'", "1.0511111 * tau) else: tau = tau * 0.8 if", "weights, logs) tangent_mean /= sum_weights mean_next = self.exp( tangent_vec=tangent_mean, base_point=mean)", "for einsum.') else: einsum_str_b = 'nk,nk->n' inner_prod = gs.einsum(einsum_str_b, aux,", "end_point = gs.to_ndarray(end_point, to_ndim=point_ndim + 1) shooting_tangent_vec = self.log(point=end_point, base_point=initial_point)", "current_tangent_mean /= sum_weights norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean) while (norm_current_tangent_mean > epsilon", "reached.' 'The mean may be inaccurate'.format(n_max_iterations)) return gs.to_ndarray(current_mean, to_ndim=2) def", "barycenter) convergence = self.dist(cc_barycenter, barycenter).max().item() barycenter = cc_barycenter if iteration", "definite Riemannian metrics. Parameters ---------- point_a : array-like, shape=[n_samples, dimension]", "assert gs.ndim(inner_prod) == 2, inner_prod.shape return inner_prod def squared_norm(self, vector,", "self.log(point=points, base_point=mean) tangent_mean = gs.einsum('nk,nj->j', weights, logs) tangent_mean /= sum_weights", "diameter(self, points): \"\"\"Give the distance between two farthest points. Distance", "5e-3 if len(points) == 1: return points iteration = 0", "tolerance for stopping the gradient descent \"\"\" # TODO(Xavier): This", "to define the geodesic.') if end_point is not None: end_point", "2 * self.log(points, expand_barycenter) cc_barycenter = self.exp(lr * grad_tangent.sum(0, keepdims=True),", "current_tangent_mean, to_ndim=2) next_mean = self.exp( tangent_vec=shooting_vector, base_point=current_mean) logs = self.log(point=points,", "print('n_iter: {}, final variance: {}, final dist: {}'.format( last_iteration, variance,", "tangent_vec_b = gs.to_ndarray(tangent_vec_b, to_ndim=2) n_tangent_vec_a = gs.shape(tangent_vec_a)[0] n_tangent_vec_b = gs.shape(tangent_vec_b)[0]", "verbose=False): \"\"\"Compute Frechet mean of (weighted) points using adaptive time-steps.", "metrics.\"\"\" import math import warnings import autograd import geomstats.backend as", "< norm_current_tangent_mean: current_mean = next_mean current_tangent_mean = next_tangent_mean norm_current_tangent_mean =", "of the norm of a vector. Squared norm of a", "points, weights=None, n_max_iterations=40, epsilon=1e-12, init_points=[], verbose=False): \"\"\"Compute Frechet mean of", "The loss function optimized is ||M_1(x)||_x (where M_1(x) is the", "einsum_str_a = 'j,njk->nk' elif n_mats == 1: inner_prod_mat = gs.squeeze(inner_prod_mat,", "0 logs = self.log(point=points, base_point=current_mean) current_tangent_mean = gs.einsum('nk,nj->j', weights, logs)", "cometric_mat_at_point, metric_derivative_at_point) term_2 = gs.einsum('nim,nmlk->nilk', cometric_mat_at_point, metric_derivative_at_point) term_3 = -", "grad = gs.einsum('ni,nij->ni', grad_vec, gs.transpose(inner_prod_mat, axes=(0, 2, 1))) return grad", "iteration == n_max_iterations: warnings.warn( 'Maximum number of iterations {} reached.", "gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) n_init = len(init_points) if", "inner_prod_mat = metric.inner_product_matrix(base_point=y_pred) grad = gs.einsum('ni,nij->ni', grad_vec, gs.transpose(inner_prod_mat, axes=(0, 2,", "point. The geodesic is returned as a function parameterized by", "- an initial point and an initial tangent vector, or", "do with sq_dists_between_iterates. def while_loop_cond(iteration, mean, variance, sq_dist): result =", "what to do with sq_dists_between_iterates. def while_loop_cond(iteration, mean, variance, sq_dist):", "import Connection EPSILON = 1e-4 N_CENTERS = 10 TOLERANCE =", "= gs.shape(aux) if n_tangent_vec_b != n_auxs: if n_auxs == 1:", "def christoffels(self, base_point): \"\"\"Compute Christoffel symbols associated with the connection.", "n_points == 1: return mean sq_dists_between_iterates = [] iteration =", "define the geodesic.') if end_point is not None: end_point =", "variance += gs.einsum('nk,nj->j', weights, sq_dists) variance = gs.array(variance) variance /=", "= gs.while_loop( lambda i, m, v, sq: while_loop_cond(i, m, v,", "prod matrix at base point. Parameters ---------- base_point : array-like,", "= shooting_tangent_vec initial_tangent_vec = gs.array(initial_tangent_vec) initial_tangent_vec = gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim +", "associated to the inner product at the tangent space at", "if point_type == 'vector': mean = gs.to_ndarray(mean, to_ndim=2) if point_type", "Parameters ---------- base_point : array-like, shape=[n_samples, dimension], optional \"\"\" metric_matrix", "0 super().__init__(dimension=dimension) self.signature = signature def inner_product_matrix(self, base_point=None): \"\"\"Inner product", "0 convergence = math.inf barycenter = points.mean(0, keepdims=True) * 0", "= gs.cast(t, gs.float32) t = gs.to_ndarray(t, to_ndim=1) t = gs.to_ndarray(t,", "iteration += 1 return [iteration, mean, variance, sq_dist] if point_type", "performance, # i.e. what to do with sq_dists_between_iterates. def while_loop_cond(iteration,", "weights, logs) next_tangent_mean /= sum_weights norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean) if verbose:", "derivative of the inner prod matrix at base point. Parameters", "'nj,njk->nk' aux = gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat) n_auxs, _ = gs.shape(aux)", "0.8 if iteration == n_max_iterations: warnings.warn( 'Maximum number of iterations", "geodesic(self, initial_point, end_point=None, initial_tangent_vec=None, point_type='vector'): \"\"\"Return the geodesic as function", "dist(self, point_a, point_b): \"\"\"Geodesic distance between two points. Note: It", "Returns ------- norm : array-like, shape=[n_samples,] \"\"\" sq_norm = self.squared_norm(vector,", "space at a base point. Note: This only works for", "of the loss function.\"\"\" tangent_vec = metric.log(base_point=y_pred, point=y_true) grad_vec =", "t : parameter value of the geodesic Returns ------- point_at_time_t", "Riemannian metrics. Parameters ---------- point_a : array-like, shape=[n_samples, dimension] point_b", "shape=[n_samples,] \"\"\" log = self.log(point=point_b, base_point=point_a) sq_dist = self.squared_norm(vector=log, base_point=point_a)", "= gs.sum(weights) if base_point is None: base_point = self.mean(points, weights)", "gs.shape(points)[0] if weights is None: weights = gs.ones((n_points, 1)) weights", "return sq_dist def dist(self, point_a, point_b): \"\"\"Geodesic distance between two", "barycenter def adaptive_gradientdescent_mean(self, points, weights=None, n_max_iterations=40, epsilon=1e-12, init_points=[], verbose=False): \"\"\"Compute", "the mean-square-distance (MSD) because this saves computation time. Parameters ----------", "vector, base_point) return sq_norm def norm(self, vector, base_point=None): \"\"\"Compute norm", "array-like, shape=[n_samples, dimension] or shape=[1, dimension] Returns ------- inner_product :", ": array-like, shape=[n_samples,] \"\"\" sq_norm = self.squared_norm(vector, base_point) norm =", "== 'frechet-poincare-ball': lr = 1e-3 tau = 5e-3 if len(points)", "dimension] base_point : array-like, shape=[n_samples, dimension] Returns ------- norm :", "base_point=current_mean) logs = self.log(point=points, base_point=next_mean) next_tangent_mean = gs.einsum('nk,nj->j', weights, logs)", "norm_current_tangent_mean: current_mean = next_mean current_tangent_mean = next_tangent_mean norm_current_tangent_mean = norm_next_tangent_mean", "n_auxs, _ = gs.shape(aux) if n_tangent_vec_b != n_auxs: if n_auxs", "the squared geodesic distance between the prediction and the ground", "len(points) == 1: return points iteration = 0 convergence =", "norm_next_tangent_mean tau = max(1.0, 1.0511111 * tau) else: tau =", "the geodesic as function of t. Geodesic curve defined by", "Returns ------- closest_neighbor_index \"\"\" dist = self.dist(point, neighbors) closest_neighbor_index =", "= self.inner_product(vector, vector, base_point) return sq_norm def norm(self, vector, base_point=None):", "Riemannian metric, expressed as the squared geodesic distance between the", "shape=[n_samples, dimension], optional point_type : str, optional Returns ------- path", "---------- y_pred y_true metric Returns ------- loss \"\"\" loss =", "barycenter = points.mean(0, keepdims=True) * 0 while convergence > tau", "sq), loop_vars=[iteration, mean, variance, sq_dist], maximum_iterations=n_max_iterations) if last_iteration == n_max_iterations:", "points = gs.to_ndarray(points, to_ndim=3) n_points = gs.shape(points)[0] if weights is", "1 expand_barycenter = gs.repeat(barycenter, points.shape[0], 0) grad_tangent = 2 *", ": array-like, shape=[n_samples, dimension] Returns ------- sq_norm : array-like, shape=[n_samples,]", "gs.to_ndarray(t, to_ndim=2, axis=1) new_initial_point = gs.to_ndarray( initial_point, to_ndim=point_ndim + 1)", "from geomstats.geometry.connection import Connection EPSILON = 1e-4 N_CENTERS = 10", "product between two tangent vectors at a base point. Parameters", "= gs.shape(points)[0] if n_points == 1: return gs.to_ndarray(points[0], to_ndim=2) if", "def closest_neighbor_index(self, point, neighbors): \"\"\"Closest neighbor of point among neighbors.", "term_3) return christoffels def inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None): \"\"\"Inner product", "'nk,k->n' else: raise ValueError('Shape mismatch for einsum.') else: einsum_str_b =", "next_tangent_mean /= sum_weights norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean) if verbose: print( \"Iter", "rather than the mean-square-distance (MSD) because this saves computation time.", "------- loss \"\"\" loss = metric.squared_dist(y_pred, y_true) return loss def", "sq_dists_between_iterates = [] iteration = 0 sq_dist = gs.array([[0.]]) variance", "Note: It only works for positive definite Riemannian metrics. Parameters", "shooting_vector = gs.to_ndarray( tau * current_tangent_mean, to_ndim=2) next_mean = self.exp(", "== 'vector': tangent_vecs = gs.einsum('il,nk->ik', t, new_initial_tangent_vec) elif point_type ==", "sq_dist] if point_type == 'vector': points = gs.to_ndarray(points, to_ndim=2) if", "tangent_vecs = gs.einsum('il,nkm->ikm', t, new_initial_tangent_vec) point_at_time_t = self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point) return", "= self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point) return point_at_time_t return path def squared_dist(self, point_a,", "shape=[n_samples, dimension] weights: array-like, shape=[n_samples, 1], optional init_points: array-like, shape=[n_init,", "= points[0] if point_type == 'vector': mean = gs.to_ndarray(mean, to_ndim=2)", "base_point=current_mean) current_tangent_mean = gs.einsum('nk,nj->j', weights, logs) current_tangent_mean /= sum_weights norm_current_tangent_mean", "'matrix': tangent_vecs = gs.einsum('il,nkm->ikm', t, new_initial_tangent_vec) point_at_time_t = self.exp(tangent_vec=tangent_vecs, base_point=new_initial_point)", "grad_tangent = 2 * self.log(points, expand_barycenter) cc_barycenter = self.exp(lr *", "self.signature = signature def inner_product_matrix(self, base_point=None): \"\"\"Inner product matrix at", "initial_tangent_vec is not None: assert gs.allclose(shooting_tangent_vec, initial_tangent_vec) initial_tangent_vec = shooting_tangent_vec", "dimension] \"\"\" cometric_mat_at_point = self.inner_product_inverse_matrix(base_point) metric_derivative_at_point = self.inner_product_derivative_matrix( base_point) term_1", "with sq_dists_between_iterates. def while_loop_cond(iteration, mean, variance, sq_dist): result = ~gs.logical_or(", "0.5 * (term_1 + term_2 + term_3) return christoffels def", "mean sq_dists_between_iterates = [] iteration = 0 sq_dist = gs.array([[0.]])", "= self.mean(points, weights) variance = 0. sq_dists = self.squared_dist(base_point, points)", "be inaccurate'.format(n_max_iterations)) return gs.to_ndarray(current_mean, to_ndim=2) def diameter(self, points): \"\"\"Give the", "epsilon=1e-12, init_points=[], verbose=False): \"\"\"Compute Frechet mean of (weighted) points using", "points. Note: It only works for positive definite Riemannian metrics.", "metric Returns ------- loss \"\"\" loss = metric.squared_dist(y_pred, y_true) return", "squared_dist(self, point_a, point_b): \"\"\"Squared geodesic distance between two points. Parameters", "inner_prod_mat = self.inner_product_matrix(base_point) inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3) n_mats = gs.shape(inner_prod_mat)[0]", "a base point. Parameters ---------- tangent_vec_a: array-like, shape=[n_samples, dimension] or", "def variance(self, points, weights=None, base_point=None, point_type='vector'): \"\"\"Variance of (weighted) points", "---------- vector : array-like, shape=[n_samples, dimension] base_point : array-like, shape=[n_samples,", "point_type == 'vector': mean = gs.to_ndarray(mean, to_ndim=2) if point_type ==", "gs.array(variance) variance /= sum_weights variance = gs.to_ndarray(variance, to_ndim=1) variance =", ": array-like the Frechet mean of points, a point on", "{}, final variance: {}, final dist: {}'.format( last_iteration, variance, sq_dist))", "if initial_tangent_vec is not None: assert gs.allclose(shooting_tangent_vec, initial_tangent_vec) initial_tangent_vec =", "= self.dist(points[i, :], points[i + 1:, :]) dist_to_farthest_neighbor = gs.amax(dist_to_neighbors)", "= gs.to_ndarray(t, to_ndim=2, axis=1) new_initial_point = gs.to_ndarray( initial_point, to_ndim=point_ndim +", "shape=[n_samples, dimension] end_point : array-like, shape=[n_samples, dimension], optional initial_tangent_vec :", "self.squared_dist(point_a, point_b) dist = gs.sqrt(sq_dist) return dist def variance(self, points,", "'Maximum number of iterations {} reached.' 'The mean may be", "n_tangent_vec_b != n_auxs: if n_auxs == 1: aux = gs.squeeze(aux,", "assumes that all points are lists # of vectors and", "grad_vec = - 2. * tangent_vec inner_prod_mat = metric.inner_product_matrix(base_point=y_pred) grad", "base_point = self.mean(points, weights) variance = 0. sq_dists = self.squared_dist(base_point,", "1: return gs.to_ndarray(points[0], to_ndim=2) if weights is None: weights =", "gs.transpose(inner_prod_mat, axes=(0, 2, 1))) return grad class RiemannianMetric(Connection): \"\"\"Class for", "an initial point and an end point. The geodesic is", "shape=[n_samples, dimension] or shape=[1, dimension] base_point: array-like, shape=[n_samples, dimension] or", "Parameters ---------- vector : array-like, shape=[n_samples, dimension] base_point : array-like,", "autograd import geomstats.backend as gs from geomstats.geometry.connection import Connection EPSILON", "~gs.logical_or( gs.isclose(variance, 0.), gs.less_equal(sq_dist, epsilon * variance)) return result[0, 0]", "= len(init_points) if n_init == 0: current_mean = points[0] else:", "base_point: array-like, shape=[n_samples, dimension] Returns ------- christoffels: array-like, shape=[n_samples, dimension,", "axis=1) sum_weights = gs.sum(weights) mean = points[0] if point_type ==", ": array-like, shape=[n_samples, dimension], optional \"\"\" raise NotImplementedError( 'The computation", "array-like, shape=[n_samples, dimension] base_point : array-like, shape=[n_samples, dimension] Returns -------", "mean of (weighted) points using adaptive time-steps. Frechet mean of", "between the two points that are farthest away from each", "expand_barycenter) cc_barycenter = self.exp(lr * grad_tangent.sum(0, keepdims=True), barycenter) convergence =", "of (weighted) points using adaptive time-steps The loss function optimized", "axis=1) sum_weights = gs.sum(weights) if base_point is None: base_point =", "= gs.einsum('nim,nmlk->nilk', cometric_mat_at_point, metric_derivative_at_point) term_3 = - gs.einsum('nim,nklm->nikl', cometric_mat_at_point, metric_derivative_at_point)", "cometric_mat_at_point, metric_derivative_at_point) christoffels = 0.5 * (term_1 + term_2 +", "inner product matrix' ' is not implemented.') def inner_product_inverse_matrix(self, base_point=None):", "y_true metric Returns ------- loss \"\"\" loss = metric.squared_dist(y_pred, y_true)", "vector : array-like, shape=[n_samples, dimension] base_point : array-like, shape=[n_samples, dimension]", "neighbors. Parameters ---------- point neighbors Returns ------- closest_neighbor_index \"\"\" dist", "or - an initial point and an end point. The", "= gs.shape(points)[0] if weights is None: weights = gs.ones((n_points, 1))", "convergence = self.dist(cc_barycenter, barycenter).max().item() barycenter = cc_barycenter if iteration ==", "dist: {}'.format( last_iteration, variance, sq_dist)) mean = gs.to_ndarray(mean, to_ndim=2) return", "shape=[n_samples, dimension] Returns ------- norm : array-like, shape=[n_samples,] \"\"\" sq_norm", "shape=[n_samples, dimension, dimension, dimension] \"\"\" cometric_mat_at_point = self.inner_product_inverse_matrix(base_point) metric_derivative_at_point =", "einsum.') else: einsum_str_a = 'nj,njk->nk' aux = gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat)", "point_b) dist = gs.sqrt(sq_dist) return dist def variance(self, points, weights=None,", "------- diameter \"\"\" diameter = 0.0 n_points = points.shape[0] for", "gs.to_ndarray(tangent_vec_b, to_ndim=2) n_tangent_vec_a = gs.shape(tangent_vec_a)[0] n_tangent_vec_b = gs.shape(tangent_vec_b)[0] inner_prod_mat =", "verbose : bool, optional Returns ------- mean : array-like the", "gs.shape(inner_prod_mat)[0] if n_tangent_vec_a != n_mats: if n_tangent_vec_a == 1: tangent_vec_a", "gs.einsum('nk,nj->j', weights, sq_dists) variance = gs.array(variance) variance /= sum_weights variance", "axis=1) return variance def mean(self, points, weights=None, n_max_iterations=32, epsilon=EPSILON, point_type='vector',", "works for positive-definite Riemannian metrics and inner products. Parameters ----------", "'default': # TODO(nina): Profile this code to study performance, #", "points : array-like, shape=[n_samples, dimension] weights : array-like, shape=[n_samples, 1],", "sq_dist def dist(self, point_a, point_b): \"\"\"Geodesic distance between two points.", "_ = gs.shape(aux) if n_tangent_vec_b != n_auxs: if n_auxs ==", "def __init__(self, dimension, signature=None): assert isinstance(dimension, int) or dimension ==", "axis=1) assert gs.ndim(inner_prod) == 2, inner_prod.shape return inner_prod def squared_norm(self,", "gs.to_ndarray( tau * current_tangent_mean, to_ndim=2) next_mean = self.exp( tangent_vec=shooting_vector, base_point=current_mean)", "result[0, 0] or iteration == 0 def while_loop_body(iteration, mean, variance,", "\"\"\"Riemannian and pseudo-Riemannian metrics.\"\"\" import math import warnings import autograd", "log = self.log(point=point_b, base_point=point_a) sq_dist = self.squared_norm(vector=log, base_point=point_a) return sq_dist", "{}, final dist: {}'.format( last_iteration, variance, sq_dist)) mean = gs.to_ndarray(mean,", "print( \"Iter {0}: tau= {1}, \" \"norm_current_tangent_mean = {2}\".format( iter,", "dimension] or shape=[1, dimension] base_point: array-like, shape=[n_samples, dimension] or shape=[1,", "points Returns ------- diameter \"\"\" diameter = 0.0 n_points =", "iteration < n_max_iterations): iteration = iteration + 1 shooting_vector =", "between the prediction and the ground truth. Parameters ---------- y_pred", "= self.squared_dist(base_point, points) variance += gs.einsum('nk,nj->j', weights, sq_dists) variance =", "square of the norm of a vector. Squared norm of", "tangent_vecs = gs.einsum('il,nk->ik', t, new_initial_tangent_vec) elif point_type == 'matrix': tangent_vecs", "= max(1.0, 1.0511111 * tau) else: tau = tau *", "weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) if base_point", "------- closest_neighbor_index \"\"\" dist = self.dist(point, neighbors) closest_neighbor_index = gs.argmin(dist)", "vector, base_point=None): \"\"\"Compute the square of the norm of a", "gs.while_loop( lambda i, m, v, sq: while_loop_cond(i, m, v, sq),", "while convergence > tau and n_max_iterations > iteration: iteration +=", "mean = points[0] if point_type == 'vector': mean = gs.to_ndarray(mean,", "self.log(point=points, base_point=next_mean) next_tangent_mean = gs.einsum('nk,nj->j', weights, logs) next_tangent_mean /= sum_weights", "Parameters ---------- point neighbors Returns ------- closest_neighbor_index \"\"\" dist =", "n_mats: if n_tangent_vec_a == 1: tangent_vec_a = gs.squeeze(tangent_vec_a, axis=0) einsum_str_a", "* self.log(points, expand_barycenter) cc_barycenter = self.exp(lr * grad_tangent.sum(0, keepdims=True), barycenter)", "and not of matrices n_points = gs.shape(points)[0] if n_points ==", "------- christoffels: array-like, shape=[n_samples, dimension, dimension, dimension] \"\"\" cometric_mat_at_point =", "---------- base_point : array-like, shape=[n_samples, dimension], optional \"\"\" metric_matrix =", "to study performance, # i.e. what to do with sq_dists_between_iterates.", "= self.exp( tangent_vec=tangent_mean, base_point=mean) sq_dist = self.squared_dist(mean_next, mean) sq_dists_between_iterates.append(sq_dist) variance", "mean) sq_dists_between_iterates.append(sq_dist) variance = self.variance(points=points, weights=weights, base_point=mean_next) mean = mean_next", "mean(self, points, weights=None, n_max_iterations=32, epsilon=EPSILON, point_type='vector', mean_method='default', verbose=False): \"\"\"Frechet mean", "barycenter = cc_barycenter if iteration == n_max_iterations: warnings.warn( 'Maximum number", "variance)) return result[0, 0] or iteration == 0 def while_loop_body(iteration,", "gs.shape(tangent_vec_a)[0] n_tangent_vec_b = gs.shape(tangent_vec_b)[0] inner_prod_mat = self.inner_product_matrix(base_point) inner_prod_mat = gs.to_ndarray(inner_prod_mat,", "- an initial point and an end point. The geodesic", "metric_derivative_at_point) christoffels = 0.5 * (term_1 + term_2 + term_3)", "gs.squeeze(tangent_vec_b, axis=0) einsum_str_b = 'nk,k->n' else: raise ValueError('Shape mismatch for", "the manifold \"\"\" if mean_method == 'default': # TODO(nina): Profile", "assert dimension > 0 super().__init__(dimension=dimension) self.signature = signature def inner_product_matrix(self,", "if end_point is not None: end_point = gs.to_ndarray(end_point, to_ndim=point_ndim +", ":]) dist_to_farthest_neighbor = gs.amax(dist_to_neighbors) diameter = gs.maximum(diameter, dist_to_farthest_neighbor) return diameter", "shape=[1, dimension] Returns ------- inner_product : array-like, shape=[n_samples,] \"\"\" tangent_vec_a", "== 1: aux = gs.squeeze(aux, axis=0) einsum_str_b = 'k,nk->n' elif", "\"\"\" dist = self.dist(point, neighbors) closest_neighbor_index = gs.argmin(dist) return closest_neighbor_index", "dimension] Returns ------- sq_norm : array-like, shape=[n_samples,] \"\"\" sq_norm =", "def inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None): \"\"\"Inner product between two tangent", "self.squared_dist(base_point, points) variance += gs.einsum('nk,nj->j', weights, sq_dists) variance = gs.array(variance)", "lists # of vectors and not of matrices n_points =", "callable \"\"\" t = gs.cast(t, gs.float32) t = gs.to_ndarray(t, to_ndim=1)", "initial_point = gs.to_ndarray(initial_point, to_ndim=point_ndim + 1) if end_point is None", "points are lists # of vectors and not of matrices", "gs.einsum('ni,nij->ni', grad_vec, gs.transpose(inner_prod_mat, axes=(0, 2, 1))) return grad class RiemannianMetric(Connection):", "def squared_norm(self, vector, base_point=None): \"\"\"Compute the square of the norm", "sq_dists = self.squared_dist(base_point, points) variance += gs.einsum('nk,nj->j', weights, sq_dists) variance", "metric_derivative(base_point) def christoffels(self, base_point): \"\"\"Compute Christoffel symbols associated with the", "base point. Parameters ---------- tangent_vec_a: array-like, shape=[n_samples, dimension] or shape=[1,", "point_type : str, optional Returns ------- path : callable \"\"\"", "mean of points, a point on the manifold \"\"\" if", "self.dist(points[i, :], points[i + 1:, :]) dist_to_farthest_neighbor = gs.amax(dist_to_neighbors) diameter", "== 'default': # TODO(nina): Profile this code to study performance,", "array-like, shape=[n_samples,] \"\"\" sq_norm = self.squared_norm(vector, base_point) norm = gs.sqrt(sq_norm)", "0 while convergence > tau and n_max_iterations > iteration: iteration", "array-like, shape=[n_samples, dimension], optional \"\"\" metric_matrix = self.inner_product_matrix(base_point) cometric_matrix =", "n_auxs: if n_auxs == 1: aux = gs.squeeze(aux, axis=0) einsum_str_b", "of iterations {} reached.' 'The mean may be inaccurate'.format(n_max_iterations)) if", "= autograd.jacobian(self.inner_product_matrix) return metric_derivative(base_point) def christoffels(self, base_point): \"\"\"Compute Christoffel symbols", "to_ndim=point_ndim + 1) new_initial_tangent_vec = gs.to_ndarray( initial_tangent_vec, to_ndim=point_ndim + 1)", "function parameterizing the geodesic. Parameters ---------- t : parameter value", "or shape=[1, dimension] Returns ------- inner_product : array-like, shape=[n_samples,] \"\"\"", "raise ValueError('Shape mismatch for einsum.') else: einsum_str_b = 'nk,nk->n' inner_prod", "mean may be inaccurate'.format(n_max_iterations)) if verbose: print('n_iter: {}, final variance:", "loss function optimized is ||M_1(x)||_x (where M_1(x) is the tangent", "tau= {1}, \" \"norm_current_tangent_mean = {2}\".format( iter, tau, norm_current_tangent_mean)) if", "dimension, dimension, dimension] \"\"\" cometric_mat_at_point = self.inner_product_inverse_matrix(base_point) metric_derivative_at_point = self.inner_product_derivative_matrix(", "point=y_true) grad_vec = - 2. * tangent_vec inner_prod_mat = metric.inner_product_matrix(base_point=y_pred)", "array-like, shape=[n_samples, dimension] Returns ------- sq_dist : array-like, shape=[n_samples,] \"\"\"", "1:, :]) dist_to_farthest_neighbor = gs.amax(dist_to_neighbors) diameter = gs.maximum(diameter, dist_to_farthest_neighbor) return", "weights, logs) current_tangent_mean /= sum_weights norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean) while (norm_current_tangent_mean", "iterations {} reached.' 'The mean may be inaccurate'.format(n_max_iterations)) if verbose:", "gs.to_ndarray(mean, to_ndim=2) return mean if mean_method == 'frechet-poincare-ball': lr =", "mode printing the surrogate value epsilon: tolerance for stopping the", "10 def loss(y_pred, y_true, metric): \"\"\"Compute loss function between prediction", "2, 1))) return grad class RiemannianMetric(Connection): \"\"\"Class for Riemannian and", "= self.squared_norm(vector=log, base_point=point_a) return sq_dist def dist(self, point_a, point_b): \"\"\"Geodesic", "gradient descent \"\"\" # TODO(Xavier): This function assumes that all", "of matrices n_points = gs.shape(points)[0] if n_points == 1: return", "'nj,jk->nk' else: raise ValueError('Shape mismatch for einsum.') else: einsum_str_a =", "base_point=new_initial_point) return point_at_time_t return path def squared_dist(self, point_a, point_b): \"\"\"Squared", "= 10 TOLERANCE = 1e-5 N_REPETITIONS = 20 N_MAX_ITERATIONS =", "tangent_vec_b) inner_prod = gs.to_ndarray(inner_prod, to_ndim=2, axis=1) assert gs.ndim(inner_prod) == 2,", "dimension] or shape=[1, dimension] tangent_vec_b: array-like, shape=[n_samples, dimension] or shape=[1,", "tangent_vec_a, tangent_vec_b, base_point=None): \"\"\"Inner product between two tangent vectors at", "variance, sq_dist], maximum_iterations=n_max_iterations) if last_iteration == n_max_iterations: print('Maximum number of", "= gs.to_ndarray(mean, to_ndim=2) return mean if mean_method == 'frechet-poincare-ball': lr", "term_2 + term_3) return christoffels def inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None):", "signature=None): assert isinstance(dimension, int) or dimension == math.inf assert dimension", "inaccurate'.format(n_max_iterations)) return gs.to_ndarray(current_mean, to_ndim=2) def diameter(self, points): \"\"\"Give the distance", "tangent space at a base point. Note: This only works", "mean, variance, sq_dist): logs = self.log(point=points, base_point=mean) tangent_mean = gs.einsum('nk,nj->j',", "function.\"\"\" tangent_vec = metric.log(base_point=y_pred, point=y_true) grad_vec = - 2. *", "gs.squeeze(aux, axis=0) einsum_str_b = 'k,nk->n' elif n_tangent_vec_b == 1: tangent_vec_b", "to_ndim=2, axis=1) assert gs.ndim(inner_prod) == 2, inner_prod.shape return inner_prod def", "__init__(self, dimension, signature=None): assert isinstance(dimension, int) or dimension == math.inf", "points, a point on the manifold \"\"\" if mean_method ==", "return inner_prod def squared_norm(self, vector, base_point=None): \"\"\"Compute the square of", "new_initial_tangent_vec = gs.to_ndarray( initial_tangent_vec, to_ndim=point_ndim + 1) if point_type ==", "+ 1) if point_type == 'vector': tangent_vecs = gs.einsum('il,nk->ik', t,", "base_point=point_a) sq_dist = self.squared_norm(vector=log, base_point=point_a) return sq_dist def dist(self, point_a,", "Returns ------- dist : array-like, shape=[n_samples,] \"\"\" sq_dist = self.squared_dist(point_a,", "dimension], optional point_type : str, optional Returns ------- path :", "new_initial_tangent_vec) elif point_type == 'matrix': tangent_vecs = gs.einsum('il,nkm->ikm', t, new_initial_tangent_vec)", "Parameters ---------- points: array-like, shape=[n_samples, dimension] weights: array-like, shape=[n_samples, 1],", "== n_max_iterations: print('Maximum number of iterations {} reached.' 'The mean", "einsum_str_b = 'nk,nk->n' inner_prod = gs.einsum(einsum_str_b, aux, tangent_vec_b) inner_prod =", "gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights = gs.sum(weights) if base_point is None:", "x) rather than the mean-square-distance (MSD) because this saves computation", "dimension] epsilon: tolerance for stopping the gradient descent verbose: verbose", "y_pred y_true metric Returns ------- loss \"\"\" loss = metric.squared_dist(y_pred,", "weights = gs.array(weights) weights = gs.to_ndarray(weights, to_ndim=2, axis=1) sum_weights =", "ground truth. Parameters ---------- y_pred y_true metric Returns ------- loss", "# TODO(nina): Profile this code to study performance, # i.e.", "point. Parameters ---------- base_point : array-like, shape=[n_samples, dimension], optional \"\"\"", "next_tangent_mean = gs.einsum('nk,nj->j', weights, logs) next_tangent_mean /= sum_weights norm_next_tangent_mean =", "(term_1 + term_2 + term_3) return christoffels def inner_product(self, tangent_vec_a,", "variance, sq_dist = gs.while_loop( lambda i, m, v, sq: while_loop_cond(i,", "= 1.0 iteration = 0 logs = self.log(point=points, base_point=current_mean) current_tangent_mean", "defined by either: - an initial point and an initial", "mean-square-distance (MSD) because this saves computation time. Parameters ---------- points:", "optional init_points: array-like, shape=[n_init, dimension] epsilon: tolerance for stopping the", "sum_weights = gs.sum(weights) mean = points[0] if point_type == 'vector':", "axis=0) einsum_str_a = 'nj,jk->nk' else: raise ValueError('Shape mismatch for einsum.')", "mean if mean_method == 'frechet-poincare-ball': lr = 1e-3 tau =", "1) new_initial_tangent_vec = gs.to_ndarray( initial_tangent_vec, to_ndim=point_ndim + 1) if point_type", "returned as a function parameterized by t. Parameters ---------- initial_point", "= gs.linalg.norm(current_tangent_mean) while (norm_current_tangent_mean > epsilon and iteration < n_max_iterations):", "by a Riemannian metric, expressed as the squared geodesic distance", "1: aux = gs.squeeze(aux, axis=0) einsum_str_b = 'k,nk->n' elif n_tangent_vec_b", "t = gs.to_ndarray(t, to_ndim=1) t = gs.to_ndarray(t, to_ndim=2, axis=1) new_initial_point", "vector. Norm of a vector associated to the inner product", "cometric_matrix = gs.linalg.inv(metric_matrix) return cometric_matrix def inner_product_derivative_matrix(self, base_point=None): \"\"\"Compute derivative", "keepdims=True), barycenter) convergence = self.dist(cc_barycenter, barycenter).max().item() barycenter = cc_barycenter if", "\"\"\" loss = metric.squared_dist(y_pred, y_true) return loss def grad(y_pred, y_true,", "\"\"\"Give the distance between two farthest points. Distance between the", "points. Parameters ---------- point_a : array-like, shape=[n_samples, dimension] point_b :", "geodesic as function of t. Geodesic curve defined by either:", "{0}: tau= {1}, \" \"norm_current_tangent_mean = {2}\".format( iter, tau, norm_current_tangent_mean))", "gs.linalg.norm(current_tangent_mean) while (norm_current_tangent_mean > epsilon and iteration < n_max_iterations): iteration", "def adaptive_gradientdescent_mean(self, points, weights=None, n_max_iterations=40, epsilon=1e-12, init_points=[], verbose=False): \"\"\"Compute Frechet", "= gs.to_ndarray(inner_prod, to_ndim=2, axis=1) assert gs.ndim(inner_prod) == 2, inner_prod.shape return", "of points, a point on the manifold \"\"\" if mean_method", "initial_tangent_vec : array-like, shape=[n_samples, dimension], optional point_type : str, optional", "= gs.to_ndarray(inner_prod_mat, to_ndim=3) n_mats = gs.shape(inner_prod_mat)[0] if n_tangent_vec_a != n_mats:", "array-like, shape=[n_init, dimension] epsilon: tolerance for stopping the gradient descent", "farthest points. Distance between the two points that are farthest", "initial_tangent_vec = shooting_tangent_vec initial_tangent_vec = gs.array(initial_tangent_vec) initial_tangent_vec = gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim", "= gs.array([[0.]]) variance = gs.array([[0.]]) last_iteration, mean, variance, sq_dist =", "a vector. Norm of a vector associated to the inner", "product matrix' ' is not implemented.') def inner_product_inverse_matrix(self, base_point=None): \"\"\"Inner", "= gs.array(initial_tangent_vec) initial_tangent_vec = gs.to_ndarray(initial_tangent_vec, to_ndim=point_ndim + 1) def path(t):", "\"\"\"Compute Frechet mean of (weighted) points using adaptive time-steps. Frechet", "point_at_time_t return path def squared_dist(self, point_a, point_b): \"\"\"Squared geodesic distance", "the geodesic.') if end_point is not None: end_point = gs.to_ndarray(end_point,", "einsum_str_b = 'nk,k->n' else: raise ValueError('Shape mismatch for einsum.') else:", "gs.to_ndarray(variance, to_ndim=1) variance = gs.to_ndarray(variance, to_ndim=2, axis=1) return variance def", "Parameters ---------- base_point : array-like, shape=[n_samples, dimension], optional \"\"\" raise", "two farthest points. Distance between the two points that are", "return sq_norm def norm(self, vector, base_point=None): \"\"\"Compute norm of a", "10 TOLERANCE = 1e-5 N_REPETITIONS = 20 N_MAX_ITERATIONS = 50000", "array-like, shape=[n_samples,] \"\"\" log = self.log(point=point_b, base_point=point_a) sq_dist = self.squared_norm(vector=log,", "0. sq_dists = self.squared_dist(base_point, points) variance += gs.einsum('nk,nj->j', weights, sq_dists)", "pseudo-Riemannian metrics.\"\"\" def __init__(self, dimension, signature=None): assert isinstance(dimension, int) or", "= self.exp(lr * grad_tangent.sum(0, keepdims=True), barycenter) convergence = self.dist(cc_barycenter, barycenter).max().item()", "weights, sq_dists) variance = gs.array(variance) variance /= sum_weights variance =", "maximum_iterations=n_max_iterations) if last_iteration == n_max_iterations: print('Maximum number of iterations {}", "shape=[n_samples, dimension] base_point : array-like, shape=[n_samples, dimension] Returns ------- norm", "2 initial_point = gs.to_ndarray(initial_point, to_ndim=point_ndim + 1) if end_point is", "1e-5 N_REPETITIONS = 20 N_MAX_ITERATIONS = 50000 N_STEPS = 10", "else: einsum_str_b = 'nk,nk->n' inner_prod = gs.einsum(einsum_str_b, aux, tangent_vec_b) inner_prod", "is not implemented.') def inner_product_inverse_matrix(self, base_point=None): \"\"\"Inner product matrix at", "array-like, shape=[n_samples, dimension] Returns ------- sq_norm : array-like, shape=[n_samples,] \"\"\"", "EPSILON = 1e-4 N_CENTERS = 10 TOLERANCE = 1e-5 N_REPETITIONS", "two tangent vectors at a base point. Parameters ---------- tangent_vec_a:", "optional point_type : str, optional Returns ------- path : callable", "warnings.warn( 'Maximum number of iterations {} reached. The ' 'mean", "1: return points iteration = 0 convergence = math.inf barycenter", "at the tangent space at a base point. Note: This", "dimension] tangent_vec_b: array-like, shape=[n_samples, dimension] or shape=[1, dimension] base_point: array-like,", "to_ndim=2) n_tangent_vec_a = gs.shape(tangent_vec_a)[0] n_tangent_vec_b = gs.shape(tangent_vec_b)[0] inner_prod_mat = self.inner_product_matrix(base_point)", "while_loop_body(i, m, v, sq), loop_vars=[iteration, mean, variance, sq_dist], maximum_iterations=n_max_iterations) if", ": array-like, shape=[n_samples, dimension] Returns ------- sq_dist : array-like, shape=[n_samples,]", "def grad(y_pred, y_true, metric): \"\"\"Closed-form for the gradient of the", "* tau) else: tau = tau * 0.8 if iteration", "term_1 = gs.einsum('nim,nmkl->nikl', cometric_mat_at_point, metric_derivative_at_point) term_2 = gs.einsum('nim,nmlk->nilk', cometric_mat_at_point, metric_derivative_at_point)" ]
[ "= DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'], seconds=[':%Ss'], minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'], hourmin=['%H:%M:'], hours=[\"%H:%M\"], days=[\"%d %b\"],", "DQ_HrsOrder join NightInfo using (NightInfo_Id) \" \\ \" where Date", "colors = [Plasma256[int((y - ord_min) * (len(Plasma256) - 1) /", "</div> </div> \"\"\" ) p = figure(title=\"HRS Order Position High", "df = pd.read_sql(sql, db.engine) colors = [] if len(df) >", "{obsmode} \" \\ \" and FileName like 'RORDER%%' \" \\", "Date <'{end_date}' {logic}\" \\ .format(start_date=start_date, end_date=end_date, logic=logic) df = pd.read_sql(sql,", "like 'RORDER%%' \" \\ .format(obsmode=obsmode) sql = \"select Date, y_upper,", "<div> <span style=\"font-size: 15px; font-weight: bold;\">HRS Order: </span> <span style=\"font-size:", "%Y\"], years=[\"%b %Y\"]) def get_position_source(start_date, end_date, obsmode): logic = \"", "element with the Order plot. \"\"\" def get_source(obsmode): logic =", "# HrsMode_Id = 2 med high_source = get_source(3) # HrsMode_Id", "= HoverTool( tooltips=\"\"\" <div> <div> <span style=\"font-size: 15px; font-weight: bold;\">Date:", "color='orange', fill_alpha=0.2, legend='Medium', size=10) p.scatter(source=high_source, x='Date', y='ord', color='green', fill_alpha=0.2, legend='High',", "obsmode High resolution over time Params: ------- start_date: date Earliest", "colors = [] if len(df) > 0: ord_min = df['HrsOrder'].min()", "from bokeh.models.formatters import DatetimeTickFormatter from bokeh.palettes import Plasma256 from bokeh.plotting", "end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine) source = ColumnDataSource(df) return", "def hrs_order_plot(start_date, end_date): \"\"\"Return a <div> element with the Order", "Order plot. The plot shows the HRS order for obsmode", "x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date', y='y_upper', color='colors', fill_alpha=0.2,", "= get_source(2) # HrsMode_Id = 2 med high_source = get_source(3)", "= date_formatter return p @data_quality(name='hrs_order_position_medium', caption=' ') def hrs_order_position_plot(start_date, end_date):", "legend='High', size=10) p.legend.location = \"top_right\" p.legend.click_policy = \"hide\" p.legend.background_fill_alpha =", "logic = \" and HrsMode_Id = {obsmode} \" \\ \"", "Position plot. \"\"\" high_source = get_position_source(start_date, end_date, 2) # HrsMode_Id", "end_date, 2) # HrsMode_Id = 3 high tool_list = \"pan,reset,save,wheel_zoom,", "high_source = get_position_source(start_date, end_date, 2) # HrsMode_Id = 3 high", "caption='HRS Order') def hrs_order_plot(start_date, end_date): \"\"\"Return a <div> element with", "p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_high', caption=' ') def hrs_order_position_plot(start_date,", "</div> </div> \"\"\" ) p = figure(title=\"HRS Order Position Low", "ColumnDataSource(df) return source low_source = get_source(1) # HrsMode_Id = 1", "bokeh.plotting import figure, ColumnDataSource from app import db from app.decorators", "import data_quality # creates your plot date_formatter = DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'],", "%b %Y\"], years=[\"%b %Y\"]) def get_position_source(start_date, end_date, obsmode): logic =", "= \"select Date, (Max(HrsOrder) - Min(HrsOrder)) as ord, CONVERT(Date, char)", "= date_formatter return p @data_quality(name='hrs_order_position_low', caption=' ') def hrs_order_position_plot(start_date, end_date):", "[] if len(df) > 0: ord_min = df['HrsOrder'].min() ord_max =", "<div> <span style=\"font-size: 15px; font-weight: bold;\">Date: </span> <span style=\"font-size: 15px;\">", "fill_alpha=0.2, legend='Medium', size=10) p.scatter(source=high_source, x='Date', y='ord', color='green', fill_alpha=0.2, legend='High', size=10)", ") p = figure(title=\"HRS Order Position Medium Resolution\", x_axis_label='Date', y_axis_label='y_upper',", "</span> <span style=\"font-size: 15px;\"> @ord</span> </div> </div> \"\"\" ) p", "\" and HrsMode_Id = {obsmode} \" \\ \" and FileName", "the Order Position plot. The plot shows the HRS order", "------- str: A <div> element with the Order Position plot.", "Return: ------- str: A <div> element with the Order plot.", "</span> <span style=\"font-size: 15px;\"> @y_upper</span> </div> <div> <span style=\"font-size: 15px;", "font-weight: bold;\">HRS Order: </span> <span style=\"font-size: 15px;\"> @HrsOrder</span> </div> </div>", "p.legend.click_policy = \"hide\" p.legend.background_fill_alpha = 0.3 p.legend.inactive_fill_alpha = 0.8 p.xaxis[0].formatter", ".format(obsmode=obsmode) sql = \"select Date, (Max(HrsOrder) - Min(HrsOrder)) as ord,", "milliseconds=['%S.%2Ns'], seconds=[':%Ss'], minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'], hourmin=['%H:%M:'], hours=[\"%H:%M\"], days=[\"%d %b\"], months=[\"%d %b", "return p @data_quality(name='hrs_order_position_medium', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return", "over time Params: ------- start_date: date Earliest date to include", "style=\"font-size: 15px;\"> @Time</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">HrsOrder(Max", "plot date_formatter = DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'], seconds=[':%Ss'], minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'], hourmin=['%H:%M:'], hours=[\"%H:%M\"],", "import Plasma256 from bokeh.plotting import figure, ColumnDataSource from app import", "seconds=[':%Ss'], minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'], hourmin=['%H:%M:'], hours=[\"%H:%M\"], days=[\"%d %b\"], months=[\"%d %b %Y\"],", "fill_alpha=0.2, legend='Low', size=10) p.scatter(source=med_source, x='Date', y='ord', color='orange', fill_alpha=0.2, legend='Medium', size=10)", "date_formatter return p @data_quality(name='hrs_order_position_low', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\"", "bold;\">HRS Order: </span> <span style=\"font-size: 15px;\"> @HrsOrder</span> </div> </div> \"\"\"", "low_source = get_source(1) # HrsMode_Id = 1 low med_source =", "from bokeh.models import HoverTool from bokeh.models.formatters import DatetimeTickFormatter from bokeh.palettes", "Date, y_upper, HrsOrder, CONVERT(Date,char) AS Time \" \\ \" from", "x='Date', y='ord', color='red', fill_alpha=0.2, legend='Low', size=10) p.scatter(source=med_source, x='Date', y='ord', color='orange',", "end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine) colors = [] if", "Order Position Low Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source,", "join NightInfo using (NightInfo_Id) \" \\ \" where Date >", "High, low and medium over time Params: ------- start_date: date", "\"top_right\" p.legend.click_policy = \"hide\" p.legend.background_fill_alpha = 0.3 p.legend.inactive_fill_alpha = 0.8", "size=10) p.scatter(source=high_source, x='Date', y='ord', color='green', fill_alpha=0.2, legend='High', size=10) p.legend.location =", "element with the Order Position plot. The plot shows the", "months=[\"%d %b %Y\"], years=[\"%b %Y\"]) def get_position_source(start_date, end_date, obsmode): logic", "\"\"\" def get_source(obsmode): logic = \" and HrsMode_Id = {obsmode}", "len(df) > 0: ord_min = df['HrsOrder'].min() ord_max = df['HrsOrder'].max() colors", "2) # HrsMode_Id = 3 high tool_list = \"pan,reset,save,wheel_zoom, box_zoom\"", "and FileName like 'RORDER%%' \" \\ .format(obsmode=obsmode) sql = \"select", "end_date): \"\"\"Return a <div> element with the Order plot. The", "p.scatter(source=low_source, x='Date', y='ord', color='red', fill_alpha=0.2, legend='Low', size=10) p.scatter(source=med_source, x='Date', y='ord',", "Position plot. The plot shows the HRS order for obsmode", "\"\"\" ) p = figure(title=\"HRS Order Position Medium Resolution\", x_axis_label='Date',", "date_formatter return p @data_quality(name='hrs_order_position_high', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\"", "ord_max = df['HrsOrder'].max() colors = [Plasma256[int((y - ord_min) * (len(Plasma256)", "df['HrsOrder'].min() ord_max = df['HrsOrder'].max() colors = [Plasma256[int((y - ord_min) *", "\\ \" group by Date \" \\ .format(obsmode=obsmode) sql =", "pd from bokeh.models import HoverTool from bokeh.models.formatters import DatetimeTickFormatter from", "low and medium over time Params: ------- start_date: date Earliest", "p = figure(title=\"HRS Order Position Medium Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime',", "plot shows the HRS order for obsmode High resolution over", "= \"top_right\" p.legend.click_policy = \"hide\" p.legend.background_fill_alpha = 0.3 p.legend.inactive_fill_alpha =", "= df['HrsOrder'].max() colors = [Plasma256[int((y - ord_min) * (len(Plasma256) -", "HoverTool from bokeh.models.formatters import DatetimeTickFormatter from bokeh.palettes import Plasma256 from", "minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'], hourmin=['%H:%M:'], hours=[\"%H:%M\"], days=[\"%d %b\"], months=[\"%d %b %Y\"], years=[\"%b", "figure, ColumnDataSource from app import db from app.decorators import data_quality", "Date \" \\ .format(obsmode=obsmode) sql = \"select Date, (Max(HrsOrder) -", "</div> \"\"\" ) p = figure(title=\"HRS Order Position Medium Resolution\",", "= figure(title=\"HRS Order Position High Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list,", "get_position_source(start_date, end_date, obsmode): logic = \" and HrsMode_Id = {obsmode}", "'RORDER%%' \" \\ \" group by Date \" \\ .format(obsmode=obsmode)", "y='ord', color='red', fill_alpha=0.2, legend='Low', size=10) p.scatter(source=med_source, x='Date', y='ord', color='orange', fill_alpha=0.2,", "Order Position High Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source,", "import figure, ColumnDataSource from app import db from app.decorators import", "with the Order plot. The plot shows the HRS order", "app.decorators import data_quality # creates your plot date_formatter = DatetimeTickFormatter(microseconds=['%f'],", "the Order plot. The plot shows the HRS order for", "element with the Order Position plot. \"\"\" high_source = get_position_source(start_date,", "= df['HrsOrder'].min() ord_max = df['HrsOrder'].max() colors = [Plasma256[int((y - ord_min)", "@HrsOrder</span> </div> </div> \"\"\" ) p = figure(title=\"HRS Order Position", "= get_position_source(start_date, end_date, 2) # HrsMode_Id = 3 high tool_list", "and medium over time Params: ------- start_date: date Earliest date", "[Plasma256[int((y - ord_min) * (len(Plasma256) - 1) / float(ord_max -", "high_source = get_source(3) # HrsMode_Id = 3 high tool_list =", "A <div> element with the Order plot. \"\"\" def get_source(obsmode):", "return source @data_quality(name='hrs_order', caption='HRS Order') def hrs_order_plot(start_date, end_date): \"\"\"Return a", "def get_source(obsmode): logic = \" and HrsMode_Id = {obsmode} \"", "the Order Position plot. \"\"\" high_source = get_position_source(start_date, end_date, 3)", "15px; font-weight: bold;\">HrsOrder(Max - Min): </span> <span style=\"font-size: 15px;\"> @ord</span>", "p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_medium', caption=' ') def hrs_order_position_plot(start_date,", "bold;\">Date: </span> <span style=\"font-size: 15px;\"> @Time</span> </div> <div> <span style=\"font-size:", "\" \\ \" and FileName like 'RORDER%%' \" \\ \"", "as pd from bokeh.models import HoverTool from bokeh.models.formatters import DatetimeTickFormatter", "Order Position plot. \"\"\" high_source = get_position_source(start_date, end_date, 2) #", "fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_medium', caption=' ')", "{logic}\" \\ .format(start_date=start_date, end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine) colors", "pd.read_sql(sql, db.engine) source = ColumnDataSource(df) return source low_source = get_source(1)", "</div> <div> <span style=\"font-size: 15px; font-weight: bold;\">HrsOrder(Max - Min): </span>", "\"pan,reset,save,wheel_zoom, box_zoom\" _hover = HoverTool( tooltips=\"\"\" <div> <div> <span style=\"font-size:", "high tool_list = \"pan,reset,save,wheel_zoom, box_zoom\" _hover = HoverTool( tooltips=\"\"\" <div>", "plot. \"\"\" high_source = get_position_source(start_date, end_date, 3) # HrsMode_Id =", "Position High Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date',", "plot. The plot shows the HRS order for obsmode High", "p.legend.inactive_fill_alpha = 0.8 p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_high', caption='", "= \"pan,reset,save,wheel_zoom, box_zoom\" _hover = HoverTool( tooltips=\"\"\" <div> <div> <span", "str: A <div> element with the Order plot. \"\"\" def", "- Min): </span> <span style=\"font-size: 15px;\"> @ord</span> </div> </div> \"\"\"", "your plot date_formatter = DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'], seconds=[':%Ss'], minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'], hourmin=['%H:%M:'],", "with the Order Position plot. \"\"\" high_source = get_position_source(start_date, end_date,", "%Y\"]) def get_position_source(start_date, end_date, obsmode): logic = \" and HrsMode_Id", "by Date \" \\ .format(obsmode=obsmode) sql = \"select Date, (Max(HrsOrder)", "\"select Date, (Max(HrsOrder) - Min(HrsOrder)) as ord, CONVERT(Date, char) AS", "bokeh.models import HoverTool from bokeh.models.formatters import DatetimeTickFormatter from bokeh.palettes import", "date Earliest date to include in the plot. end_date: date", "return source low_source = get_source(1) # HrsMode_Id = 1 low", "date not to include in the plot. Return: ------- str:", "HRS order for obsmode High resolution over time Params: -------", "Min): </span> <span style=\"font-size: 15px;\"> @ord</span> </div> </div> \"\"\" )", "style=\"font-size: 15px;\"> @y_upper</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">HRS", "\" from DQ_HrsOrder join NightInfo using (NightInfo_Id) \" \\ \"", "figure(title=\"HRS Order Position Low Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover])", "HrsMode_Id = 2 med high_source = get_source(3) # HrsMode_Id =", "for obsmode High resolution over time Params: ------- start_date: date", "y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date', y='y_upper', color='colors', fill_alpha=0.2, size=10)", "include in the plot. end_date: date Earliest date not to", "</div> \"\"\" ) p = figure(title=\"HRS Order Position Low Resolution\",", "style=\"font-size: 15px; font-weight: bold;\">HRS Order: </span> <span style=\"font-size: 15px;\"> @HrsOrder</span>", "</div> <div> <span style=\"font-size: 15px; font-weight: bold;\">HRS Order: </span> <span", "bokeh.models.formatters import DatetimeTickFormatter from bokeh.palettes import Plasma256 from bokeh.plotting import", "A <div> element with the Order Position plot. \"\"\" high_source", "from DQ_HrsOrder join NightInfo using (NightInfo_Id) \" \\ \" where", "CONVERT(Date, char) AS Time \" \\ \" from DQ_HrsOrder join", "3 high tool_list = \"pan,reset,save,wheel_zoom, box_zoom\" _hover = HoverTool( tooltips=\"\"\"", "{logic}\" \\ .format(start_date=start_date, end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine) source", "from app.decorators import data_quality # creates your plot date_formatter =", "str: A <div> element with the Order Position plot. \"\"\"", "p.scatter(source=med_source, x='Date', y='ord', color='orange', fill_alpha=0.2, legend='Medium', size=10) p.scatter(source=high_source, x='Date', y='ord',", "in the plot. Return: ------- str: A <div> element with", "# HrsMode_Id = 3 high tool_list = \"pan,reset,save,wheel_zoom, box_zoom\" _hover", "2 med high_source = get_source(3) # HrsMode_Id = 3 high", "y='ord', color='orange', fill_alpha=0.2, legend='Medium', size=10) p.scatter(source=high_source, x='Date', y='ord', color='green', fill_alpha=0.2,", "\" \\ \" and FileName like 'RORDER%%' \" \\ .format(obsmode=obsmode)", "= get_position_source(start_date, end_date, 3) # HrsMode_Id = 3 high tool_list", "Plasma256 from bokeh.plotting import figure, ColumnDataSource from app import db", "NightInfo using (NightInfo_Id) \" \\ \" where Date > '{start_date}'", "@data_quality(name='hrs_order', caption='HRS Order') def hrs_order_plot(start_date, end_date): \"\"\"Return a <div> element", "The plot shows the HRS order for obsmode High resolution", "HoverTool( tooltips=\"\"\" <div> <div> <span style=\"font-size: 15px; font-weight: bold;\">Date: </span>", "DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'], seconds=[':%Ss'], minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'], hourmin=['%H:%M:'], hours=[\"%H:%M\"], days=[\"%d %b\"], months=[\"%d", "15px;\"> @y_upper</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">HRS Order:", "\" \\ \" group by Date \" \\ .format(obsmode=obsmode) sql", "= get_source(3) # HrsMode_Id = 3 high tool_list = \"pan,reset,save,wheel_zoom,", "p.scatter(source=high_source, x='Date', y='ord', color='green', fill_alpha=0.2, legend='High', size=10) p.legend.location = \"top_right\"", "<span style=\"font-size: 15px; font-weight: bold;\">Y Upper: </span> <span style=\"font-size: 15px;\">", "<span style=\"font-size: 15px; font-weight: bold;\">Date: </span> <span style=\"font-size: 15px;\"> @Time</span>", "a <div> element with the Order Position plot. The plot", "FileName like 'RORDER%%' \" \\ .format(obsmode=obsmode) sql = \"select Date,", "a <div> element with the Order plot. The plot shows", "p.legend.background_fill_alpha = 0.3 p.legend.inactive_fill_alpha = 0.8 p.xaxis[0].formatter = date_formatter return", "3) # HrsMode_Id = 3 high tool_list = \"pan,reset,save,wheel_zoom, box_zoom\"", "hrs_order_plot(start_date, end_date): \"\"\"Return a <div> element with the Order plot.", "= 1 low med_source = get_source(2) # HrsMode_Id = 2", "= figure(title=\"HRS Order Position Low Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list,", "\"\"\" ) p = figure(title=\"HRS Order Position High Resolution\", x_axis_label='Date',", "app import db from app.decorators import data_quality # creates your", "medium over time Params: ------- start_date: date Earliest date to", "= date_formatter return p @data_quality(name='hrs_order_position_high', caption=' ') def hrs_order_position_plot(start_date, end_date):", "<span style=\"font-size: 15px;\"> @y_upper</span> </div> <div> <span style=\"font-size: 15px; font-weight:", "\"\"\" ) p = figure(title=\"HRS Order Position Low Resolution\", x_axis_label='Date',", "shows the HRS order for obsmode High resolution over time", "low med_source = get_source(2) # HrsMode_Id = 2 med high_source", "colors source = ColumnDataSource(df) return source @data_quality(name='hrs_order', caption='HRS Order') def", "<div> <div> <span style=\"font-size: 15px; font-weight: bold;\">Date: </span> <span style=\"font-size:", "the HRS order for obsmode High resolution over time Params:", "= \"select Date, y_upper, HrsOrder, CONVERT(Date,char) AS Time \" \\", "= figure(title=\"HRS Order Position Medium Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list,", "p.scatter(source=high_source, x='Date', y='y_upper', color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter return", "and FileName like 'RORDER%%' \" \\ \" group by Date", "bold;\">Y Upper: </span> <span style=\"font-size: 15px;\"> @y_upper</span> </div> <div> <span", "= figure(title=\"HRS Order\", x_axis_label='Date', y_axis_label='Max(HrsOrder) - Min(HrsOrder)', x_axis_type='datetime', tools=[tool_list, _hover])", "return p @data_quality(name='hrs_order_position_high', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return", "end_date): \"\"\" Return a <div> element with the Order Position", "pd.read_sql(sql, db.engine) colors = [] if len(df) > 0: ord_min", "in df[\"HrsOrder\"]] df['colors'] = colors source = ColumnDataSource(df) return source", "for y in df[\"HrsOrder\"]] df['colors'] = colors source = ColumnDataSource(df)", "time Params: ------- start_date: date Earliest date to include in", "</div> \"\"\" ) p = figure(title=\"HRS Order\", x_axis_label='Date', y_axis_label='Max(HrsOrder) -", "plot shows the HRS order for obsmode High, low and", "color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_low', caption='", "source @data_quality(name='hrs_order', caption='HRS Order') def hrs_order_plot(start_date, end_date): \"\"\"Return a <div>", "= 2 med high_source = get_source(3) # HrsMode_Id = 3", "legend='Medium', size=10) p.scatter(source=high_source, x='Date', y='ord', color='green', fill_alpha=0.2, legend='High', size=10) p.legend.location", "Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date', y='y_upper', color='colors',", "0.3 p.legend.inactive_fill_alpha = 0.8 p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_high',", "Date > '{start_date}' and Date <'{end_date}' {logic}\" \\ .format(start_date=start_date, end_date=end_date,", "Order Position Medium Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source,", "- 1) / float(ord_max - ord_min))] for y in df[\"HrsOrder\"]]", "plot. \"\"\" high_source = get_position_source(start_date, end_date, 2) # HrsMode_Id =", "<div> <span style=\"font-size: 15px; font-weight: bold;\">HrsOrder(Max - Min): </span> <span", "Earliest date to include in the plot. end_date: date Earliest", "Order\", x_axis_label='Date', y_axis_label='Max(HrsOrder) - Min(HrsOrder)', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=low_source, x='Date',", "= [] if len(df) > 0: ord_min = df['HrsOrder'].min() ord_max", "Position plot. \"\"\" high_source = get_position_source(start_date, end_date, 3) # HrsMode_Id", "x='Date', y='ord', color='green', fill_alpha=0.2, legend='High', size=10) p.legend.location = \"top_right\" p.legend.click_policy", "\\ .format(start_date=start_date, end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine) source =", "(NightInfo_Id) \" \\ \" where Date > '{start_date}' and Date", "\" \\ \" where Date > '{start_date}' and Date <'{end_date}'", "resolution over time Params: ------- start_date: date Earliest date to", "x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=low_source, x='Date', y='ord', color='red', fill_alpha=0.2, legend='Low', size=10)", "ord, CONVERT(Date, char) AS Time \" \\ \" from DQ_HrsOrder", "fill_alpha=0.2, legend='High', size=10) p.legend.location = \"top_right\" p.legend.click_policy = \"hide\" p.legend.background_fill_alpha", "with the Order plot. \"\"\" def get_source(obsmode): logic = \"", "order for obsmode High, low and medium over time Params:", "<span style=\"font-size: 15px; font-weight: bold;\">HRS Order: </span> <span style=\"font-size: 15px;\">", "figure(title=\"HRS Order\", x_axis_label='Date', y_axis_label='Max(HrsOrder) - Min(HrsOrder)', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=low_source,", "FileName like 'RORDER%%' \" \\ \" group by Date \"", "char) AS Time \" \\ \" from DQ_HrsOrder join NightInfo", "def get_position_source(start_date, end_date, obsmode): logic = \" and HrsMode_Id =", "- ord_min) * (len(Plasma256) - 1) / float(ord_max - ord_min))]", "shows the HRS order for obsmode High, low and medium", "years=[\"%b %Y\"]) def get_position_source(start_date, end_date, obsmode): logic = \" and", "end_date, obsmode): logic = \" and HrsMode_Id = {obsmode} \"", "@ord</span> </div> </div> \"\"\" ) p = figure(title=\"HRS Order\", x_axis_label='Date',", "CONVERT(Date,char) AS Time \" \\ \" from DQ_HrsOrder join NightInfo", "= colors source = ColumnDataSource(df) return source @data_quality(name='hrs_order', caption='HRS Order')", "Order Position plot. \"\"\" high_source = get_position_source(start_date, end_date, 3) #", "High resolution over time Params: ------- start_date: date Earliest date", "\\ \" from DQ_HrsOrder join NightInfo using (NightInfo_Id) \" \\", "<span style=\"font-size: 15px;\"> @HrsOrder</span> </div> </div> \"\"\" ) p =", "if len(df) > 0: ord_min = df['HrsOrder'].min() ord_max = df['HrsOrder'].max()", "\\ \" where Date > '{start_date}' and Date <'{end_date}' {logic}\"", "Order Position plot. The plot shows the HRS order for", "the plot. Return: ------- str: A <div> element with the", ") p = figure(title=\"HRS Order Position High Resolution\", x_axis_label='Date', y_axis_label='y_upper',", "\\ \" and FileName like 'RORDER%%' \" \\ \" group", "= 0.8 p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_high', caption=' ')", "@y_upper</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">HRS Order: </span>", "and HrsMode_Id = {obsmode} \" \\ \" and FileName like", ") p = figure(title=\"HRS Order\", x_axis_label='Date', y_axis_label='Max(HrsOrder) - Min(HrsOrder)', x_axis_type='datetime',", "</div> </div> \"\"\" ) p = figure(title=\"HRS Order\", x_axis_label='Date', y_axis_label='Max(HrsOrder)", ") p = figure(title=\"HRS Order Position Low Resolution\", x_axis_label='Date', y_axis_label='y_upper',", "Order') def hrs_order_plot(start_date, end_date): \"\"\"Return a <div> element with the", "DatetimeTickFormatter from bokeh.palettes import Plasma256 from bokeh.plotting import figure, ColumnDataSource", "df = pd.read_sql(sql, db.engine) source = ColumnDataSource(df) return source low_source", "include in the plot. Return: ------- str: A <div> element", "med high_source = get_source(3) # HrsMode_Id = 3 high tool_list", "return p @data_quality(name='hrs_order_position_low', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return", "date Earliest date not to include in the plot. Return:", "Medium Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date', y='y_upper',", "HrsMode_Id = 3 high tool_list = \"pan,reset,save,wheel_zoom, box_zoom\" _hover =", "1) / float(ord_max - ord_min))] for y in df[\"HrsOrder\"]] df['colors']", "size=10) p.legend.location = \"top_right\" p.legend.click_policy = \"hide\" p.legend.background_fill_alpha = 0.3", "# HrsMode_Id = 1 low med_source = get_source(2) # HrsMode_Id", "= 0.3 p.legend.inactive_fill_alpha = 0.8 p.xaxis[0].formatter = date_formatter return p", "style=\"font-size: 15px; font-weight: bold;\">Y Upper: </span> <span style=\"font-size: 15px;\"> @y_upper</span>", "Time \" \\ \" from DQ_HrsOrder join NightInfo using (NightInfo_Id)", "x='Date', y='y_upper', color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter return p", "= pd.read_sql(sql, db.engine) source = ColumnDataSource(df) return source low_source =", "Min(HrsOrder)', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=low_source, x='Date', y='ord', color='red', fill_alpha=0.2, legend='Low',", "date_formatter return p @data_quality(name='hrs_order_position_medium', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\"", "font-weight: bold;\">Date: </span> <span style=\"font-size: 15px;\"> @Time</span> </div> <div> <span", "\\ .format(obsmode=obsmode) sql = \"select Date, y_upper, HrsOrder, CONVERT(Date,char) AS", "------- str: A <div> element with the Order plot. \"\"\"", "hours=[\"%H:%M\"], days=[\"%d %b\"], months=[\"%d %b %Y\"], years=[\"%b %Y\"]) def get_position_source(start_date,", "style=\"font-size: 15px;\"> @Time</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">Y", "\" \\ .format(obsmode=obsmode) sql = \"select Date, (Max(HrsOrder) - Min(HrsOrder))", "High Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date', y='y_upper',", "0: ord_min = df['HrsOrder'].min() ord_max = df['HrsOrder'].max() colors = [Plasma256[int((y", "= 3 high tool_list = \"pan,reset,save,wheel_zoom, box_zoom\" _hover = HoverTool(", "the HRS order for obsmode High, low and medium over", "df['HrsOrder'].max() colors = [Plasma256[int((y - ord_min) * (len(Plasma256) - 1)", "minutes=['%H:%M:%S'], hourmin=['%H:%M:'], hours=[\"%H:%M\"], days=[\"%d %b\"], months=[\"%d %b %Y\"], years=[\"%b %Y\"])", "from bokeh.plotting import figure, ColumnDataSource from app import db from", "Return a <div> element with the Order Position plot. The", "get_position_source(start_date, end_date, 3) # HrsMode_Id = 3 high tool_list =", "= \"hide\" p.legend.background_fill_alpha = 0.3 p.legend.inactive_fill_alpha = 0.8 p.xaxis[0].formatter =", "logic=logic) df = pd.read_sql(sql, db.engine) source = ColumnDataSource(df) return source", "Date, (Max(HrsOrder) - Min(HrsOrder)) as ord, CONVERT(Date, char) AS Time", "tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date', y='y_upper', color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter =", "tooltips=\"\"\" <div> <div> <span style=\"font-size: 15px; font-weight: bold;\">Date: </span> <span", "\\ .format(obsmode=obsmode) sql = \"select Date, (Max(HrsOrder) - Min(HrsOrder)) as", "\\ .format(start_date=start_date, end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine) colors =", "<div> element with the Order Position plot. The plot shows", "Low Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date', y='y_upper',", "end_date, 3) # HrsMode_Id = 3 high tool_list = \"pan,reset,save,wheel_zoom,", "start_date: date Earliest date to include in the plot. end_date:", "group by Date \" \\ .format(obsmode=obsmode) sql = \"select Date,", "- Min(HrsOrder)) as ord, CONVERT(Date, char) AS Time \" \\", "color='green', fill_alpha=0.2, legend='High', size=10) p.legend.location = \"top_right\" p.legend.click_policy = \"hide\"", "ord_min = df['HrsOrder'].min() ord_max = df['HrsOrder'].max() colors = [Plasma256[int((y -", "size=10) p.scatter(source=med_source, x='Date', y='ord', color='orange', fill_alpha=0.2, legend='Medium', size=10) p.scatter(source=high_source, x='Date',", "legend='Low', size=10) p.scatter(source=med_source, x='Date', y='ord', color='orange', fill_alpha=0.2, legend='Medium', size=10) p.scatter(source=high_source,", "y='y_upper', color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_low',", "<span style=\"font-size: 15px;\"> @Time</span> </div> <div> <span style=\"font-size: 15px; font-weight:", "db from app.decorators import data_quality # creates your plot date_formatter", "y='ord', color='green', fill_alpha=0.2, legend='High', size=10) p.legend.location = \"top_right\" p.legend.click_policy =", "obsmode): logic = \" and HrsMode_Id = {obsmode} \" \\", "from bokeh.palettes import Plasma256 from bokeh.plotting import figure, ColumnDataSource from", "_hover]) p.scatter(source=high_source, x='Date', y='y_upper', color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter", "style=\"font-size: 15px;\"> @HrsOrder</span> </div> </div> \"\"\" ) p = figure(title=\"HRS", "<div> <span style=\"font-size: 15px; font-weight: bold;\">Y Upper: </span> <span style=\"font-size:", "size=10) p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_low', caption=' ') def", "high_source = get_position_source(start_date, end_date, 3) # HrsMode_Id = 3 high", "import db from app.decorators import data_quality # creates your plot", "\"select Date, y_upper, HrsOrder, CONVERT(Date,char) AS Time \" \\ \"", "<'{end_date}' {logic}\" \\ .format(start_date=start_date, end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine)", "hourmin=['%H:%M:'], hours=[\"%H:%M\"], days=[\"%d %b\"], months=[\"%d %b %Y\"], years=[\"%b %Y\"]) def", "figure(title=\"HRS Order Position High Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover])", "source = ColumnDataSource(df) return source @data_quality(name='hrs_order', caption='HRS Order') def hrs_order_plot(start_date,", "p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_low', caption=' ') def hrs_order_position_plot(start_date,", "db.engine) colors = [] if len(df) > 0: ord_min =", "get_source(3) # HrsMode_Id = 3 high tool_list = \"pan,reset,save,wheel_zoom, box_zoom\"", "p @data_quality(name='hrs_order_position_high', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return a", "p = figure(title=\"HRS Order Position High Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime',", "Position Low Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date',", "y='y_upper', color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_medium',", "order for obsmode High resolution over time Params: ------- start_date:", "\"\"\" Return a <div> element with the Order Position plot.", "\" \\ \" from DQ_HrsOrder join NightInfo using (NightInfo_Id) \"", "sql = \"select Date, y_upper, HrsOrder, CONVERT(Date,char) AS Time \"", "import HoverTool from bokeh.models.formatters import DatetimeTickFormatter from bokeh.palettes import Plasma256", "15px; font-weight: bold;\">Y Upper: </span> <span style=\"font-size: 15px;\"> @y_upper</span> </div>", "</span> <span style=\"font-size: 15px;\"> @HrsOrder</span> </div> </div> \"\"\" ) p", "hrs_order_position_plot(start_date, end_date): \"\"\" Return a <div> element with the Order", "= ColumnDataSource(df) return source low_source = get_source(1) # HrsMode_Id =", "the plot. end_date: date Earliest date not to include in", "using (NightInfo_Id) \" \\ \" where Date > '{start_date}' and", ".format(obsmode=obsmode) sql = \"select Date, y_upper, HrsOrder, CONVERT(Date,char) AS Time", "tool_list = \"pan,reset,save,wheel_zoom, box_zoom\" _hover = HoverTool( tooltips=\"\"\" <div> <div>", "where Date > '{start_date}' and Date <'{end_date}' {logic}\" \\ .format(start_date=start_date,", "= ColumnDataSource(df) return source @data_quality(name='hrs_order', caption='HRS Order') def hrs_order_plot(start_date, end_date):", "ord_min) * (len(Plasma256) - 1) / float(ord_max - ord_min))] for", "days=[\"%d %b\"], months=[\"%d %b %Y\"], years=[\"%b %Y\"]) def get_position_source(start_date, end_date,", "import DatetimeTickFormatter from bokeh.palettes import Plasma256 from bokeh.plotting import figure,", "</div> <div> <span style=\"font-size: 15px; font-weight: bold;\">Y Upper: </span> <span", "style=\"font-size: 15px; font-weight: bold;\">HrsOrder(Max - Min): </span> <span style=\"font-size: 15px;\">", "sql = \"select Date, (Max(HrsOrder) - Min(HrsOrder)) as ord, CONVERT(Date,", "- Min(HrsOrder)', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=low_source, x='Date', y='ord', color='red', fill_alpha=0.2,", "y in df[\"HrsOrder\"]] df['colors'] = colors source = ColumnDataSource(df) return", "\" group by Date \" \\ .format(obsmode=obsmode) sql = \"select", "<div> element with the Order Position plot. \"\"\" high_source =", "Position Medium Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date',", "y_upper, HrsOrder, CONVERT(Date,char) AS Time \" \\ \" from DQ_HrsOrder", "'RORDER%%' \" \\ .format(obsmode=obsmode) sql = \"select Date, y_upper, HrsOrder,", "box_zoom\" _hover = HoverTool( tooltips=\"\"\" <div> <div> <span style=\"font-size: 15px;", "%b\"], months=[\"%d %b %Y\"], years=[\"%b %Y\"]) def get_position_source(start_date, end_date, obsmode):", "= get_source(1) # HrsMode_Id = 1 low med_source = get_source(2)", "data_quality # creates your plot date_formatter = DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'], seconds=[':%Ss'],", "like 'RORDER%%' \" \\ \" group by Date \" \\", "date_formatter = DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'], seconds=[':%Ss'], minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'], hourmin=['%H:%M:'], hours=[\"%H:%M\"], days=[\"%d", "Min(HrsOrder)) as ord, CONVERT(Date, char) AS Time \" \\ \"", "\" and FileName like 'RORDER%%' \" \\ \" group by", "= \" and HrsMode_Id = {obsmode} \" \\ \" and", "</span> <span style=\"font-size: 15px;\"> @Time</span> </div> <div> <span style=\"font-size: 15px;", "p @data_quality(name='hrs_order_position_low', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return a", "med_source = get_source(2) # HrsMode_Id = 2 med high_source =", "0.8 p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_high', caption=' ') def", "15px; font-weight: bold;\">Date: </span> <span style=\"font-size: 15px;\"> @Time</span> </div> <div>", "db.engine) source = ColumnDataSource(df) return source low_source = get_source(1) #", "p.legend.location = \"top_right\" p.legend.click_policy = \"hide\" p.legend.background_fill_alpha = 0.3 p.legend.inactive_fill_alpha", "\"\"\" ) p = figure(title=\"HRS Order\", x_axis_label='Date', y_axis_label='Max(HrsOrder) - Min(HrsOrder)',", "as ord, CONVERT(Date, char) AS Time \" \\ \" from", "\"\"\" high_source = get_position_source(start_date, end_date, 2) # HrsMode_Id = 3", "p = figure(title=\"HRS Order\", x_axis_label='Date', y_axis_label='Max(HrsOrder) - Min(HrsOrder)', x_axis_type='datetime', tools=[tool_list,", "df['colors'] = colors source = ColumnDataSource(df) return source @data_quality(name='hrs_order', caption='HRS", "@Time</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">Y Upper: </span>", "@Time</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">HrsOrder(Max - Min):", "obsmode High, low and medium over time Params: ------- start_date:", "HrsMode_Id = {obsmode} \" \\ \" and FileName like 'RORDER%%'", "color='red', fill_alpha=0.2, legend='Low', size=10) p.scatter(source=med_source, x='Date', y='ord', color='orange', fill_alpha=0.2, legend='Medium',", "HRS order for obsmode High, low and medium over time", "_hover = HoverTool( tooltips=\"\"\" <div> <div> <span style=\"font-size: 15px; font-weight:", "\"hide\" p.legend.background_fill_alpha = 0.3 p.legend.inactive_fill_alpha = 0.8 p.xaxis[0].formatter = date_formatter", "x_axis_label='Date', y_axis_label='Max(HrsOrder) - Min(HrsOrder)', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=low_source, x='Date', y='ord',", "to include in the plot. Return: ------- str: A <div>", ".format(start_date=start_date, end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine) colors = []", "get_source(2) # HrsMode_Id = 2 med high_source = get_source(3) #", "the Order plot. \"\"\" def get_source(obsmode): logic = \" and", "- ord_min))] for y in df[\"HrsOrder\"]] df['colors'] = colors source", ".format(start_date=start_date, end_date=end_date, logic=logic) df = pd.read_sql(sql, db.engine) source = ColumnDataSource(df)", "HrsMode_Id = 1 low med_source = get_source(2) # HrsMode_Id =", "tools=[tool_list, _hover]) p.scatter(source=low_source, x='Date', y='ord', color='red', fill_alpha=0.2, legend='Low', size=10) p.scatter(source=med_source,", "source = ColumnDataSource(df) return source low_source = get_source(1) # HrsMode_Id", "Upper: </span> <span style=\"font-size: 15px;\"> @y_upper</span> </div> <div> <span style=\"font-size:", "get_source(1) # HrsMode_Id = 1 low med_source = get_source(2) #", "source low_source = get_source(1) # HrsMode_Id = 1 low med_source", "get_position_source(start_date, end_date, 2) # HrsMode_Id = 3 high tool_list =", "x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=high_source, x='Date', y='y_upper', color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter", "x='Date', y='ord', color='orange', fill_alpha=0.2, legend='Medium', size=10) p.scatter(source=high_source, x='Date', y='ord', color='green',", "and Date <'{end_date}' {logic}\" \\ .format(start_date=start_date, end_date=end_date, logic=logic) df =", "= {obsmode} \" \\ \" and FileName like 'RORDER%%' \"", "def hrs_order_position_plot(start_date, end_date): \"\"\" Return a <div> element with the", "with the Order Position plot. The plot shows the HRS", "= pd.read_sql(sql, db.engine) colors = [] if len(df) > 0:", "p @data_quality(name='hrs_order_position_medium', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return a", "HrsOrder, CONVERT(Date,char) AS Time \" \\ \" from DQ_HrsOrder join", "AS Time \" \\ \" from DQ_HrsOrder join NightInfo using", "1 low med_source = get_source(2) # HrsMode_Id = 2 med", "15px;\"> @Time</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">HrsOrder(Max -", "15px;\"> @ord</span> </div> </div> \"\"\" ) p = figure(title=\"HRS Order\",", "15px; font-weight: bold;\">HRS Order: </span> <span style=\"font-size: 15px;\"> @HrsOrder</span> </div>", "\"\"\" high_source = get_position_source(start_date, end_date, 3) # HrsMode_Id = 3", "<div> element with the Order plot. The plot shows the", "# creates your plot date_formatter = DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'], seconds=[':%Ss'], minsec=[':%Mm:%Ss'],", "Order plot. \"\"\" def get_source(obsmode): logic = \" and HrsMode_Id", "_hover]) p.scatter(source=low_source, x='Date', y='ord', color='red', fill_alpha=0.2, legend='Low', size=10) p.scatter(source=med_source, x='Date',", "\" where Date > '{start_date}' and Date <'{end_date}' {logic}\" \\", "plot. \"\"\" def get_source(obsmode): logic = \" and HrsMode_Id =", "@data_quality(name='hrs_order_position_high', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return a <div>", "Order: </span> <span style=\"font-size: 15px;\"> @HrsOrder</span> </div> </div> \"\"\" )", "plot. The plot shows the HRS order for obsmode High,", "pandas as pd from bokeh.models import HoverTool from bokeh.models.formatters import", "<span style=\"font-size: 15px;\"> @ord</span> </div> </div> \"\"\" ) p =", "'{start_date}' and Date <'{end_date}' {logic}\" \\ .format(start_date=start_date, end_date=end_date, logic=logic) df", "\" \\ .format(obsmode=obsmode) sql = \"select Date, y_upper, HrsOrder, CONVERT(Date,char)", "</div> </div> \"\"\" ) p = figure(title=\"HRS Order Position Medium", "Earliest date not to include in the plot. Return: -------", "* (len(Plasma256) - 1) / float(ord_max - ord_min))] for y", "float(ord_max - ord_min))] for y in df[\"HrsOrder\"]] df['colors'] = colors", "------- start_date: date Earliest date to include in the plot.", "color='colors', fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_medium', caption='", "the Order Position plot. \"\"\" high_source = get_position_source(start_date, end_date, 2)", "logic=logic) df = pd.read_sql(sql, db.engine) colors = [] if len(df)", "= [Plasma256[int((y - ord_min) * (len(Plasma256) - 1) / float(ord_max", "') def hrs_order_position_plot(start_date, end_date): \"\"\" Return a <div> element with", "(len(Plasma256) - 1) / float(ord_max - ord_min))] for y in", "\\ \" and FileName like 'RORDER%%' \" \\ .format(obsmode=obsmode) sql", "@data_quality(name='hrs_order_position_low', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return a <div>", "font-weight: bold;\">Y Upper: </span> <span style=\"font-size: 15px;\"> @y_upper</span> </div> <div>", "\" and FileName like 'RORDER%%' \" \\ .format(obsmode=obsmode) sql =", "> '{start_date}' and Date <'{end_date}' {logic}\" \\ .format(start_date=start_date, end_date=end_date, logic=logic)", "Return: ------- str: A <div> element with the Order Position", "bokeh.palettes import Plasma256 from bokeh.plotting import figure, ColumnDataSource from app", "</div> \"\"\" ) p = figure(title=\"HRS Order Position High Resolution\",", "for obsmode High, low and medium over time Params: -------", "in the plot. end_date: date Earliest date not to include", "plot. Return: ------- str: A <div> element with the Order", "15px;\"> @HrsOrder</span> </div> </div> \"\"\" ) p = figure(title=\"HRS Order", "15px;\"> @Time</span> </div> <div> <span style=\"font-size: 15px; font-weight: bold;\">Y Upper:", "df[\"HrsOrder\"]] df['colors'] = colors source = ColumnDataSource(df) return source @data_quality(name='hrs_order',", "The plot shows the HRS order for obsmode High, low", "not to include in the plot. Return: ------- str: A", "(Max(HrsOrder) - Min(HrsOrder)) as ord, CONVERT(Date, char) AS Time \"", "<div> element with the Order plot. \"\"\" def get_source(obsmode): logic", "import pandas as pd from bokeh.models import HoverTool from bokeh.models.formatters", "element with the Order plot. The plot shows the HRS", "creates your plot date_formatter = DatetimeTickFormatter(microseconds=['%f'], milliseconds=['%S.%2Ns'], seconds=[':%Ss'], minsec=[':%Mm:%Ss'], minutes=['%H:%M:%S'],", "end_date: date Earliest date not to include in the plot.", "bold;\">HrsOrder(Max - Min): </span> <span style=\"font-size: 15px;\"> @ord</span> </div> </div>", "style=\"font-size: 15px;\"> @ord</span> </div> </div> \"\"\" ) p = figure(title=\"HRS", "> 0: ord_min = df['HrsOrder'].min() ord_max = df['HrsOrder'].max() colors =", "\"\"\"Return a <div> element with the Order plot. The plot", "/ float(ord_max - ord_min))] for y in df[\"HrsOrder\"]] df['colors'] =", "ColumnDataSource(df) return source @data_quality(name='hrs_order', caption='HRS Order') def hrs_order_plot(start_date, end_date): \"\"\"Return", "get_source(obsmode): logic = \" and HrsMode_Id = {obsmode} \" \\", "<span style=\"font-size: 15px; font-weight: bold;\">HrsOrder(Max - Min): </span> <span style=\"font-size:", "date to include in the plot. end_date: date Earliest date", "size=10) p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_medium', caption=' ') def", "from app import db from app.decorators import data_quality # creates", "ColumnDataSource from app import db from app.decorators import data_quality #", "ord_min))] for y in df[\"HrsOrder\"]] df['colors'] = colors source =", "style=\"font-size: 15px; font-weight: bold;\">Date: </span> <span style=\"font-size: 15px;\"> @Time</span> </div>", "figure(title=\"HRS Order Position Medium Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime', tools=[tool_list, _hover])", "p = figure(title=\"HRS Order Position Low Resolution\", x_axis_label='Date', y_axis_label='y_upper', x_axis_type='datetime',", "fill_alpha=0.2, size=10) p.xaxis[0].formatter = date_formatter return p @data_quality(name='hrs_order_position_low', caption=' ')", "plot. end_date: date Earliest date not to include in the", "y_axis_label='Max(HrsOrder) - Min(HrsOrder)', x_axis_type='datetime', tools=[tool_list, _hover]) p.scatter(source=low_source, x='Date', y='ord', color='red',", "to include in the plot. end_date: date Earliest date not", "Params: ------- start_date: date Earliest date to include in the", "font-weight: bold;\">HrsOrder(Max - Min): </span> <span style=\"font-size: 15px;\"> @ord</span> </div>", "@data_quality(name='hrs_order_position_medium', caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return a <div>", "caption=' ') def hrs_order_position_plot(start_date, end_date): \"\"\" Return a <div> element" ]
[ "superar es {limite}. La lista creada es \", end=\"\") for", "introducidos coincida con el número inicial. El programa termina escribiendo", "limite = int(input(\"Escribe limite:\")) valores = int(input(\"Escribe un valor:\")) listavalores", "otro valor\")) listavalores.append(valores) print(f\"El limite a superar es {limite}. La", "for i in range(len(listavalores)): print (listavalores[i], end=\" \") print(f\"ya que", "luego te pida números hasta que la suma de los", "lista de números. limite = int(input(\"Escribe limite:\")) valores = int(input(\"Escribe", "el número inicial. El programa termina escribiendo la lista de", "programa termina escribiendo la lista de números. limite = int(input(\"Escribe", "número y luego te pida números hasta que la suma", "un programa que te pida primero un número y luego", "limite a superar es {limite}. La lista creada es \",", "lista creada es \", end=\"\") for i in range(len(listavalores)): print", "te pida primero un número y luego te pida números", "números hasta que la suma de los números introducidos coincida", "= int(input(\"Escribe otro valor\")) listavalores.append(valores) print(f\"El limite a superar es", "escribiendo la lista de números. limite = int(input(\"Escribe limite:\")) valores", "un valor:\")) listavalores = [] listavalores.append(valores) while limite > sum(listavalores):", "\", end=\"\") for i in range(len(listavalores)): print (listavalores[i], end=\" \")", "de los números introducidos coincida con el número inicial. El", "los números introducidos coincida con el número inicial. El programa", "in range(len(listavalores)): print (listavalores[i], end=\" \") print(f\"ya que la suma", "inicial. El programa termina escribiendo la lista de números. limite", "sum(listavalores): valores = int(input(\"Escribe otro valor\")) listavalores.append(valores) print(f\"El limite a", "programa que te pida primero un número y luego te", "listavalores.append(valores) while limite > sum(listavalores): valores = int(input(\"Escribe otro valor\"))", "while limite > sum(listavalores): valores = int(input(\"Escribe otro valor\")) listavalores.append(valores)", "print(f\"El limite a superar es {limite}. La lista creada es", "pida números hasta que la suma de los números introducidos", "suma de los números introducidos coincida con el número inicial.", "<reponame>yannickbf-prog/python #<NAME>6e8 Escribe un programa que te pida primero un", "números. limite = int(input(\"Escribe limite:\")) valores = int(input(\"Escribe un valor:\"))", "valores = int(input(\"Escribe otro valor\")) listavalores.append(valores) print(f\"El limite a superar", "listavalores.append(valores) print(f\"El limite a superar es {limite}. La lista creada", "int(input(\"Escribe limite:\")) valores = int(input(\"Escribe un valor:\")) listavalores = []", "#<NAME>6e8 Escribe un programa que te pida primero un número", "= int(input(\"Escribe limite:\")) valores = int(input(\"Escribe un valor:\")) listavalores =", "primero un número y luego te pida números hasta que", "= int(input(\"Escribe un valor:\")) listavalores = [] listavalores.append(valores) while limite", "termina escribiendo la lista de números. limite = int(input(\"Escribe limite:\"))", "La lista creada es \", end=\"\") for i in range(len(listavalores)):", "la suma de los números introducidos coincida con el número", "limite:\")) valores = int(input(\"Escribe un valor:\")) listavalores = [] listavalores.append(valores)", "range(len(listavalores)): print (listavalores[i], end=\" \") print(f\"ya que la suma de", "un número y luego te pida números hasta que la", "coincida con el número inicial. El programa termina escribiendo la", "valor\")) listavalores.append(valores) print(f\"El limite a superar es {limite}. La lista", "número inicial. El programa termina escribiendo la lista de números.", "es \", end=\"\") for i in range(len(listavalores)): print (listavalores[i], end=\"", "end=\"\") for i in range(len(listavalores)): print (listavalores[i], end=\" \") print(f\"ya", "listavalores = [] listavalores.append(valores) while limite > sum(listavalores): valores =", "a superar es {limite}. La lista creada es \", end=\"\")", "Escribe un programa que te pida primero un número y", "con el número inicial. El programa termina escribiendo la lista", "end=\" \") print(f\"ya que la suma de estos numeros es", "números introducidos coincida con el número inicial. El programa termina", "print (listavalores[i], end=\" \") print(f\"ya que la suma de estos", "int(input(\"Escribe otro valor\")) listavalores.append(valores) print(f\"El limite a superar es {limite}.", "[] listavalores.append(valores) while limite > sum(listavalores): valores = int(input(\"Escribe otro", "pida primero un número y luego te pida números hasta", "que te pida primero un número y luego te pida", "de números. limite = int(input(\"Escribe limite:\")) valores = int(input(\"Escribe un", "creada es \", end=\"\") for i in range(len(listavalores)): print (listavalores[i],", "\") print(f\"ya que la suma de estos numeros es {sum(listavalores)}\")", "> sum(listavalores): valores = int(input(\"Escribe otro valor\")) listavalores.append(valores) print(f\"El limite", "(listavalores[i], end=\" \") print(f\"ya que la suma de estos numeros", "hasta que la suma de los números introducidos coincida con", "te pida números hasta que la suma de los números", "{limite}. La lista creada es \", end=\"\") for i in", "limite > sum(listavalores): valores = int(input(\"Escribe otro valor\")) listavalores.append(valores) print(f\"El", "es {limite}. La lista creada es \", end=\"\") for i", "= [] listavalores.append(valores) while limite > sum(listavalores): valores = int(input(\"Escribe", "que la suma de los números introducidos coincida con el", "El programa termina escribiendo la lista de números. limite =", "valor:\")) listavalores = [] listavalores.append(valores) while limite > sum(listavalores): valores", "i in range(len(listavalores)): print (listavalores[i], end=\" \") print(f\"ya que la", "int(input(\"Escribe un valor:\")) listavalores = [] listavalores.append(valores) while limite >", "la lista de números. limite = int(input(\"Escribe limite:\")) valores =", "y luego te pida números hasta que la suma de", "valores = int(input(\"Escribe un valor:\")) listavalores = [] listavalores.append(valores) while" ]
[ "self.add(command) def add(self, command): # type: (BaseCommand) -> Application \"\"\"", "config = ApplicationConfig(name, version) super(Application, self).__init__(config) if complete: self.add(CompletionsCommand()) def", "name.split(\" \") command = self.get_command(names[0]) for name in names[1:]: command", "self.get_command(names[0]) for name in names[1:]: command = command.get_sub_command(name) return command.config.handler", "ApplicationConfig class Application(ConsoleApplication, object): \"\"\" An Application is the container", "def add(self, command): # type: (BaseCommand) -> Application \"\"\" Adds", "Usage: >>> app = Application('myapp', '1.0 (stable)') >>> app.add(HelpCommand()) >>>", "= self.get_command(names[0]) for name in names[1:]: command = command.get_sub_command(name) return", "app = Application('myapp', '1.0 (stable)') >>> app.add(HelpCommand()) >>> app.run() \"\"\"", "name=None, version=None, complete=True, config=None ): # type: (str, str, bool,", "# type: (str, str, bool, Optional[ApplicationConfig]) -> None if config", "self).__init__(config) if complete: self.add(CompletionsCommand()) def add_commands(self, *commands): # type: (Tuple[BaseCommand])", "names = name.split(\" \") command = self.get_command(names[0]) for name in", "Tuple from clikit.console_application import ConsoleApplication from .commands import BaseCommand from", "is optimized for a standard CLI environment. Usage: >>> app", "# type: (str) -> BaseCommand names = name.split(\" \") command", "return self def find(self, name): # type: (str) -> BaseCommand", "from .commands.completions_command import CompletionsCommand from .config import ApplicationConfig class Application(ConsoleApplication,", ".commands.completions_command import CompletionsCommand from .config import ApplicationConfig class Application(ConsoleApplication, object):", ".commands import BaseCommand from .commands.completions_command import CompletionsCommand from .config import", "(BaseCommand) -> Application \"\"\" Adds a command object. \"\"\" self.add_command(command.config)", ">>> app = Application('myapp', '1.0 (stable)') >>> app.add(HelpCommand()) >>> app.run()", "name): # type: (str) -> BaseCommand names = name.split(\" \")", "command): # type: (BaseCommand) -> Application \"\"\" Adds a command", "str, bool, Optional[ApplicationConfig]) -> None if config is None: config", "add(self, command): # type: (BaseCommand) -> Application \"\"\" Adds a", "for command in commands: self.add(command) def add(self, command): # type:", "= Application('myapp', '1.0 (stable)') >>> app.add(HelpCommand()) >>> app.run() \"\"\" def", "from .config import ApplicationConfig class Application(ConsoleApplication, object): \"\"\" An Application", "Application('myapp', '1.0 (stable)') >>> app.add(HelpCommand()) >>> app.run() \"\"\" def __init__(", "import Tuple from clikit.console_application import ConsoleApplication from .commands import BaseCommand", "self, name=None, version=None, complete=True, config=None ): # type: (str, str,", "(stable)') >>> app.add(HelpCommand()) >>> app.run() \"\"\" def __init__( self, name=None,", "add_commands(self, *commands): # type: (Tuple[BaseCommand]) -> None for command in", "commands. This class is optimized for a standard CLI environment.", "None if config is None: config = ApplicationConfig(name, version) super(Application,", "Application \"\"\" Adds a command object. \"\"\" self.add_command(command.config) command.set_application(self) return", "type: (str) -> BaseCommand names = name.split(\" \") command =", "version=None, complete=True, config=None ): # type: (str, str, bool, Optional[ApplicationConfig])", "CLI environment. Usage: >>> app = Application('myapp', '1.0 (stable)') >>>", "self def find(self, name): # type: (str) -> BaseCommand names", "for a collection of commands. This class is optimized for", "Application(ConsoleApplication, object): \"\"\" An Application is the container for a", "__init__( self, name=None, version=None, complete=True, config=None ): # type: (str,", "\") command = self.get_command(names[0]) for name in names[1:]: command =", "object): \"\"\" An Application is the container for a collection", "a standard CLI environment. Usage: >>> app = Application('myapp', '1.0", "class Application(ConsoleApplication, object): \"\"\" An Application is the container for", "app.add(HelpCommand()) >>> app.run() \"\"\" def __init__( self, name=None, version=None, complete=True,", "from clikit.console_application import ConsoleApplication from .commands import BaseCommand from .commands.completions_command", "import CompletionsCommand from .config import ApplicationConfig class Application(ConsoleApplication, object): \"\"\"", "): # type: (str, str, bool, Optional[ApplicationConfig]) -> None if", "Optional[ApplicationConfig]) -> None if config is None: config = ApplicationConfig(name,", "a collection of commands. This class is optimized for a", "in commands: self.add(command) def add(self, command): # type: (BaseCommand) ->", "'1.0 (stable)') >>> app.add(HelpCommand()) >>> app.run() \"\"\" def __init__( self,", "Application is the container for a collection of commands. This", "type: (str, str, bool, Optional[ApplicationConfig]) -> None if config is", "None for command in commands: self.add(command) def add(self, command): #", "container for a collection of commands. This class is optimized", "<gh_stars>1-10 from typing import Optional from typing import Tuple from", "import ConsoleApplication from .commands import BaseCommand from .commands.completions_command import CompletionsCommand", "if complete: self.add(CompletionsCommand()) def add_commands(self, *commands): # type: (Tuple[BaseCommand]) ->", "is None: config = ApplicationConfig(name, version) super(Application, self).__init__(config) if complete:", "ConsoleApplication from .commands import BaseCommand from .commands.completions_command import CompletionsCommand from", "Adds a command object. \"\"\" self.add_command(command.config) command.set_application(self) return self def", "from .commands import BaseCommand from .commands.completions_command import CompletionsCommand from .config", "type: (BaseCommand) -> Application \"\"\" Adds a command object. \"\"\"", "# type: (BaseCommand) -> Application \"\"\" Adds a command object.", "\"\"\" self.add_command(command.config) command.set_application(self) return self def find(self, name): # type:", "a command object. \"\"\" self.add_command(command.config) command.set_application(self) return self def find(self,", "typing import Tuple from clikit.console_application import ConsoleApplication from .commands import", ">>> app.run() \"\"\" def __init__( self, name=None, version=None, complete=True, config=None", "the container for a collection of commands. This class is", "from typing import Tuple from clikit.console_application import ConsoleApplication from .commands", "-> None if config is None: config = ApplicationConfig(name, version)", "-> BaseCommand names = name.split(\" \") command = self.get_command(names[0]) for", "collection of commands. This class is optimized for a standard", "config=None ): # type: (str, str, bool, Optional[ApplicationConfig]) -> None", "environment. Usage: >>> app = Application('myapp', '1.0 (stable)') >>> app.add(HelpCommand())", "-> Application \"\"\" Adds a command object. \"\"\" self.add_command(command.config) command.set_application(self)", "\"\"\" def __init__( self, name=None, version=None, complete=True, config=None ): #", "find(self, name): # type: (str) -> BaseCommand names = name.split(\"", "for a standard CLI environment. Usage: >>> app = Application('myapp',", "app.run() \"\"\" def __init__( self, name=None, version=None, complete=True, config=None ):", "(str) -> BaseCommand names = name.split(\" \") command = self.get_command(names[0])", "of commands. This class is optimized for a standard CLI", "(str, str, bool, Optional[ApplicationConfig]) -> None if config is None:", "None: config = ApplicationConfig(name, version) super(Application, self).__init__(config) if complete: self.add(CompletionsCommand())", ".config import ApplicationConfig class Application(ConsoleApplication, object): \"\"\" An Application is", "bool, Optional[ApplicationConfig]) -> None if config is None: config =", "def find(self, name): # type: (str) -> BaseCommand names =", "class is optimized for a standard CLI environment. Usage: >>>", "commands: self.add(command) def add(self, command): # type: (BaseCommand) -> Application", "command.set_application(self) return self def find(self, name): # type: (str) ->", "typing import Optional from typing import Tuple from clikit.console_application import", "\"\"\" An Application is the container for a collection of", "= name.split(\" \") command = self.get_command(names[0]) for name in names[1:]:", "\"\"\" Adds a command object. \"\"\" self.add_command(command.config) command.set_application(self) return self", "CompletionsCommand from .config import ApplicationConfig class Application(ConsoleApplication, object): \"\"\" An", "self.add(CompletionsCommand()) def add_commands(self, *commands): # type: (Tuple[BaseCommand]) -> None for", "import ApplicationConfig class Application(ConsoleApplication, object): \"\"\" An Application is the", "from typing import Optional from typing import Tuple from clikit.console_application", "BaseCommand from .commands.completions_command import CompletionsCommand from .config import ApplicationConfig class", "object. \"\"\" self.add_command(command.config) command.set_application(self) return self def find(self, name): #", "optimized for a standard CLI environment. Usage: >>> app =", "*commands): # type: (Tuple[BaseCommand]) -> None for command in commands:", "-> None for command in commands: self.add(command) def add(self, command):", "This class is optimized for a standard CLI environment. Usage:", "clikit.console_application import ConsoleApplication from .commands import BaseCommand from .commands.completions_command import", "super(Application, self).__init__(config) if complete: self.add(CompletionsCommand()) def add_commands(self, *commands): # type:", "command in commands: self.add(command) def add(self, command): # type: (BaseCommand)", "Optional from typing import Tuple from clikit.console_application import ConsoleApplication from", "An Application is the container for a collection of commands.", "import BaseCommand from .commands.completions_command import CompletionsCommand from .config import ApplicationConfig", "config is None: config = ApplicationConfig(name, version) super(Application, self).__init__(config) if", "complete=True, config=None ): # type: (str, str, bool, Optional[ApplicationConfig]) ->", "# type: (Tuple[BaseCommand]) -> None for command in commands: self.add(command)", "command = self.get_command(names[0]) for name in names[1:]: command = command.get_sub_command(name)", "self.add_command(command.config) command.set_application(self) return self def find(self, name): # type: (str)", "if config is None: config = ApplicationConfig(name, version) super(Application, self).__init__(config)", "version) super(Application, self).__init__(config) if complete: self.add(CompletionsCommand()) def add_commands(self, *commands): #", "BaseCommand names = name.split(\" \") command = self.get_command(names[0]) for name", "complete: self.add(CompletionsCommand()) def add_commands(self, *commands): # type: (Tuple[BaseCommand]) -> None", "ApplicationConfig(name, version) super(Application, self).__init__(config) if complete: self.add(CompletionsCommand()) def add_commands(self, *commands):", "is the container for a collection of commands. This class", "(Tuple[BaseCommand]) -> None for command in commands: self.add(command) def add(self,", ">>> app.add(HelpCommand()) >>> app.run() \"\"\" def __init__( self, name=None, version=None,", "type: (Tuple[BaseCommand]) -> None for command in commands: self.add(command) def", "def __init__( self, name=None, version=None, complete=True, config=None ): # type:", "import Optional from typing import Tuple from clikit.console_application import ConsoleApplication", "command object. \"\"\" self.add_command(command.config) command.set_application(self) return self def find(self, name):", "standard CLI environment. Usage: >>> app = Application('myapp', '1.0 (stable)')", "= ApplicationConfig(name, version) super(Application, self).__init__(config) if complete: self.add(CompletionsCommand()) def add_commands(self,", "def add_commands(self, *commands): # type: (Tuple[BaseCommand]) -> None for command" ]
[ "(if necessary) and associates it with the user #\"\"\" #user", "associates it with the user #\"\"\" #user = instance #i", "necessary) and associates it with the user #\"\"\" #user =", "#\"\"\" #user = instance #i = user.get_profile().imap_servers.create() #user.get_profile().about = 'test'", "#user.save_profile() ## we want this called after every user is", "user #\"\"\" #user = instance #i = user.get_profile().imap_servers.create() #user.get_profile().about =", "blank imap server entry (if necessary) and associates it with", "instance #i = user.get_profile().imap_servers.create() #user.get_profile().about = 'test' #i.save() #user.save_profile() ##", "imap server entry (if necessary) and associates it with the", "#from django.dispatch import dispatcher #def UserProfilePostInsert(sender, instance, signal, *args, **kwargs):", "entry (if necessary) and associates it with the user #\"\"\"", "#user.get_profile().about = 'test' #i.save() #user.save_profile() ## we want this called", "instance, signal, *args, **kwargs): #\"\"\" #Inserts a blank imap server", "the user #\"\"\" #user = instance #i = user.get_profile().imap_servers.create() #user.get_profile().about", "we want this called after every user is inserted #dispatcher.connect(UserProfilePostInsert,", "a blank imap server entry (if necessary) and associates it", "and associates it with the user #\"\"\" #user = instance", "#Inserts a blank imap server entry (if necessary) and associates", "= user.get_profile().imap_servers.create() #user.get_profile().about = 'test' #i.save() #user.save_profile() ## we want", "= instance #i = user.get_profile().imap_servers.create() #user.get_profile().about = 'test' #i.save() #user.save_profile()", "## we want this called after every user is inserted", "signal, *args, **kwargs): #\"\"\" #Inserts a blank imap server entry", "with the user #\"\"\" #user = instance #i = user.get_profile().imap_servers.create()", "import dispatcher #def UserProfilePostInsert(sender, instance, signal, *args, **kwargs): #\"\"\" #Inserts", "user.get_profile().imap_servers.create() #user.get_profile().about = 'test' #i.save() #user.save_profile() ## we want this", "*args, **kwargs): #\"\"\" #Inserts a blank imap server entry (if", "it with the user #\"\"\" #user = instance #i =", "= 'test' #i.save() #user.save_profile() ## we want this called after", "#i = user.get_profile().imap_servers.create() #user.get_profile().about = 'test' #i.save() #user.save_profile() ## we", "want this called after every user is inserted #dispatcher.connect(UserProfilePostInsert, signal=signals.pre_save,", "'test' #i.save() #user.save_profile() ## we want this called after every", "this called after every user is inserted #dispatcher.connect(UserProfilePostInsert, signal=signals.pre_save, sender=User)", "UserProfilePostInsert(sender, instance, signal, *args, **kwargs): #\"\"\" #Inserts a blank imap", "dispatcher #def UserProfilePostInsert(sender, instance, signal, *args, **kwargs): #\"\"\" #Inserts a", "#def UserProfilePostInsert(sender, instance, signal, *args, **kwargs): #\"\"\" #Inserts a blank", "#i.save() #user.save_profile() ## we want this called after every user", "#\"\"\" #Inserts a blank imap server entry (if necessary) and", "#user = instance #i = user.get_profile().imap_servers.create() #user.get_profile().about = 'test' #i.save()", "server entry (if necessary) and associates it with the user", "django.dispatch import dispatcher #def UserProfilePostInsert(sender, instance, signal, *args, **kwargs): #\"\"\"", "**kwargs): #\"\"\" #Inserts a blank imap server entry (if necessary)" ]
[ "and not drawer.window.next and not drawer.window.previous: drawer.process() if drawer.window.next and", "name of the datafile\") parser.add_argument(\"--size\", help=\"width,height\") args = parser.parse_args() if", "utils.drawer import Drawer import argparse if __name__ == '__main__': parser", "= args.size.split(',') drawer = Drawer('data/'+args.name, [int(width), int(height)]) while not drawer.window.should_close():", "drawer.window.previous: drawer.process() if drawer.window.next and drawer.current + 2 < len(drawer.data_base.keys()):", "drawer.window.should_close(): drawer.update() # the main application loop while not drawer.window.should_close()", "drawer.process() if drawer.window.next and drawer.current + 2 < len(drawer.data_base.keys()): drawer.current", "drawer.window.previous and drawer.current > 0: drawer.current = drawer.current - 1", "while not drawer.window.should_close(): drawer.update() # the main application loop while", "from utils.drawer import Drawer import argparse if __name__ == '__main__':", "width, height = args.size.split(',') drawer = Drawer('data/'+args.name, [int(width), int(height)]) while", "drawer.current + 1 if drawer.window.previous and drawer.current > 0: drawer.current", "the datafile\") parser.add_argument(\"--size\", help=\"width,height\") args = parser.parse_args() if args.size is", "and drawer.current > 0: drawer.current = drawer.current - 1 drawer.window.next", "parser.parse_args() if args.size is None: width, height = 1280, 720", "else: width, height = args.size.split(',') drawer = Drawer('data/'+args.name, [int(width), int(height)])", "= drawer.current + 1 if drawer.window.previous and drawer.current > 0:", "1 if drawer.window.previous and drawer.current > 0: drawer.current = drawer.current", "== '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"name\", help=\"the name of the", "drawer.current = drawer.current - 1 drawer.window.next = False drawer.window.previous =", "[int(width), int(height)]) while not drawer.window.should_close(): drawer.update() # the main application", "drawer.window.should_close() and not drawer.window.next and not drawer.window.previous: drawer.process() if drawer.window.next", "720 else: width, height = args.size.split(',') drawer = Drawer('data/'+args.name, [int(width),", "= argparse.ArgumentParser() parser.add_argument(\"name\", help=\"the name of the datafile\") parser.add_argument(\"--size\", help=\"width,height\")", "if drawer.window.previous and drawer.current > 0: drawer.current = drawer.current -", "import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"name\",", "Drawer import argparse if __name__ == '__main__': parser = argparse.ArgumentParser()", "drawer.current - 1 drawer.window.next = False drawer.window.previous = False drawer.window.terminate()", "help=\"width,height\") args = parser.parse_args() if args.size is None: width, height", "args.size is None: width, height = 1280, 720 else: width,", "int(height)]) while not drawer.window.should_close(): drawer.update() # the main application loop", "the main application loop while not drawer.window.should_close() and not drawer.window.next", "args = parser.parse_args() if args.size is None: width, height =", "help=\"the name of the datafile\") parser.add_argument(\"--size\", help=\"width,height\") args = parser.parse_args()", "drawer.update() # the main application loop while not drawer.window.should_close() and", "= parser.parse_args() if args.size is None: width, height = 1280,", "args.size.split(',') drawer = Drawer('data/'+args.name, [int(width), int(height)]) while not drawer.window.should_close(): drawer.update()", "if args.size is None: width, height = 1280, 720 else:", "= Drawer('data/'+args.name, [int(width), int(height)]) while not drawer.window.should_close(): drawer.update() # the", "application loop while not drawer.window.should_close() and not drawer.window.next and not", "> 0: drawer.current = drawer.current - 1 drawer.window.next = False", "not drawer.window.should_close(): drawer.update() # the main application loop while not", "__name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"name\", help=\"the name of", "and not drawer.window.previous: drawer.process() if drawer.window.next and drawer.current + 2", "drawer.window.next and drawer.current + 2 < len(drawer.data_base.keys()): drawer.current = drawer.current", "drawer = Drawer('data/'+args.name, [int(width), int(height)]) while not drawer.window.should_close(): drawer.update() #", "width, height = 1280, 720 else: width, height = args.size.split(',')", "argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"name\", help=\"the", "is None: width, height = 1280, 720 else: width, height", "drawer.current = drawer.current + 1 if drawer.window.previous and drawer.current >", "<filename>watcher/fly.py from utils.drawer import Drawer import argparse if __name__ ==", "height = args.size.split(',') drawer = Drawer('data/'+args.name, [int(width), int(height)]) while not", "2 < len(drawer.data_base.keys()): drawer.current = drawer.current + 1 if drawer.window.previous", "parser.add_argument(\"name\", help=\"the name of the datafile\") parser.add_argument(\"--size\", help=\"width,height\") args =", "argparse.ArgumentParser() parser.add_argument(\"name\", help=\"the name of the datafile\") parser.add_argument(\"--size\", help=\"width,height\") args", "drawer.current + 2 < len(drawer.data_base.keys()): drawer.current = drawer.current + 1", "'__main__': parser = argparse.ArgumentParser() parser.add_argument(\"name\", help=\"the name of the datafile\")", "not drawer.window.next and not drawer.window.previous: drawer.process() if drawer.window.next and drawer.current", "parser = argparse.ArgumentParser() parser.add_argument(\"name\", help=\"the name of the datafile\") parser.add_argument(\"--size\",", "= drawer.current - 1 drawer.window.next = False drawer.window.previous = False", "None: width, height = 1280, 720 else: width, height =", "Drawer('data/'+args.name, [int(width), int(height)]) while not drawer.window.should_close(): drawer.update() # the main", "1280, 720 else: width, height = args.size.split(',') drawer = Drawer('data/'+args.name,", "+ 1 if drawer.window.previous and drawer.current > 0: drawer.current =", "< len(drawer.data_base.keys()): drawer.current = drawer.current + 1 if drawer.window.previous and", "loop while not drawer.window.should_close() and not drawer.window.next and not drawer.window.previous:", "+ 2 < len(drawer.data_base.keys()): drawer.current = drawer.current + 1 if", "= 1280, 720 else: width, height = args.size.split(',') drawer =", "and drawer.current + 2 < len(drawer.data_base.keys()): drawer.current = drawer.current +", "if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"name\", help=\"the name", "if drawer.window.next and drawer.current + 2 < len(drawer.data_base.keys()): drawer.current =", "# the main application loop while not drawer.window.should_close() and not", "while not drawer.window.should_close() and not drawer.window.next and not drawer.window.previous: drawer.process()", "len(drawer.data_base.keys()): drawer.current = drawer.current + 1 if drawer.window.previous and drawer.current", "0: drawer.current = drawer.current - 1 drawer.window.next = False drawer.window.previous", "not drawer.window.previous: drawer.process() if drawer.window.next and drawer.current + 2 <", "height = 1280, 720 else: width, height = args.size.split(',') drawer", "of the datafile\") parser.add_argument(\"--size\", help=\"width,height\") args = parser.parse_args() if args.size", "import Drawer import argparse if __name__ == '__main__': parser =", "drawer.window.next and not drawer.window.previous: drawer.process() if drawer.window.next and drawer.current +", "main application loop while not drawer.window.should_close() and not drawer.window.next and", "datafile\") parser.add_argument(\"--size\", help=\"width,height\") args = parser.parse_args() if args.size is None:", "not drawer.window.should_close() and not drawer.window.next and not drawer.window.previous: drawer.process() if", "drawer.current > 0: drawer.current = drawer.current - 1 drawer.window.next =", "parser.add_argument(\"--size\", help=\"width,height\") args = parser.parse_args() if args.size is None: width," ]
[ "], MasterKeyInfo: [ dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\",", "key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\" ) ], } @pytest.mark.parametrize(\"cls, kwargs\", all_valid_kwargs(VALID_KWARGS)) def test_attributes_valid_kwargs(cls,", "# # Licensed under the Apache License, Version 2.0 (the", "All Rights Reserved. # # Licensed under the Apache License,", "CONDITIONS OF # ANY KIND, either express or implied. See", "aws_encryption_sdk.identifiers import Algorithm, ContentType, ObjectType, SerializationVersion from aws_encryption_sdk.structures import DataKey,", "key_info=b\"<KEY>\"), data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\", ) ], EncryptedDataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"),", "the License. A copy of # the License is located", "dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), ], RawDataKey:", "(dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"key_info\", b\"<KEY>\"), ), ) def test_master_key_info_convert(kwargs, attribute, expected_value):", "def test_attributes_valid_kwargs(cls, kwargs): cls(**kwargs) @pytest.mark.parametrize(\"cls, kwargs\", all_invalid_kwargs(VALID_KWARGS)) def test_attributes_invalid_kwargs(cls, kwargs):", "\"asfoijwae\"), (dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"), \"key_info\", b\"<KEY>\"), (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"key_info\", b\"<KEY>\"), ),", "under the Apache License, Version 2.0 (the \"License\"). You #", "for the specific # language governing permissions and limitations under", "limitations under the License. \"\"\"Unit test suite for aws_encryption_sdk.structures\"\"\" import", "type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\", encryption_context={}, encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA, content_aad_length=32456, header_iv_length=32456, frame_length=234567, )", "MasterKeyInfo, MessageHeader, RawDataKey from .unit_test_utils import all_invalid_kwargs, all_valid_kwargs pytestmark =", "{ MessageHeader: [ dict( version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\", encryption_context={}, encrypted_data_keys=set([]),", "key_info=b\"ajsnoiajerofi\"), ], RawDataKey: [ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\") ], DataKey: [", "encryption_context={}, encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA, content_aad_length=32456, header_iv_length=32456, frame_length=234567, ) ], MasterKeyInfo: [", "encrypted_data_key=b\"aisofiawjef\", ) ], EncryptedDataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\" )", "attribute, expected_value\", ( (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\",", "aws_encryption_sdk.structures\"\"\" import pytest from aws_encryption_sdk.identifiers import Algorithm, ContentType, ObjectType, SerializationVersion", "not use this file except in compliance with the License.", "# # http://aws.amazon.com/apache2.0/ # # or in the \"license\" file", "import DataKey, EncryptedDataKey, MasterKeyInfo, MessageHeader, RawDataKey from .unit_test_utils import all_invalid_kwargs,", "EncryptedDataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\" ) ], } @pytest.mark.parametrize(\"cls,", "ContentType, ObjectType, SerializationVersion from aws_encryption_sdk.structures import DataKey, EncryptedDataKey, MasterKeyInfo, MessageHeader,", "cls(**kwargs) @pytest.mark.parametrize(\"cls, kwargs\", all_invalid_kwargs(VALID_KWARGS)) def test_attributes_invalid_kwargs(cls, kwargs): with pytest.raises(TypeError): cls(**kwargs)", "all_valid_kwargs pytestmark = [pytest.mark.unit, pytest.mark.local] VALID_KWARGS = { MessageHeader: [", "encrypted_data_key=b\"aisofiawjef\" ) ], } @pytest.mark.parametrize(\"cls, kwargs\", all_valid_kwargs(VALID_KWARGS)) def test_attributes_valid_kwargs(cls, kwargs):", "data_key=b\"<KEY>\") ], DataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\", )", "kwargs\", all_invalid_kwargs(VALID_KWARGS)) def test_attributes_invalid_kwargs(cls, kwargs): with pytest.raises(TypeError): cls(**kwargs) @pytest.mark.parametrize( \"kwargs,", "<filename>test/unit/test_structures.py # Copyright 2017 Amazon.com, Inc. or its affiliates. All", "# http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "file accompanying this file. This file is # distributed on", "# # or in the \"license\" file accompanying this file.", "See the License for the specific # language governing permissions", "VALID_KWARGS = { MessageHeader: [ dict( version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\",", ") ], EncryptedDataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\" ) ],", "pytest.raises(TypeError): cls(**kwargs) @pytest.mark.parametrize( \"kwargs, attribute, expected_value\", ( (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\",", "MessageHeader, RawDataKey from .unit_test_utils import all_invalid_kwargs, all_valid_kwargs pytestmark = [pytest.mark.unit,", "Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.", "WARRANTIES OR CONDITIONS OF # ANY KIND, either express or", "accompanying this file. This file is # distributed on an", "from .unit_test_utils import all_invalid_kwargs, all_valid_kwargs pytestmark = [pytest.mark.unit, pytest.mark.local] VALID_KWARGS", "ANY KIND, either express or implied. See the License for", "@pytest.mark.parametrize(\"cls, kwargs\", all_valid_kwargs(VALID_KWARGS)) def test_attributes_valid_kwargs(cls, kwargs): cls(**kwargs) @pytest.mark.parametrize(\"cls, kwargs\", all_invalid_kwargs(VALID_KWARGS))", ") def test_master_key_info_convert(kwargs, attribute, expected_value): test = MasterKeyInfo(**kwargs) assert getattr(test,", "key_info=b\"<KEY>\"), \"key_info\", b\"<KEY>\"), ), ) def test_master_key_info_convert(kwargs, attribute, expected_value): test", "2.0 (the \"License\"). You # may not use this file", "key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\", ) ], EncryptedDataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\",", "# or in the \"license\" file accompanying this file. This", "Rights Reserved. # # Licensed under the Apache License, Version", "aws_encryption_sdk.structures import DataKey, EncryptedDataKey, MasterKeyInfo, MessageHeader, RawDataKey from .unit_test_utils import", "\"key_info\", b\"<KEY>\"), ), ) def test_master_key_info_convert(kwargs, attribute, expected_value): test =", "all_invalid_kwargs, all_valid_kwargs pytestmark = [pytest.mark.unit, pytest.mark.local] VALID_KWARGS = { MessageHeader:", "the \"license\" file accompanying this file. This file is #", "EncryptedDataKey, MasterKeyInfo, MessageHeader, RawDataKey from .unit_test_utils import all_invalid_kwargs, all_valid_kwargs pytestmark", "= [pytest.mark.unit, pytest.mark.local] VALID_KWARGS = { MessageHeader: [ dict( version=SerializationVersion.V1,", "either express or implied. See the License for the specific", "\"key_info\", b\"<KEY>\"), (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"key_info\", b\"<KEY>\"), ), ) def test_master_key_info_convert(kwargs,", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY", "RawDataKey: [ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\") ], DataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\",", "2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. #", "all_invalid_kwargs(VALID_KWARGS)) def test_attributes_invalid_kwargs(cls, kwargs): with pytest.raises(TypeError): cls(**kwargs) @pytest.mark.parametrize( \"kwargs, attribute,", "except in compliance with the License. A copy of #", "A copy of # the License is located at #", "[ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\") ], DataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"),", "expected_value\", ( (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"),", "# Licensed under the Apache License, Version 2.0 (the \"License\").", "all_valid_kwargs(VALID_KWARGS)) def test_attributes_valid_kwargs(cls, kwargs): cls(**kwargs) @pytest.mark.parametrize(\"cls, kwargs\", all_invalid_kwargs(VALID_KWARGS)) def test_attributes_invalid_kwargs(cls,", "MessageHeader: [ dict( version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\", encryption_context={}, encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA,", "cls(**kwargs) @pytest.mark.parametrize( \"kwargs, attribute, expected_value\", ( (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"),", "Version 2.0 (the \"License\"). You # may not use this", "\"kwargs, attribute, expected_value\", ( (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"),", "\"asfoijwae\"), (dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"), \"key_info\", b\"<KEY>\"), (dict(provider_id=\"asfoijwae\",", "MasterKeyInfo: [ dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"),", "(dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"),", "permissions and limitations under the License. \"\"\"Unit test suite for", "this file except in compliance with the License. A copy", "Reserved. # # Licensed under the Apache License, Version 2.0", "pytest from aws_encryption_sdk.identifiers import Algorithm, ContentType, ObjectType, SerializationVersion from aws_encryption_sdk.structures", "import Algorithm, ContentType, ObjectType, SerializationVersion from aws_encryption_sdk.structures import DataKey, EncryptedDataKey,", "Algorithm, ContentType, ObjectType, SerializationVersion from aws_encryption_sdk.structures import DataKey, EncryptedDataKey, MasterKeyInfo,", "frame_length=234567, ) ], MasterKeyInfo: [ dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\",", "DataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\", ) ], EncryptedDataKey:", "kwargs\", all_valid_kwargs(VALID_KWARGS)) def test_attributes_valid_kwargs(cls, kwargs): cls(**kwargs) @pytest.mark.parametrize(\"cls, kwargs\", all_invalid_kwargs(VALID_KWARGS)) def", "kwargs): with pytest.raises(TypeError): cls(**kwargs) @pytest.mark.parametrize( \"kwargs, attribute, expected_value\", ( (dict(provider_id=\"asfoijwae\",", "dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), ], RawDataKey: [ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\",", "\"license\" file accompanying this file. This file is # distributed", "# language governing permissions and limitations under the License. \"\"\"Unit", "suite for aws_encryption_sdk.structures\"\"\" import pytest from aws_encryption_sdk.identifiers import Algorithm, ContentType,", "dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), ], RawDataKey: [ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\")", "key_info=b\"<KEY>\"), data_key=b\"<KEY>\") ], DataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\",", "or in the \"license\" file accompanying this file. This file", "key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), ], RawDataKey: [", "with the License. A copy of # the License is", "key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"), \"key_info\",", "RawDataKey from .unit_test_utils import all_invalid_kwargs, all_valid_kwargs pytestmark = [pytest.mark.unit, pytest.mark.local]", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either", "License is located at # # http://aws.amazon.com/apache2.0/ # # or", "Amazon.com, Inc. or its affiliates. All Rights Reserved. # #", "file is # distributed on an \"AS IS\" BASIS, WITHOUT", "[ dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), ],", "OF # ANY KIND, either express or implied. See the", "key_info=\"<KEY>\"), \"key_info\", b\"<KEY>\"), (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"key_info\", b\"<KEY>\"), ), ) def", "\"License\"). You # may not use this file except in", "), ) def test_master_key_info_convert(kwargs, attribute, expected_value): test = MasterKeyInfo(**kwargs) assert", "This file is # distributed on an \"AS IS\" BASIS,", "is located at # # http://aws.amazon.com/apache2.0/ # # or in", "key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\" ) ], } @pytest.mark.parametrize(\"cls, kwargs\", all_valid_kwargs(VALID_KWARGS)) def", "[pytest.mark.unit, pytest.mark.local] VALID_KWARGS = { MessageHeader: [ dict( version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA,", "# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights", "License, Version 2.0 (the \"License\"). You # may not use", "and limitations under the License. \"\"\"Unit test suite for aws_encryption_sdk.structures\"\"\"", "b\"<KEY>\"), (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"key_info\", b\"<KEY>\"), ), ) def test_master_key_info_convert(kwargs, attribute,", "test suite for aws_encryption_sdk.structures\"\"\" import pytest from aws_encryption_sdk.identifiers import Algorithm,", "b\"<KEY>\"), ), ) def test_master_key_info_convert(kwargs, attribute, expected_value): test = MasterKeyInfo(**kwargs)", "or its affiliates. All Rights Reserved. # # Licensed under", "content_type=ContentType.FRAMED_DATA, content_aad_length=32456, header_iv_length=32456, frame_length=234567, ) ], MasterKeyInfo: [ dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"),", "file. This file is # distributed on an \"AS IS\"", "\"\"\"Unit test suite for aws_encryption_sdk.structures\"\"\" import pytest from aws_encryption_sdk.identifiers import", "key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), ], RawDataKey: [ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\") ],", "version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\", encryption_context={}, encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA, content_aad_length=32456, header_iv_length=32456, frame_length=234567,", "( (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=\"asfoijwae\",", "Licensed under the Apache License, Version 2.0 (the \"License\"). You", "test_attributes_invalid_kwargs(cls, kwargs): with pytest.raises(TypeError): cls(**kwargs) @pytest.mark.parametrize( \"kwargs, attribute, expected_value\", (", "language governing permissions and limitations under the License. \"\"\"Unit test", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF #", "specific # language governing permissions and limitations under the License.", "Inc. or its affiliates. All Rights Reserved. # # Licensed", "\"provider_id\", \"asfoijwae\"), (dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"), \"key_info\", b\"<KEY>\"), (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"key_info\", b\"<KEY>\"),", ") ], } @pytest.mark.parametrize(\"cls, kwargs\", all_valid_kwargs(VALID_KWARGS)) def test_attributes_valid_kwargs(cls, kwargs): cls(**kwargs)", "pytestmark = [pytest.mark.unit, pytest.mark.local] VALID_KWARGS = { MessageHeader: [ dict(", "express or implied. See the License for the specific #", "KIND, either express or implied. See the License for the", "@pytest.mark.parametrize( \"kwargs, attribute, expected_value\", ( (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=b\"asfoijwae\",", "License for the specific # language governing permissions and limitations", "], RawDataKey: [ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\") ], DataKey: [ dict(", "import pytest from aws_encryption_sdk.identifiers import Algorithm, ContentType, ObjectType, SerializationVersion from", "key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"), \"key_info\", b\"<KEY>\"), (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"key_info\",", "dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\") ], DataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\",", "[ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\" ) ], } @pytest.mark.parametrize(\"cls, kwargs\",", "[ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\", ) ], EncryptedDataKey: [", "(dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"), \"key_info\", b\"<KEY>\"), (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"),", "of # the License is located at # # http://aws.amazon.com/apache2.0/", "# the License is located at # # http://aws.amazon.com/apache2.0/ #", "its affiliates. All Rights Reserved. # # Licensed under the", "[ dict( version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\", encryption_context={}, encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA, content_aad_length=32456,", "@pytest.mark.parametrize(\"cls, kwargs\", all_invalid_kwargs(VALID_KWARGS)) def test_attributes_invalid_kwargs(cls, kwargs): with pytest.raises(TypeError): cls(**kwargs) @pytest.mark.parametrize(", "\"provider_id\", \"asfoijwae\"), (dict(provider_id=b\"asfoijwae\", key_info=b\"<KEY>\"), \"provider_id\", \"asfoijwae\"), (dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"), \"key_info\", b\"<KEY>\"),", "# may not use this file except in compliance with", "or implied. See the License for the specific # language", "copy of # the License is located at # #", "file except in compliance with the License. A copy of", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "def test_attributes_invalid_kwargs(cls, kwargs): with pytest.raises(TypeError): cls(**kwargs) @pytest.mark.parametrize( \"kwargs, attribute, expected_value\",", ".unit_test_utils import all_invalid_kwargs, all_valid_kwargs pytestmark = [pytest.mark.unit, pytest.mark.local] VALID_KWARGS =", "key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), ], RawDataKey: [ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"),", "(dict(provider_id=\"asfoijwae\", key_info=\"<KEY>\"), \"key_info\", b\"<KEY>\"), (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"), \"key_info\", b\"<KEY>\"), ), )", "= { MessageHeader: [ dict( version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\", encryption_context={},", "dict( version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\", encryption_context={}, encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA, content_aad_length=32456, header_iv_length=32456,", "dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\", ) ], EncryptedDataKey: [ dict(", "Apache License, Version 2.0 (the \"License\"). You # may not", "from aws_encryption_sdk.structures import DataKey, EncryptedDataKey, MasterKeyInfo, MessageHeader, RawDataKey from .unit_test_utils", "dict(provider_id=b\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"), ], RawDataKey: [ dict(key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\") ], DataKey:", "pytest.mark.local] VALID_KWARGS = { MessageHeader: [ dict( version=SerializationVersion.V1, type=ObjectType.CUSTOMER_AE_DATA, algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384,", "You # may not use this file except in compliance", "the specific # language governing permissions and limitations under the", "content_aad_length=32456, header_iv_length=32456, frame_length=234567, ) ], MasterKeyInfo: [ dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\",", "compliance with the License. A copy of # the License", "License. A copy of # the License is located at", "is # distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "for aws_encryption_sdk.structures\"\"\" import pytest from aws_encryption_sdk.identifiers import Algorithm, ContentType, ObjectType,", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND,", "DataKey, EncryptedDataKey, MasterKeyInfo, MessageHeader, RawDataKey from .unit_test_utils import all_invalid_kwargs, all_valid_kwargs", "import all_invalid_kwargs, all_valid_kwargs pytestmark = [pytest.mark.unit, pytest.mark.local] VALID_KWARGS = {", "attribute, expected_value): test = MasterKeyInfo(**kwargs) assert getattr(test, attribute) == expected_value", "], EncryptedDataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\" ) ], }", "(the \"License\"). You # may not use this file except", "# ANY KIND, either express or implied. See the License", "under the License. \"\"\"Unit test suite for aws_encryption_sdk.structures\"\"\" import pytest", "use this file except in compliance with the License. A", "kwargs): cls(**kwargs) @pytest.mark.parametrize(\"cls, kwargs\", all_invalid_kwargs(VALID_KWARGS)) def test_attributes_invalid_kwargs(cls, kwargs): with pytest.raises(TypeError):", "test_attributes_valid_kwargs(cls, kwargs): cls(**kwargs) @pytest.mark.parametrize(\"cls, kwargs\", all_invalid_kwargs(VALID_KWARGS)) def test_attributes_invalid_kwargs(cls, kwargs): with", "the License for the specific # language governing permissions and", "], } @pytest.mark.parametrize(\"cls, kwargs\", all_valid_kwargs(VALID_KWARGS)) def test_attributes_valid_kwargs(cls, kwargs): cls(**kwargs) @pytest.mark.parametrize(\"cls,", "def test_master_key_info_convert(kwargs, attribute, expected_value): test = MasterKeyInfo(**kwargs) assert getattr(test, attribute)", "data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\", ) ], EncryptedDataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\"", "http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying this", "algorithm=Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, message_id=b\"aosiejfoaiwej\", encryption_context={}, encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA, content_aad_length=32456, header_iv_length=32456, frame_length=234567, ) ],", "located at # # http://aws.amazon.com/apache2.0/ # # or in the", "with pytest.raises(TypeError): cls(**kwargs) @pytest.mark.parametrize( \"kwargs, attribute, expected_value\", ( (dict(provider_id=\"asfoijwae\", key_info=b\"<KEY>\"),", "License. \"\"\"Unit test suite for aws_encryption_sdk.structures\"\"\" import pytest from aws_encryption_sdk.identifiers", "test_master_key_info_convert(kwargs, attribute, expected_value): test = MasterKeyInfo(**kwargs) assert getattr(test, attribute) ==", ") ], MasterKeyInfo: [ dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=\"fawnofijawef\", key_info=b\"ajsnoiajerofi\"),", "implied. See the License for the specific # language governing", "encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA, content_aad_length=32456, header_iv_length=32456, frame_length=234567, ) ], MasterKeyInfo: [ dict(provider_id=\"fawnofijawef\",", "affiliates. All Rights Reserved. # # Licensed under the Apache", "may not use this file except in compliance with the", "this file. This file is # distributed on an \"AS", "the License is located at # # http://aws.amazon.com/apache2.0/ # #", "the Apache License, Version 2.0 (the \"License\"). You # may", "in the \"license\" file accompanying this file. This file is", "SerializationVersion from aws_encryption_sdk.structures import DataKey, EncryptedDataKey, MasterKeyInfo, MessageHeader, RawDataKey from", "message_id=b\"aosiejfoaiwej\", encryption_context={}, encrypted_data_keys=set([]), content_type=ContentType.FRAMED_DATA, content_aad_length=32456, header_iv_length=32456, frame_length=234567, ) ], MasterKeyInfo:", "at # # http://aws.amazon.com/apache2.0/ # # or in the \"license\"", "governing permissions and limitations under the License. \"\"\"Unit test suite", "# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "header_iv_length=32456, frame_length=234567, ) ], MasterKeyInfo: [ dict(provider_id=\"fawnofijawef\", key_info=\"ajsnoiajerofi\"), dict(provider_id=b\"fawnofijawef\", key_info=\"ajsnoiajerofi\"),", "], DataKey: [ dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), data_key=b\"<KEY>\", encrypted_data_key=b\"aisofiawjef\", ) ],", "the License. \"\"\"Unit test suite for aws_encryption_sdk.structures\"\"\" import pytest from", "ObjectType, SerializationVersion from aws_encryption_sdk.structures import DataKey, EncryptedDataKey, MasterKeyInfo, MessageHeader, RawDataKey", "in compliance with the License. A copy of # the", "from aws_encryption_sdk.identifiers import Algorithm, ContentType, ObjectType, SerializationVersion from aws_encryption_sdk.structures import", "dict( key_provider=MasterKeyInfo(provider_id=\"asjnoa\", key_info=b\"<KEY>\"), encrypted_data_key=b\"aisofiawjef\" ) ], } @pytest.mark.parametrize(\"cls, kwargs\", all_valid_kwargs(VALID_KWARGS))", "} @pytest.mark.parametrize(\"cls, kwargs\", all_valid_kwargs(VALID_KWARGS)) def test_attributes_valid_kwargs(cls, kwargs): cls(**kwargs) @pytest.mark.parametrize(\"cls, kwargs\",", "WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express", "OR CONDITIONS OF # ANY KIND, either express or implied." ]
[ "right') plt.title(title) #rcc_train[(rcc_train.saldo>=0.2)&(rcc_train.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation <3\", alpha=0.5) #rcc_train[(rcc_test.saldo>=0.2)&(rcc_test.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation <3\", alpha=0.5)", "data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x, y],label=labels, bins = bins, alpha=alpha) plt.legend(loc='upper right') plt.title(title)", "target and it will graph a hist of values def", "data1[(data1>=l_range[0])&(data1<l_range[1])] y = data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x, y],label=labels, bins = bins, alpha=alpha)", "seaborn as sns import matplotlib.pyplot as plt import numpy as", "0.7 and more for p in ax.patches: height = p.get_height()", "in ax.patches: height = p.get_height() ax.text(p.get_x()+p.get_width()/2., height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name)", "\"+str(int(total))+\" users\" if title_name is None else title_name+\" of \"+str(int(total))+\"", "title_name is None else title_name+\" of \"+str(int(total))+\" users\" ax =", "ax = sns.countplot(x=name, data=data) # for Seaborn version 0.7 and", "# plot histograms of train and test to understand the", "title_name = \"Target distribution\"+\" of \"+str(int(total))+\" users\" if title_name is", "per row title_name = \"Target distribution\"+\" of \"+str(int(total))+\" users\" if", "version 0.7 and more for p in ax.patches: height =", "will graph a hist of values def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize) total", "= data1[(data1>=l_range[0])&(data1<l_range[1])] y = data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x, y],label=labels, bins = bins,", "it will graph a hist of values def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize)", "histograms of train and test to understand the differences between", "understand the differences between them def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x = data1[(data1>=l_range[0])&(data1<l_range[1])]", "matplotlib.pyplot as plt import numpy as np path_results = '../results/images/'", "= \"Target distribution\"+\" of \"+str(int(total))+\" users\" if title_name is None", "for Seaborn version 0.7 and more for p in ax.patches:", "p in ax.patches: height = p.get_height() ax.text(p.get_x()+p.get_width()/2., height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10", "def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize) total = float(len(data)) # one person per", "of values def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize) total = float(len(data)) # one", "as sns import matplotlib.pyplot as plt import numpy as np", "title_name+\" of \"+str(int(total))+\" users\" ax = sns.countplot(x=name, data=data) # for", "is None else title_name+\" of \"+str(int(total))+\" users\" ax = sns.countplot(x=name,", "as np path_results = '../results/images/' # this function receives a", "import seaborn as sns import matplotlib.pyplot as plt import numpy", "the differences between them def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x = data1[(data1>=l_range[0])&(data1<l_range[1])] y", "Seaborn version 0.7 and more for p in ax.patches: height", "binary target and it will graph a hist of values", "plt.title(title_name) plt.show() if save: figure = ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches =", "numpy as np path_results = '../results/images/' # this function receives", "y],label=labels, bins = bins, alpha=alpha) plt.legend(loc='upper right') plt.title(title) #rcc_train[(rcc_train.saldo>=0.2)&(rcc_train.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation", "to understand the differences between them def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x =", "graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize) total = float(len(data)) # one person per row", "receives a dataset with binary target and it will graph", "users\" ax = sns.countplot(x=name, data=data) # for Seaborn version 0.7", "values def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize) total = float(len(data)) # one person", "if title_name is None else title_name+\" of \"+str(int(total))+\" users\" ax", "'tight') # plot histograms of train and test to understand", "test to understand the differences between them def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x", "= p.get_height() ax.text(p.get_x()+p.get_width()/2., height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name) plt.show() if save:", "path_results = '../results/images/' # this function receives a dataset with", "users\" if title_name is None else title_name+\" of \"+str(int(total))+\" users\"", "save: figure = ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches = 'tight') # plot", "ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches = 'tight') # plot histograms of train", "graph a hist of values def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize) total =", "plt.hist([x, y],label=labels, bins = bins, alpha=alpha) plt.legend(loc='upper right') plt.title(title) #rcc_train[(rcc_train.saldo>=0.2)&(rcc_train.saldo<3)].saldo.plot.hist(title=\"Fraud", "np path_results = '../results/images/' # this function receives a dataset", "of train and test to understand the differences between them", "bins, alpha=alpha) plt.legend(loc='upper right') plt.title(title) #rcc_train[(rcc_train.saldo>=0.2)&(rcc_train.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation <3\", alpha=0.5) #rcc_train[(rcc_test.saldo>=0.2)&(rcc_test.saldo<3)].saldo.plot.hist(title=\"Fraud", "float(len(data)) # one person per row title_name = \"Target distribution\"+\"", "height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name) plt.show() if save: figure = ax.get_figure()", "dataset with binary target and it will graph a hist", "plt.legend(loc='upper right') plt.title(title) #rcc_train[(rcc_train.saldo>=0.2)&(rcc_train.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation <3\", alpha=0.5) #rcc_train[(rcc_test.saldo>=0.2)&(rcc_test.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation <3\",", "as plt import numpy as np path_results = '../results/images/' #", "bins = bins, alpha=alpha) plt.legend(loc='upper right') plt.title(title) #rcc_train[(rcc_train.saldo>=0.2)&(rcc_train.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation <3\",", "= ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches = 'tight') # plot histograms of", "plt.show() if save: figure = ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches = 'tight')", "= data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x, y],label=labels, bins = bins, alpha=alpha) plt.legend(loc='upper right')", "for p in ax.patches: height = p.get_height() ax.text(p.get_x()+p.get_width()/2., height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height),", "y = data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x, y],label=labels, bins = bins, alpha=alpha) plt.legend(loc='upper", "figure = ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches = 'tight') # plot histograms", "ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name) plt.show() if save: figure = ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches", "sns import matplotlib.pyplot as plt import numpy as np path_results", "pd import seaborn as sns import matplotlib.pyplot as plt import", "person per row title_name = \"Target distribution\"+\" of \"+str(int(total))+\" users\"", "a dataset with binary target and it will graph a", "them def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x = data1[(data1>=l_range[0])&(data1<l_range[1])] y = data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x,", "# this function receives a dataset with binary target and", "plt import numpy as np path_results = '../results/images/' # this", "\"Target distribution\"+\" of \"+str(int(total))+\" users\" if title_name is None else", "import matplotlib.pyplot as plt import numpy as np path_results =", "as pd import seaborn as sns import matplotlib.pyplot as plt", "'{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name) plt.show() if save: figure = ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400,", "if save: figure = ax.get_figure() figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches = 'tight') #", "data=data) # for Seaborn version 0.7 and more for p", "ax.text(p.get_x()+p.get_width()/2., height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name) plt.show() if save: figure =", "plt.figure(figsize=figsize) total = float(len(data)) # one person per row title_name", "with binary target and it will graph a hist of", "= '../results/images/' # this function receives a dataset with binary", "row title_name = \"Target distribution\"+\" of \"+str(int(total))+\" users\" if title_name", "more for p in ax.patches: height = p.get_height() ax.text(p.get_x()+p.get_width()/2., height/3,", "alpha=alpha) plt.legend(loc='upper right') plt.title(title) #rcc_train[(rcc_train.saldo>=0.2)&(rcc_train.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation <3\", alpha=0.5) #rcc_train[(rcc_test.saldo>=0.2)&(rcc_test.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation", "of \"+str(int(total))+\" users\" if title_name is None else title_name+\" of", "distribution\"+\" of \"+str(int(total))+\" users\" if title_name is None else title_name+\"", "one person per row title_name = \"Target distribution\"+\" of \"+str(int(total))+\"", "figure.savefig(path_results+name_file+'.png',dpi=400, bbox_inches = 'tight') # plot histograms of train and", "plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x = data1[(data1>=l_range[0])&(data1<l_range[1])] y = data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x, y],label=labels, bins", "else title_name+\" of \"+str(int(total))+\" users\" ax = sns.countplot(x=name, data=data) #", "None else title_name+\" of \"+str(int(total))+\" users\" ax = sns.countplot(x=name, data=data)", "\"+str(int(total))+\" users\" ax = sns.countplot(x=name, data=data) # for Seaborn version", "function receives a dataset with binary target and it will", "= sns.countplot(x=name, data=data) # for Seaborn version 0.7 and more", "between them def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x = data1[(data1>=l_range[0])&(data1<l_range[1])] y = data2[(data2>=l_range[0])&(data2<l_range[1])]", "of \"+str(int(total))+\" users\" ax = sns.countplot(x=name, data=data) # for Seaborn", "= 'tight') # plot histograms of train and test to", "= bins, alpha=alpha) plt.legend(loc='upper right') plt.title(title) #rcc_train[(rcc_train.saldo>=0.2)&(rcc_train.saldo<3)].saldo.plot.hist(title=\"Fraud Tranascation <3\", alpha=0.5)", "and more for p in ax.patches: height = p.get_height() ax.text(p.get_x()+p.get_width()/2.,", "'../results/images/' # this function receives a dataset with binary target", "plot histograms of train and test to understand the differences", "= float(len(data)) # one person per row title_name = \"Target", "differences between them def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x = data1[(data1>=l_range[0])&(data1<l_range[1])] y =", "# one person per row title_name = \"Target distribution\"+\" of", "def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5): x = data1[(data1>=l_range[0])&(data1<l_range[1])] y = data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x, y],label=labels,", "train and test to understand the differences between them def", "ax.patches: height = p.get_height() ax.text(p.get_x()+p.get_width()/2., height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name) plt.show()", "x = data1[(data1>=l_range[0])&(data1<l_range[1])] y = data2[(data2>=l_range[0])&(data2<l_range[1])] plt.hist([x, y],label=labels, bins =", "bbox_inches = 'tight') # plot histograms of train and test", "hist of values def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize) total = float(len(data)) #", "and test to understand the differences between them def plot_comp_hist(data1,data2,l_range=[-np.inf,np.inf],labels=['x','y'],title='histogram',bins=20,alpha=0.5):", "p.get_height() ax.text(p.get_x()+p.get_width()/2., height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name) plt.show() if save: figure", "a hist of values def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'): plt.figure(figsize=figsize) total = float(len(data))", "height = p.get_height() ax.text(p.get_x()+p.get_width()/2., height/3, '{:.2f}%\\n{:d}'.format(100*height/total,height), ha=\"center\",color=color_text,fontweight='bold')#fontsize=10 plt.title(title_name) plt.show() if", "and it will graph a hist of values def graph_target(data,name=\"target\",figsize=(6,4),title_name=None,color_text=\"white\",save=False,name_file='target_distribution'):", "# for Seaborn version 0.7 and more for p in", "this function receives a dataset with binary target and it", "total = float(len(data)) # one person per row title_name =", "pandas as pd import seaborn as sns import matplotlib.pyplot as", "import numpy as np path_results = '../results/images/' # this function", "import pandas as pd import seaborn as sns import matplotlib.pyplot", "sns.countplot(x=name, data=data) # for Seaborn version 0.7 and more for" ]
[ "from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.utils.translation", "_('This slug has an invalid value: %(value)s.'), code='invalid', params={'value': value},", "logic if value in self.blacklist: raise ValidationError( _('This slug has", ") @deconstructible class EventSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck', 'locale',", "class EventSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck', 'locale', 'control', 'redirect',", "] @deconstructible class OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck', 'locale',", "'events', ] @deconstructible class OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck',", "Validation logic if value in self.blacklist: raise ValidationError( _('This slug", "# Validation logic if value in self.blacklist: raise ValidationError( _('This", "from django.utils.translation import ugettext_lazy as _ class BlacklistValidator: blacklist =", "[ 'download', 'healthcheck', 'locale', 'control', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__',", "blacklist = [ 'download', 'healthcheck', 'locale', 'control', 'pretixdroid', 'redirect', 'jsi18n',", "'control', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__', 'api', 'events', ] @deconstructible", "@deconstructible class EventSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck', 'locale', 'control',", "import ValidationError from django.utils.deconstruct import deconstructible from django.utils.translation import ugettext_lazy", "from django.utils.deconstruct import deconstructible from django.utils.translation import ugettext_lazy as _", "if value in self.blacklist: raise ValidationError( _('This slug has an", "%(value)s.'), code='invalid', params={'value': value}, ) @deconstructible class EventSlugBlacklistValidator(BlacklistValidator): blacklist =", "invalid value: %(value)s.'), code='invalid', params={'value': value}, ) @deconstructible class EventSlugBlacklistValidator(BlacklistValidator):", "'jsi18n', 'metrics', '_global', '__debug__', 'api', 'events', ] @deconstructible class OrganizerSlugBlacklistValidator(BlacklistValidator):", "value): # Validation logic if value in self.blacklist: raise ValidationError(", "= [ 'download', 'healthcheck', 'locale', 'control', 'redirect', 'jsi18n', 'metrics', '_global',", "value}, ) @deconstructible class EventSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck',", "[ 'download', 'healthcheck', 'locale', 'control', 'pretixdroid', 'redirect', 'jsi18n', 'metrics', '_global',", "code='invalid', params={'value': value}, ) @deconstructible class EventSlugBlacklistValidator(BlacklistValidator): blacklist = [", "'healthcheck', 'locale', 'control', 'pretixdroid', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__', 'about',", "django.utils.deconstruct import deconstructible from django.utils.translation import ugettext_lazy as _ class", "class BlacklistValidator: blacklist = [] def __call__(self, value): # Validation", "import ugettext_lazy as _ class BlacklistValidator: blacklist = [] def", "self.blacklist: raise ValidationError( _('This slug has an invalid value: %(value)s.'),", "django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.utils.translation import", "@deconstructible class OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck', 'locale', 'control',", "in self.blacklist: raise ValidationError( _('This slug has an invalid value:", "class OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck', 'locale', 'control', 'pretixdroid',", "'locale', 'control', 'pretixdroid', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__', 'about', 'api',", "'api', 'events', ] @deconstructible class OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download',", "'control', 'pretixdroid', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__', 'about', 'api', ]", "'metrics', '_global', '__debug__', 'api', 'events', ] @deconstructible class OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist", "ugettext_lazy as _ class BlacklistValidator: blacklist = [] def __call__(self,", "as _ class BlacklistValidator: blacklist = [] def __call__(self, value):", "= [ 'download', 'healthcheck', 'locale', 'control', 'pretixdroid', 'redirect', 'jsi18n', 'metrics',", "EventSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck', 'locale', 'control', 'redirect', 'jsi18n',", "'download', 'healthcheck', 'locale', 'control', 'pretixdroid', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__',", "import deconstructible from django.utils.translation import ugettext_lazy as _ class BlacklistValidator:", "[] def __call__(self, value): # Validation logic if value in", "deconstructible from django.utils.translation import ugettext_lazy as _ class BlacklistValidator: blacklist", "def __call__(self, value): # Validation logic if value in self.blacklist:", "value in self.blacklist: raise ValidationError( _('This slug has an invalid", "django.utils.translation import ugettext_lazy as _ class BlacklistValidator: blacklist = []", "slug has an invalid value: %(value)s.'), code='invalid', params={'value': value}, )", "has an invalid value: %(value)s.'), code='invalid', params={'value': value}, ) @deconstructible", "'_global', '__debug__', 'api', 'events', ] @deconstructible class OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist =", "BlacklistValidator: blacklist = [] def __call__(self, value): # Validation logic", "raise ValidationError( _('This slug has an invalid value: %(value)s.'), code='invalid',", "ValidationError( _('This slug has an invalid value: %(value)s.'), code='invalid', params={'value':", "ValidationError from django.utils.deconstruct import deconstructible from django.utils.translation import ugettext_lazy as", "_ class BlacklistValidator: blacklist = [] def __call__(self, value): #", "value: %(value)s.'), code='invalid', params={'value': value}, ) @deconstructible class EventSlugBlacklistValidator(BlacklistValidator): blacklist", "'healthcheck', 'locale', 'control', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__', 'api', 'events',", "'locale', 'control', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__', 'api', 'events', ]", "= [] def __call__(self, value): # Validation logic if value", "params={'value': value}, ) @deconstructible class EventSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download',", "blacklist = [ 'download', 'healthcheck', 'locale', 'control', 'redirect', 'jsi18n', 'metrics',", "OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist = [ 'download', 'healthcheck', 'locale', 'control', 'pretixdroid', 'redirect',", "'__debug__', 'api', 'events', ] @deconstructible class OrganizerSlugBlacklistValidator(BlacklistValidator): blacklist = [", "'download', 'healthcheck', 'locale', 'control', 'redirect', 'jsi18n', 'metrics', '_global', '__debug__', 'api',", "__call__(self, value): # Validation logic if value in self.blacklist: raise", "'redirect', 'jsi18n', 'metrics', '_global', '__debug__', 'api', 'events', ] @deconstructible class", "blacklist = [] def __call__(self, value): # Validation logic if", "an invalid value: %(value)s.'), code='invalid', params={'value': value}, ) @deconstructible class" ]
[ "None cog._eject(self) def get_cog(self, name: str) -> Optional[Cog]: \"\"\"Gets the", "except Exception: # if the load failed, the remnants should", "self._check_once if call_once else self._checks try: list_.remove(func) except ValueError: pass", "called. Parameters ---------- coro The coroutine to register as the", "raise TypeError('Cogs must derive from Cog.') cog = cog._inject(self) self.__cogs[cog.__cog_name__]", "= self.help_command if help_command and help_command.cog is cog: help_command.cog =", "substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS", "starting with ``!?``. This is especially important when passing an", "the collection. You cannot set both `owner_id` and `owner_ids`. This", "func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that adds a \"call", "equivalent to a call to :meth:`~.Bot.get_context` followed by a call", "noqa view = StringView(message.content) ctx = cls(prefix=None, view=view, bot=self, message=message)", "raise ExtensionFailed(key, e) from e try: setup = getattr(lib, 'extension_setup')", "self.all_commands.get(invoker) return ctx def _print_error(self, ctx: Context, error: Exception) ->", "a :class:`.Context`. .. note:: Similar to :meth:`~.Bot.before_invoke`\\, this is not", "fails mid-reload then the bot will roll-back to the prior", "{}:'.format(ctx.command), file=sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__, file=sys.stderr ) async", "def invoke(self, ctx: Context) -> None: \"\"\"|coro| Invokes the command", "the prefix of. Returns -------- Union[List[:class:`str`], :class:`str`] A list of", "to get the prefix of. Returns -------- Union[List[:class:`str`], :class:`str`] A", "to reload. It must be dot separated like regular Python", "content must contain initially to have a command invoked. This", "well. If no cog is found then this method has", "under :meth:`~.Bot.invoke`. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to", "cancel: _cancel_futs(pending) return future async def _wait_for_error_return(self, futures: List[asyncio.Future], ctx:", "do miscellaneous clean-up if necessary. This function takes a single", "res = func(ctx) if not res: return False return True", "FortniteHelpCommand() else: self.help_command = help_command self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message', self.process_commands) def", "remove_check(self, func: MaybeCoro, *, call_once: bool = False) -> None:", "want to import ``foo/test.py``. Raises ------ ExtensionNotFound The extension could", "command {}:'.format(ctx.command), file=sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__, file=sys.stderr )", "if an operation fails mid-reload then the bot will roll-back", "this coroutine is called automatically when a new message is", "view = StringView(message.content) ctx = cls(prefix=None, view=view, bot=self, message=message) prefix", "sys.modules[module] def _load_from_module_spec(self, spec: types.ModuleType, key: str) -> None: #", "modules modules = { name: module for name, module in", "extension name to extension. \"\"\" return types.MappingProxyType(self.__extensions) @property def help_command(self)", "checks and argument parsing procedures pass without error. If any", "listeners from the module for event_list in self._events.copy().values(): remove =", "from the module for cmd in self.all_commands.copy().values(): if cmd.module is", "-> MaybeCoro: r\"\"\"A decorator that registers a coroutine as a", "self.get_prefix(message) invoked_prefix = prefix if isinstance(prefix, str): if not view.skip_string(prefix):", "message content must contain initially to have a command invoked.", "extension in tuple(self.__extensions): try: self.unload_extension(extension) except Exception: pass for cog", "self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key) raise ExtensionFailed(key, e) from e else: self.__extensions[key]", "def dispatch_error(self, ctx: Context, error: Exception) -> None: if self._event_has_handler('command_error'):", "iterables are not allowed. .. note:: When passing multiple prefixes", "not be imported. ExtensionAlreadyLoaded The extension is already loaded. ExtensionMissingEntryPoint", "Parameters ------------ name: :class:`str` The extension name to reload. It", "if not isinstance(ret, str): try: ret = list(ret) except TypeError:", "None: def check(future): return future.result() is False ret = await", "Retrieves the prefix the bot is listening to with the", "event dispatch mechanisms. Parameters ----------- ctx: :class:`.Context` The invocation context", "Cog]: \"\"\"Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog name to", "takes in the bot as its first parameter and :class:`fortnitepy.FriendMessage`", "remove from the global checks. call_once: :class:`bool` If the function", "kwargs.get('case_insensitive', False) super().__init__(auth, **kwargs) self.command_prefix = command_prefix self.description = inspect.cleandoc(description)", "or a coroutine. This function takes a single parameter, :class:`.Context`,", "ctx, error) asyncio.ensure_future(self._wait_for_error_return( futures, ctx, error )) else: self._print_error(ctx, error)", "None: \"\"\"Adds a global check to the bot. This is", "str, child: str) -> bool: return parent == child or", "bypasses that and ensures that it's called only once, even", "pre-invoke hook is called directly before the command is called.", "and returns the prefix. This is to facilitate \"dynamic\" command", "with the message as a context. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`,", "checks that call this method. owner_ids: Optional[Collection[:class:`int`]] The user IDs", "except CommandError as exc: await ctx.command.dispatch_error(ctx, exc) else: self.dispatch_event('command_completion', ctx)", "except AttributeError: del sys.modules[key] raise ExtensionMissingEntryPoint(key) try: setup(self) except Exception", "global_check(ctx): # Allows only party commands. return ctx.party is not", "called directly after the command is called. This makes it", "commands that have been registered to the bot and other", "is recommended to use a :class:`set` for the collection. You", "post-invoke hook. A post-invoke hook is called directly after the", "bool: data = self._check_once if call_once else self._checks if len(data)", "A read-only mapping of extension name to extension. \"\"\" return", "if dispatch_close: await asyncio.gather( self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'), ) for extension in", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "prefix is ``('!', '!?')`` the ``'!?'`` prefix will never be", "normal and raise back to caller sys.modules.update(modules) raise @property def", "'failed.') except CommandError as exc: await ctx.command.dispatch_error(ctx, exc) else: self.dispatch_event('command_completion',", "imports if accessing a sub-module. e.g. ``foo.test`` if you want", "'{}'.format(ret.__class__.__name__)) if not ret: raise ValueError('Iterable command_prefix must contain at", "persons to whom the Software is furnished to do so,", "all checks and argument parsing procedures pass without error. If", "is None: try: self.add_command(obj) except CommandError: traceback.print_exc() continue super().register_methods() async", "the bot will roll-back to the prior working state. Parameters", "be triggered. By default, this coroutine is called automatically when", "user ID that owns the bot. This is used by", ".help import HelpCommand, FortniteHelpCommand from .typedefs import Message log =", "matched to any message as the previous one matches messages", "self if obj.parent is None: try: self.add_command(obj) except CommandError: traceback.print_exc()", "The coroutine to register as the pre-invoke hook. Raises ------", "a coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook", "to the bot. Raises ------ TypeError The cog does not", "of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "Optional, Mapping, Set from fortnitepy.client import Client from fortnitepy.auth import", "regular function or a coroutine. This function takes a single", "from the load_extension function call # so let's load it", "# noqa prefix = ret = self.command_prefix if callable(prefix): if", "a user id is the owner of the bot. Parameters", "implementing a help command, see :ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`] The user", "as a pre-invoke hook. A pre-invoke hook is called directly", "asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke", "from get_prefix must ' 'contain only strings, not ' '{}'.format(value.__class__.__name__))", "Checks if a user id is the owner of the", "read-only mapping of cog name to cog. \"\"\" return types.MappingProxyType(self.__cogs)", "help_command.cog = None cog._eject(self) def get_cog(self, name: str) -> Optional[Cog]:", "Context, error: Exception) -> None: if self._event_has_handler('command_error'): futures = self.dispatch_event('command_error',", "called only once per :meth:`Command.invoke` call. Regular global checks are", "tuple(self.__extensions): try: self.unload_extension(extension) except Exception: pass for cog in tuple(self.__cogs):", "that it's called only once, even inside the default help", "runtime. To remove the help command pass ``None``. For more", "-> bool: \"\"\"|coro| Checks if a user id is the", "' 'returning either of these, not ' '{}'.format(ret.__class__.__name__)) if not", "This replaces the extension with the same extension, only refreshed.", "with our own error if that's the case. if isinstance(ret,", "other low level tools, and is equivalent to a call", "the cog to remove. \"\"\" cog = self.__cogs.pop(name, None) if", "checks that call this method. \"\"\" def __init__(self, command_prefix: Any,", "def get_cog(self, name: str) -> Optional[Cog]: \"\"\"Gets the cog instance", "name: str) -> None: # find all references to the", "context, :attr:`.Context.valid` must be checked to make sure it is.", "noqa prefix = ret = self.command_prefix if callable(prefix): if asyncio.iscoroutinefunction(prefix):", "message is received. This is built using other low level", "to groups. You must set it to every group if", "register to the bot. Raises ------ TypeError The cog does", "def add_check(self, func: MaybeCoro, *, call_once: bool = False) ->", "remove_cog(self, name: str) -> None: \"\"\"Removes a cog from the", "name) } try: # Unload and then load the module...", "None: try: self.add_command(obj) except CommandError: traceback.print_exc() continue super().register_methods() async def", ":class:`.Context`, and can only raise exceptions inherited from :exc:`.CommandError`. Example", "not a valid candidate to be invoked under :meth:`~.Bot.invoke`. Parameters", "is :class:`.Context`. Should a custom class be provided, it must", "Returns ------- :class:`.Context` The invocation context. The type of this", "the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception: # if", "When the extension is unloaded, all commands, listeners, and cogs", "-> None: print( 'Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr )", "that registers a coroutine as a pre-invoke hook. A pre-invoke", ":class:`py:types.ModuleType`]: A read-only mapping of extension name to extension. \"\"\"", "functions ' 'failed.') except CommandError as exc: await ctx.command.dispatch_error(ctx, exc)", "must be a coroutine.') self._before_invoke = coro return coro def", "This makes it a useful function to clean-up database connections", "fortnitepy.typedefs import MaybeCoro, ListOrTuple from ._types import _BaseCommand from .errors", "return coro def after_invoke(self, coro: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator", "up database connections or any type of set up required.", "prefix') return ret async def get_context(self, message: Message, *, cls:", "of the bot. Parameters ---------- user_id: :class:`str` The user id", "Bot(GroupMixin, Client): \"\"\"Represents a fortnite bot. This class is a", "help_command: Optional[:class:`.HelpCommand`] The help command implementation to use. This can", "command invoked. This prefix could either be a string to", "furnished to do so, subject to the following conditions: The", "else: return user_id in self.owner_ids def before_invoke(self, coro: MaybeCoro) ->", "Client from fortnitepy.auth import Auth from fortnitepy.typedefs import MaybeCoro, ListOrTuple", "Parameters ----------- name: :class:`str` The name of the cog you", "name) def unload_extension(self, name: str) -> None: \"\"\"Unloads an extension.", "func(ctx) else: res = func(ctx) if not res: return False", "isinstance(ret, str): try: ret = list(ret) except TypeError: # It's", "from :class:`.Cog`. CommandError An error happened during loading. \"\"\" if", "be a coroutine.') self._before_invoke = coro return coro def after_invoke(self,", "counter-part for :meth:`.process_commands` to allow users more fine grained control", "prefix of. Returns -------- Union[List[:class:`str`], :class:`str`] A list of prefixes", "name: str) -> None: \"\"\"Atomically reloads an extension. This replaces", "str) -> None: \"\"\"Loads an extension. An extension is a", "\"\"\" # noqa view = StringView(message.content) ctx = cls(prefix=None, view=view,", "the bot. Parameters ---------- func The function to remove from", "the default help command. .. note:: This function can either", "\"Software\"), to deal in the Software without restriction, including without", "command_prefix must contain at ' 'least one prefix') return ret", "it is. If the context is not valid then it", "_wait_for_error_return(self, futures: List[asyncio.Future], ctx: Context, error: Exception) -> None: def", "as the prefix always matches, enabling prefix-less command invocation. The", "extension with the same extension, only refreshed. This is equivalent", "owner_ids: Optional[Collection[:class:`int`]] The user IDs that owns the bot. This", "def add_cog(self, cog: Cog) -> None: \"\"\"Adds a \"cog\" to", "await ctx.command.invoke(ctx) else: raise CheckFailure('The global check once functions '", "return parent == child or child.startswith(parent + \".\") class _DefaultRepr:", "the global checks. call_once: :class:`bool` If the function was added", "The extension was not loaded. ExtensionNotFound The extension could not", "if view.skip_string(element): invoked_prefix = element break else: invoked_prefix = None", "not loaded. ExtensionNotFound The extension could not be imported. ExtensionMissingEntryPoint", "The message to get the invocation context from. cls The", "CheckFailure, CommandError, CommandNotFound) from .core import GroupMixin from .cog import", "a single parameter, the ``bot``, similar to ``extension_setup`` from :meth:`~.Bot.load_extension`.", "str: return '<default-help-command>' _default = _DefaultRepr() class Bot(GroupMixin, Client): \"\"\"Represents", "the function should only be called once per :meth:`Command.invoke` call.", "bool: \"\"\"|coro| Checks if a user id is the owner", "The extension name to reload. It must be dot separated", "and self.owner_ids: raise TypeError('Both owner_id and owner_ids are set.') if", "for. \"\"\" # noqa prefix = ret = self.command_prefix if", "close(self, *, close_http: bool = True, dispatch_close: bool = True)", "extension name to reload. It must be dot separated like", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "single argument, the ``bot``. Parameters ---------- name: :class:`str` The extension", ":class:`.GroupMixin` to provide the functionality to manage commands. Attributes -----------", "You must set it to every group if you require", "not None: self.dispatch_event('command', ctx) try: if await self.can_run(ctx, call_once=True): await", "not be imported. ExtensionMissingEntryPoint The extension does not have a", "hook is called directly before the command is called. This", "is what the message content must contain initially to have", "TypeError('get_prefix must return either a string ' 'or a list", "None: try: func = getattr(lib, 'cog_teardown') except AttributeError: pass else:", "all commands, listeners, and cogs are removed from the bot", "lib.extension_setup(self) self.__extensions[name] = lib # revert sys.modules back to normal", "the module # remove the cogs registered from the module", "# replace it with our own error if that's the", "False) -> None: \"\"\"Removes a global check from the bot.", "however, **always** called regardless of the internal command callback raising", "enumerate(event_list): if (event.__module__ is not None and _is_submodule(name, event.__module__)): remove.append(index)", "ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name) if spec is None: raise ExtensionNotFound(name)", "isinstance(ret, collections.abc.Iterable): raise raise TypeError('command_prefix must be plain string, '", "commands to be case insensitive as well. description: :class:`str` The", "cancel: bool = False) -> None: def _cancel_futs(pending_futures: Set[asyncio.Future]) ->", "accessing a sub-module. e.g. ``foo.test`` if you want to import", "files (the \"Software\"), to deal in the Software without restriction,", ":class:`fortnitepy.Client` you can do with this bot. This class also", "async def wait_for_futures(self, futures: ListOrTuple, *, check: Optional[callable] = None,", "the rights to use, copy, modify, merge, publish, distribute, sublicense,", "is not a valid candidate to be invoked under :meth:`~.Bot.invoke`.", "if _is_submodule(name, cog.__module__): self.remove_cog(cogname) # remove all the commands from", ":class:`.Cog` The cog to register to the bot. Raises ------", "p.cancelled(): p.cancel() pending = futures while pending: done, pending =", "[] self._check_once = [] self._help_command = None self._before_invoke = None", "must contain initially to have a command invoked. This prefix", "OTHER DEALINGS IN THE SOFTWARE. \"\"\" import logging import inspect", "timeout: Optional[int] = None, cancel: bool = False) -> None:", "ctx.invoked_with: exc = CommandNotFound('Command \"{}\" is not found' ''.format(ctx.invoked_with)) self.dispatch_error(ctx,", "software and associated documentation files (the \"Software\"), to deal in", "and event listeners that the cog has registered will be", "coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must", ".. note:: When passing multiple prefixes be careful to not", "an error (i.e. :exc:`.CommandInvokeError`\\). This makes it ideal for clean-up", "call this method. owner_ids: Optional[Collection[:class:`int`]] The user IDs that owns", "an extension. This replaces the extension with the same extension,", "is hereby granted, free of charge, to any person obtaining", "del sys.modules[module] def _load_from_module_spec(self, spec: types.ModuleType, key: str) -> None:", "be dot separated like regular Python imports if accessing a", "equivalent to the name passed via keyword argument in class", "else: return ctx except TypeError: if not isinstance(prefix, list): raise", "this is :class:`.Context`. Should a custom class be provided, it", "== self.owner_id else: return user_id in self.owner_ids def before_invoke(self, coro:", "Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to get the", ":class:`bool` Whether the commands should be case insensitive. Defaults to", "self.__extensions[name] = lib # revert sys.modules back to normal and", "= None, **kwargs: Any) -> None: kwargs['case_insensitive'] = kwargs.get('case_insensitive', False)", "-> None: for p in pending_futures: if not p.cancelled(): p.cancel()", "def extensions(self) -> Mapping[str, types.ModuleType]: \"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping", "to the following conditions: The above copyright notice and this", "a regular function or a coroutine. An empty string as", "database connections or any type of clean up required. This", "self.help_command = help_command self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message', self.process_commands) def register_methods(self) ->", "the bot. This is the non-decorator interface to :meth:`.check` and", "= False) -> bool: data = self._check_once if call_once else", "or a callable that takes in the bot as its", "Exception: pass for cog in tuple(self.__cogs): try: self.remove_cog(cog) except Exception:", "_BaseCommand from .errors import (ExtensionFailed, ExtensionMissingEntryPoint, ExtensionNotLoaded, ExtensionAlreadyLoaded, ExtensionNotFound, CheckFailure,", "= StringView(message.content) ctx = cls(prefix=None, view=view, bot=self, message=message) prefix =", "insensitive as well. description: :class:`str` The content prefixed into the", "permit persons to whom the Software is furnished to do", "cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog def remove_cog(self, name: str)", "commands for. \"\"\" # noqa if message.author.id == self.user.id: return", "for extension in tuple(self.__extensions): try: self.unload_extension(extension) except Exception: pass for", "do so, subject to the following conditions: The above copyright", "separated like regular Python imports if accessing a sub-module. e.g.", "to use. This can be dynamically set at runtime. To", "any person obtaining a copy of this software and associated", "hook is, however, **always** called regardless of the internal command", "the owner of the bot. Parameters ---------- user_id: :class:`str` The", "from typing import Any, List, Optional, Mapping, Set from fortnitepy.client", "over the processing. The returned context is not guaranteed to", "TypeError: # It's possible that a generator raised this exception.", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT", "call this method. \"\"\" def __init__(self, command_prefix: Any, auth: Auth,", "function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or", "return_when=asyncio.FIRST_COMPLETED, timeout=timeout ) # Set should only contain one value", "valid invocation context, :attr:`.Context.valid` must be checked to make sure", "try: self.add_command(obj) except CommandError: traceback.print_exc() continue super().register_methods() async def close(self,", "_print_error(self, ctx: Context, error: Exception) -> None: print( 'Ignoring exception", "the ``bot``. Parameters ---------- name: :class:`str` The extension name to", "it's called only once, even inside the default help command.", ":exc:`.CommandError`. Example ------- .. code-block:: python3 @bot.check_once def whitelist(ctx): return", "including without limitation the rights to use, copy, modify, merge,", "enough to :class:`.Context`\\'s interface. Returns ------- :class:`.Context` The invocation context.", "then it is not a valid candidate to be invoked", "Example ------- .. code-block:: python3 @bot.check def global_check(ctx): # Allows", "\"\"\" return types.MappingProxyType(self.__extensions) @property def help_command(self) -> Optional[HelpCommand]: return self._help_command", "= view.get_word() ctx.invoked_with = invoker ctx.prefix = invoked_prefix ctx.command =", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "user is the owner. \"\"\" if self.owner_id: return user_id ==", "and handles all the internal event dispatch mechanisms. Parameters -----------", "None: for _, obj in inspect.getmembers(self): if isinstance(obj, _BaseCommand): obj.instance", "low level tools, and is equivalent to a call to", "from .context import Context from .help import HelpCommand, FortniteHelpCommand from", "be called once per :meth:`Command.invoke` call. \"\"\" if call_once: self._check_once.append(func)", "del sys.modules[key] raise ExtensionMissingEntryPoint(key) try: setup(self) except Exception as e:", "Cog) -> None: \"\"\"Adds a \"cog\" to the bot. A", "loaded. ExtensionNotFound The extension could not be imported. ExtensionMissingEntryPoint The", "is to facilitate \"dynamic\" command prefixes. This callable can be", "tools, and is equivalent to a call to :meth:`~.Bot.get_context` followed", "obj.instance = self if obj.parent is None: try: self.add_command(obj) except", "without limitation the rights to use, copy, modify, merge, publish,", "create the context. By default, this is :class:`.Context`. Should a", "not in self.__extensions lib = importlib.util.module_from_spec(spec) sys.modules[key] = lib try:", "that you can do with a :class:`fortnitepy.Client` you can do", "message. This is a more low-level counter-part for :meth:`.process_commands` to", "messages starting with ``!?``. This is especially important when passing", "subclass of :class:`fortnitepy.Client` and as a result anything that you", "is _default: self.help_command = FortniteHelpCommand() else: self.help_command = help_command self.add_event_handler('friend_message',", "types.ModuleType]: \"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension name to", "to do when the extension is loaded. This entry point", "extension name to unload. It must be dot separated like", "will be triggered. By default, this coroutine is called automatically", "not None: if not isinstance(value, HelpCommand): raise TypeError('help_command must be", ":class:`str` The name of the cog you are requesting. This", "The extension can provide an optional global function, ``cog_teardown``, to", "one to match will be the invocation prefix. You can", "and not isinstance(self.owner_ids, collections.abc.Collection)): raise TypeError( 'owner_ids must be a", "*, close_http: bool = True, dispatch_close: bool = True) ->", "Parameters ---------- coro The coroutine to register as the pre-invoke", "TypeError: if not isinstance(prefix, list): raise TypeError('get_prefix must return either", "name if unspecified. \"\"\" return self.__cogs.get(name) @property def cogs(self) ->", "our own error if that's the case. if isinstance(ret, collections.abc.Iterable):", "CommandNotFound) from .core import GroupMixin from .cog import Cog from", "self.remove_cog(cog) except Exception: pass await self._close( close_http=close_http, dispatch_close=dispatch_close ) def", "global check once functions ' 'failed.') except CommandError as exc:", "function processes the commands that have been registered to the", "deal in the Software without restriction, including without limitation the", "collections import traceback from typing import Any, List, Optional, Mapping,", "the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ---------- func", "\"\"\"|coro| This function processes the commands that have been registered", "isinstance(self.owner_ids, collections.abc.Collection)): raise TypeError( 'owner_ids must be a collection not", ":meth:`.check` and :meth:`.check_once`. Parameters ---------- func The function that was", "had an execution error. \"\"\" if name in self.__extensions: raise", "isinstance(obj, _BaseCommand): obj.instance = self if obj.parent is None: try:", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR", "a coroutine. This function takes a single parameter, :class:`.Context`, and", "coro: The coroutine to register as the post-invoke hook. Raises", "self.__cogs.copy().items(): if _is_submodule(name, cog.__module__): self.remove_cog(cogname) # remove all the commands", "invocation context. The type of this can change via the", "the module for cmd in self.all_commands.copy().values(): if cmd.module is not", "= lib def load_extension(self, name: str) -> None: \"\"\"Loads an", "_is_submodule(parent: str, child: str) -> bool: return parent == child", "to make sure it is. If the context is not", "commands and event listeners that the cog has registered will", "post-invoke hook must be a coroutine.') self._after_invoke = coro return", "Optional[HelpCommand]) -> None: if value is not None: if not", "registered commands and event listeners that the cog has registered", "use. This can be dynamically set at runtime. To remove", "AttributeError: del sys.modules[key] raise ExtensionMissingEntryPoint(key) try: setup(self) except Exception as", "``foo.test`` if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded", "invoked_prefix ctx.command = self.all_commands.get(invoker) return ctx def _print_error(self, ctx: Context,", "2015-present Rapptz Permission is hereby granted, free of charge, to", "from e else: self.__extensions[key] = lib def load_extension(self, name: str)", "entry point on what to do when the extension is", "allow users more fine grained control over the processing. The", "``False``. This attribute does not carry over to groups. You", "global checks. call_once: :class:`bool` If the function was added with", "in self.__extensions: raise ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name) if spec is", "def reload_extension(self, name: str) -> None: \"\"\"Atomically reloads an extension.", "regardless of the internal command callback raising an error (i.e.", "Optional[str] = None, **kwargs: Any) -> None: kwargs['case_insensitive'] = kwargs.get('case_insensitive',", "get_prefix(self, message: Message) -> Any: \"\"\"|coro| Retrieves the prefix the", "see :ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`] The user ID that owns the", "directly after the command is called. This makes it a", "types.ModuleType, key: str) -> None: # precondition: key not in", "None: \"\"\"|coro| Invokes the command given under the invocation context", "cog is not found, ``None`` is returned instead. Parameters -----------", "Parameters ---------- name: :class:`str` The name of the cog to", "the hooks are not called. Parameters ---------- coro The coroutine", "or the class name if unspecified. \"\"\" return self.__cogs.get(name) @property", "__repr__(self) -> str: return '<default-help-command>' _default = _DefaultRepr() class Bot(GroupMixin,", "called only once, even inside the default help command. ..", "= self if obj.parent is None: try: self.add_command(obj) except CommandError:", "previous module states from sys modules modules = { name:", "prefix if isinstance(prefix, str): if not view.skip_string(prefix): return ctx else:", "get_prefix must ' 'contain only strings, not ' '{}'.format(value.__class__.__name__)) raise", "\"\"\" if ctx.command is not None: self.dispatch_event('command', ctx) try: if", "exc) else: self.dispatch_event('command_completion', ctx) elif ctx.invoked_with: exc = CommandNotFound('Command \"{}\"", "await func(ctx) else: res = func(ctx) if not res: return", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "when passing an empty string, it should always be last", "keyword argument in class creation or the class name if", "in an atomic way. That is, if an operation fails", "function takes a single parameter, the ``bot``, similar to ``extension_setup``", "ret = prefix(self, message) if not isinstance(ret, str): try: ret", "is called automatically when a new message is received. This", ":meth:`.Bot.add_check` call or using :meth:`.check_once`. \"\"\" list_ = self._check_once if", "last as no prefix after it will be matched. case_insensitive:", "listening to with the message as a context. Parameters ----------", "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT", "Don't # replace it with our own error if that's", ":meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are only called if all checks", "return func def add_check(self, func: MaybeCoro, *, call_once: bool =", "old compiled library. lib.extension_setup(self) self.__extensions[name] = lib # revert sys.modules", "element in prefix: if view.skip_string(element): invoked_prefix = element break else:", "IN THE SOFTWARE. \"\"\" import logging import inspect import asyncio", "coroutine, none of the commands will be triggered. By default,", "module for cogname, cog in self.__cogs.copy().items(): if _is_submodule(name, cog.__module__): self.remove_cog(cogname)", "TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "this exception. Don't # replace it with our own error", "-> None: \"\"\"Removes a cog from the bot. All registered", "import ``foo/test.py``. Raises ------ ExtensionNotFound The extension could not be", "The extension could not be imported. ExtensionMissingEntryPoint The extension does", "self.wait_for_futures(futures, check=check) if isinstance(ret, asyncio.Future): self._print_error(ctx, error) def dispatch_error(self, ctx:", "if you require group commands to be case insensitive as", "str) -> None: # precondition: key not in self.__extensions lib", "name to load. It must be dot separated like regular", "had an execution error. \"\"\" lib = self.__extensions.get(name) if lib", "else: self.dispatch_event('command_completion', ctx) elif ctx.invoked_with: exc = CommandNotFound('Command \"{}\" is", "return types.MappingProxyType(self.__cogs) def _remove_module_references(self, name: str) -> None: # find", "value value._add_to_bot(self) elif self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command =", "------- ExtensionNotLoaded The extension was not loaded. \"\"\" lib =", "allowed. .. note:: When passing multiple prefixes be careful to", "is called directly before the command is called. This makes", "merge, publish, distribute, sublicense, and/or sell copies of the Software,", "an atomic way. That is, if an operation fails mid-reload", "to create the context. By default, this is :class:`.Context`. Should", "so, subject to the following conditions: The above copyright notice", "handles all the internal event dispatch mechanisms. Parameters ----------- ctx:", "sys.modules[key] raise ExtensionFailed(key, e) from e try: setup = getattr(lib,", "charge, to any person obtaining a copy of this software", "that adds a check globally to every command. .. note::", "exceptions inherited from :exc:`.CommandError`. Example ------- .. code-block:: python3 @bot.check", "every command. .. note:: This function can either be a", "not None \"\"\" self.add_check(func) return func def add_check(self, func: MaybeCoro,", "None else: self._help_command = None async def get_prefix(self, message: Message)", "``!?``. This is especially important when passing an empty string,", "regular global checks, this one is called only once per", "unspecified. \"\"\" return self.__cogs.get(name) @property def cogs(self) -> Mapping[str, Cog]:", "self._help_command._remove_from_bot(self) self._help_command = None else: self._help_command = None async def", "extension setup function had an execution error. \"\"\" lib =", "call to :meth:`~.Bot.invoke`. Parameters ----------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message", "Allows only party commands. return ctx.party is not None \"\"\"", "processes the commands that have been registered to the bot", "permission notice shall be included in all copies or substantial", "For performance reasons it is recommended to use a :class:`set`", "The function to remove from the global checks. call_once: :class:`bool`", "lib # revert sys.modules back to normal and raise back", "to do miscellaneous clean-up if necessary. This function takes a", "single prefix that the bot is listening for. \"\"\" #", "be provided, it must be similar enough to :class:`.Context`\\'s interface.", "not guaranteed to be a valid invocation context, :attr:`.Context.valid` must", "except Exception: pass for cog in tuple(self.__cogs): try: self.remove_cog(cog) except", "OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import logging import", "ret = await prefix(self, message) else: ret = prefix(self, message)", "with the same extension, only refreshed. This is equivalent to", "and cogs are removed from the bot and the module", "makes it a useful function to set up database connections", "at ' 'least one prefix') return ret async def get_context(self,", "-> None: if value is not None: if not isinstance(value,", "for event_list in self._events.copy().values(): remove = [] for index, event", "a regular function or a coroutine. This function takes a", "= True) -> None: if dispatch_close: await asyncio.gather( self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'),", "method. \"\"\" def __init__(self, command_prefix: Any, auth: Auth, *, help_command:", "if _is_submodule(name, module): del sys.modules[module] def _load_from_module_spec(self, spec: types.ModuleType, key:", "self.__extensions.get(name) if lib is None: raise ExtensionNotLoaded(name) # get the", "function call # so let's load it from our old", "coroutine. An empty string as the prefix always matches, enabling", "child: str) -> bool: return parent == child or child.startswith(parent", "= command_prefix self.description = inspect.cleandoc(description) if description else '' self.owner_id", "The function that was used as a global check. call_once:", "not None and _is_submodule(name, event.__module__)): remove.append(index) for index in reversed(remove):", "ExtensionNotFound(name) self._load_from_module_spec(spec, name) def unload_extension(self, name: str) -> None: \"\"\"Unloads", "callable ' 'returning either of these, not ' '{}'.format(ret.__class__.__name__)) if", "python3 @bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist \"\"\" self.add_check(func,", "None, cancel: bool = False) -> None: def _cancel_futs(pending_futures: Set[asyncio.Future])", "invoker = view.get_word() ctx.invoked_with = invoker ctx.prefix = invoked_prefix ctx.command", "name: :class:`str` The name of the cog you are requesting.", "= { name: module for name, module in sys.modules.items() if", "try: spec.loader.exec_module(lib) except Exception as e: del sys.modules[key] raise ExtensionFailed(key,", "function. ExtensionFailed The extension or its setup function had an", "owner_id: Optional[:class:`int`] The user ID that owns the bot. This", "@property def extensions(self) -> Mapping[str, types.ModuleType]: \"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only", "'Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr ) traceback.print_exception( type(error), error,", "message to process commands for. \"\"\" # noqa if message.author.id", "if you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The", "the internal event dispatch mechanisms. Parameters ----------- ctx: :class:`.Context` The", "one is called only once per :meth:`Command.invoke` call. Regular global", "called unless checks and argument parsing procedures succeed. This hook", "str): raise TypeError('Iterable command_prefix or list ' 'returned from get_prefix", "only contain one value for future in done: if check", "self.owner_ids = kwargs.get('owner_ids', set()) if self.owner_id and self.owner_ids: raise TypeError('Both", "bool: return parent == child or child.startswith(parent + \".\") class", "this prefix via :attr:`.Context.prefix`. To avoid confusion empty iterables are", "not found' ''.format(ctx.invoked_with)) self.dispatch_error(ctx, exc) async def process_commands(self, message: Message)", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "name) def reload_extension(self, name: str) -> None: \"\"\"Atomically reloads an", "is loaded. This entry point must have a single argument,", "raise ValueError('Iterable command_prefix must contain at ' 'least one prefix')", "def _load_from_module_spec(self, spec: types.ModuleType, key: str) -> None: # precondition:", "raise ExtensionFailed(key, e) from e else: self.__extensions[key] = lib def", "invocation prefix. You can get this prefix via :attr:`.Context.prefix`. To", "that call this method. \"\"\" def __init__(self, command_prefix: Any, auth:", "TypeError('Cogs must derive from Cog.') cog = cog._inject(self) self.__cogs[cog.__cog_name__] =", "asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout ) # Set should only contain", "if description else '' self.owner_id = kwargs.get('owner_id') self.owner_ids = kwargs.get('owner_ids',", "that registers a coroutine as a post-invoke hook. A post-invoke", "func: MaybeCoro, *, call_once: bool = False) -> None: \"\"\"Removes", "None else: return ctx except TypeError: if not isinstance(prefix, list):", "is, however, **always** called regardless of the internal command callback", "Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message context to get the prefix of.", "coroutine passed is not actually a coroutine. \"\"\" if not", "MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that adds a \"call once\"", "except done in an atomic way. That is, if an", "This is equivalent to the name passed via keyword argument", "command prefix could also be an iterable of strings indicating", "self.add_event_handler('party_message', self.process_commands) def register_methods(self) -> None: for _, obj in", "importlib import collections import traceback from typing import Any, List,", "It's possible that a generator raised this exception. Don't #", "obtaining a copy of this software and associated documentation files", "of set up required. This pre-invoke hook takes a sole", "``foo.test`` if you want to import ``foo/test.py``. Raises ------ ExtensionNotFound", "None: \"\"\"Adds a \"cog\" to the bot. A cog is", "be, or a callable that takes in the bot as", "a subclass ' 'of HelpCommand') if self._help_command is not None:", "any message as the previous one matches messages starting with", "----------- command_prefix The command prefix is what the message content", "to the bot. A cog is a class that has", "self._load_from_module_spec(spec, name) def unload_extension(self, name: str) -> None: \"\"\"Unloads an", ":class:`bool` If the function was added with ``call_once=True`` in the", "not None: self._help_command._remove_from_bot(self) self._help_command = None else: self._help_command = None", "except AttributeError: pass else: try: func(self) except Exception: pass finally:", "after_invoke(self, coro: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that registers a", "function to remove from the global checks. call_once: :class:`bool` If", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "a copy of this software and associated documentation files (the", "from the module for cogname, cog in self.__cogs.copy().items(): if _is_submodule(name,", "not isinstance(value, HelpCommand): raise TypeError('help_command must be a subclass '", "you are requesting. This is equivalent to the name passed", "extension. An extension is a python module that contains commands,", "= None else: self._help_command = None async def get_prefix(self, message:", "a subclass of :class:`fortnitepy.Client` and as a result anything that", "as the previous one matches messages starting with ``!?``. This", "a check globally to every command. .. note:: This function", "def check_once(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that adds", "useful function to clean-up database connections or any type of", "setup function had an execution error. \"\"\" if name in", "the ``cls`` parameter. \"\"\" # noqa view = StringView(message.content) ctx", "a useful function to set up database connections or any", "loaded. This entry point must have a single argument, the", "from fortnitepy.typedefs import MaybeCoro, ListOrTuple from ._types import _BaseCommand from", "module for cmd in self.all_commands.copy().values(): if cmd.module is not None", "Auth from fortnitepy.typedefs import MaybeCoro, ListOrTuple from ._types import _BaseCommand", "\"\"\" list_ = self._check_once if call_once else self._checks try: list_.remove(func)", "A post-invoke hook is called directly after the command is", ".context import Context from .help import HelpCommand, FortniteHelpCommand from .typedefs", "a result anything that you can do with a :class:`fortnitepy.Client`", "cmd.recursively_remove_all_commands() self.remove_command(cmd.name) # remove all the listeners from the module", "if (event.__module__ is not None and _is_submodule(name, event.__module__)): remove.append(index) for", "cog in self.__cogs.copy().items(): if _is_submodule(name, cog.__module__): self.remove_cog(cogname) # remove all", "group if you require group commands to be case insensitive", "class be provided, it must be similar enough to :class:`.Context`\\'s", "file=sys.stderr ) async def wait_for_futures(self, futures: ListOrTuple, *, check: Optional[callable]", "function. ExtensionFailed The extension setup function had an execution error.", "the context. By default, this is :class:`.Context`. Should a custom", "exc: await ctx.command.dispatch_error(ctx, exc) else: self.dispatch_event('command_completion', ctx) elif ctx.invoked_with: exc", "Optional[:class:`int`] The user ID that owns the bot. This is", "self.owner_ids def before_invoke(self, coro: MaybeCoro) -> MaybeCoro: \"\"\"A decorator that", "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "can be either a regular function or a coroutine. An", "self.process_commands) def register_methods(self) -> None: for _, obj in inspect.getmembers(self):", "the :meth:`.Bot.add_check` call or using :meth:`.check_once`. \"\"\" list_ = self._check_once", "of clean up required. This post-invoke hook takes a sole", "call. \"\"\" if call_once: self._check_once.append(func) else: self._checks.append(func) def remove_check(self, func:", "list): raise TypeError('get_prefix must return either a string ' 'or", "takes a single parameter, the ``bot``, similar to ``extension_setup`` from", "as the post-invoke hook. Raises ------ TypeError The coroutine passed", "self._before_invoke = None self._after_invoke = None if help_command is _default:", "content prefixed into the default help message. help_command: Optional[:class:`.HelpCommand`] The", "class Bot(GroupMixin, Client): \"\"\"Represents a fortnite bot. This class is", "must have a single argument, the ``bot``. Parameters ---------- name:", "'contain only strings, not ' '{}'.format(value.__class__.__name__)) raise invoker = view.get_word()", "License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted,", "and checks that call this method. owner_ids: Optional[Collection[:class:`int`]] The user", "is not called unless checks and argument parsing procedures succeed.", "def _print_error(self, ctx: Context, error: Exception) -> None: print( 'Ignoring", "if unspecified. \"\"\" return self.__cogs.get(name) @property def cogs(self) -> Mapping[str,", "return coro def add_cog(self, cog: Cog) -> None: \"\"\"Adds a", "case_insensitive: :class:`bool` Whether the commands should be case insensitive. Defaults", "bot. This is used by :meth:`.is_owner()` and checks that call", "prefixes or a single prefix that the bot is listening", "ctx: Context, *, call_once: bool = False) -> bool: data", "If the context is not valid then it is not", "if name in self.__extensions: raise ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name) if", "A list of prefixes or a single prefix that the", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,", "called. This makes it a useful function to set up", "async def can_run(self, ctx: Context, *, call_once: bool = False)", "can only raise exceptions inherited from :exc:`.CommandError`. Example ------- ..", "the entry point on what to do when the extension", ") def check(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that", "be last as no prefix after it will be matched.", "= prefix if isinstance(prefix, str): if not view.skip_string(prefix): return ctx", "you can do with this bot. This class also subclasses", "require group commands to be case insensitive as well. description:", "That is, if an operation fails mid-reload then the bot", "help command, see :ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`] The user ID that", "is furnished to do so, subject to the following conditions:", "self.remove_command(cmd.name) # remove all the listeners from the module for", "will roll-back to the prior working state. Parameters ------------ name:", "party commands. return ctx.party is not None \"\"\" self.add_check(func) return", "lib = importlib.util.module_from_spec(spec) sys.modules[key] = lib try: spec.loader.exec_module(lib) except Exception", "contain at ' 'least one prefix') return ret async def", "= None else: return ctx except TypeError: if not isinstance(prefix,", "def close(self, *, close_http: bool = True, dispatch_close: bool =", "The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is", "users more fine grained control over the processing. The returned", "extension. This replaces the extension with the same extension, only", "exception. Don't # replace it with our own error if", "this coroutine, none of the commands will be triggered. By", "= kwargs.get('case_insensitive', False) super().__init__(auth, **kwargs) self.command_prefix = command_prefix self.description =", "ExtensionAlreadyLoaded, ExtensionNotFound, CheckFailure, CommandError, CommandNotFound) from .core import GroupMixin from", "into the default help message. help_command: Optional[:class:`.HelpCommand`] The help command", "done, pending = await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout ) #", "called or :meth:`.Command.can_run` is called. This type of check bypasses", "low-level counter-part for :meth:`.process_commands` to allow users more fine grained", "None: self._help_command._remove_from_bot(self) self._help_command = None else: self._help_command = None async", "self.owner_id = kwargs.get('owner_id') self.owner_ids = kwargs.get('owner_ids', set()) if self.owner_id and", "command prefix is what the message content must contain initially", "by :meth:`.is_owner()` and checks that call this method. owner_ids: Optional[Collection[:class:`int`]]", "ctx = cls(prefix=None, view=view, bot=self, message=message) prefix = await self.get_prefix(message)", "in done: if check is None or check(future): if cancel:", "= True, dispatch_close: bool = True) -> None: if dispatch_close:", "like regular Python imports if accessing a sub-module. e.g. ``foo.test``", "is called. This makes it a useful function to set", "import Cog from .view import StringView from .context import Context", "get this prefix via :attr:`.Context.prefix`. To avoid confusion empty iterables", "a single parameter, :class:`.Context`, and can only raise exceptions inherited", "This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters", "from our old compiled library. lib.extension_setup(self) self.__extensions[name] = lib #", "self._events.copy().values(): remove = [] for index, event in enumerate(event_list): if", "Parameters ---------- coro: The coroutine to register as the post-invoke", "-> MaybeCoro: r\"\"\"A decorator that adds a check globally to", "to invoke. \"\"\" if ctx.command is not None: self.dispatch_event('command', ctx)", "asyncio.iscoroutinefunction(func): res = await func(ctx) else: res = func(ctx) if", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT", "fortnitepy.client import Client from fortnitepy.auth import Auth from fortnitepy.typedefs import", "context. The type of this can change via the ``cls``", "what the message content must contain initially to have a", "done: if check is None or check(future): if cancel: _cancel_futs(pending)", "The cog does not inherit from :class:`.Cog`. CommandError An error", "str): if not view.skip_string(prefix): return ctx else: try: if message.content.startswith(tuple(prefix)):", "list(ret) except TypeError: # It's possible that a generator raised", "one value for future in done: if check is None", "error: Exception) -> None: def check(future): return future.result() is False", "is not found, ``None`` is returned instead. Parameters ----------- name:", "Parameters ---------- user_id: :class:`str` The user id to check for.", "MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that registers a coroutine as", "prefix the bot is listening to with the message as", "the remnants should have been # cleaned from the load_extension", "either of these, not ' '{}'.format(ret.__class__.__name__)) if not ret: raise", "library. lib.extension_setup(self) self.__extensions[name] = lib # revert sys.modules back to", "from .errors import (ExtensionFailed, ExtensionMissingEntryPoint, ExtensionNotLoaded, ExtensionAlreadyLoaded, ExtensionNotFound, CheckFailure, CommandError,", "for clean-up scenarios. Parameters ---------- coro: The coroutine to register", "hook. Raises ------ TypeError The coroutine passed is not actually", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "check(future): if cancel: _cancel_futs(pending) return future async def _wait_for_error_return(self, futures:", "state. Parameters ------------ name: :class:`str` The extension name to reload.", "to extension. \"\"\" return types.MappingProxyType(self.__extensions) @property def help_command(self) -> Optional[HelpCommand]:", "if not isinstance(cog, Cog): raise TypeError('Cogs must derive from Cog.')", "' 'or a list of string, not ' '{}'.format(prefix.__class__.__name__)) for", "parent == child or child.startswith(parent + \".\") class _DefaultRepr: def", "load. It must be dot separated like regular Python imports", "or callable ' 'returning either of these, not ' '{}'.format(ret.__class__.__name__))", "= cls(prefix=None, view=view, bot=self, message=message) prefix = await self.get_prefix(message) invoked_prefix", "default, this coroutine is called automatically when a new message", "The message context to get the prefix of. Returns --------", "typing import Any, List, Optional, Mapping, Set from fortnitepy.client import", "global check to the bot. Unlike regular global checks, this", "if the load failed, the remnants should have been #", "def check(future): return future.result() is False ret = await self.wait_for_futures(futures,", "-> MaybeCoro: \"\"\"A decorator that registers a coroutine as a", "Context, error: Exception) -> None: def check(future): return future.result() is", "obj.parent is None: try: self.add_command(obj) except CommandError: traceback.print_exc() continue super().register_methods()", "def process_commands(self, message: Message) -> None: \"\"\"|coro| This function processes", ":meth:`~.Bot.invoke`. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to get", "will be used to create the context. By default, this", "entry point must have a single argument, the ``bot``. Parameters", "not allowed. .. note:: When passing multiple prefixes be careful", "group commands to be case insensitive as well. description: :class:`str`", "If the function should only be called once per :meth:`Command.invoke`", "_is_submodule(name, cog.__module__): self.remove_cog(cogname) # remove all the commands from the", "module for event_list in self._events.copy().values(): remove = [] for index,", "not isinstance(value, str): raise TypeError('Iterable command_prefix or list ' 'returned", "ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded The extension", ":meth:`.is_owner()` and checks that call this method. owner_ids: Optional[Collection[:class:`int`]] The", "async def get_prefix(self, message: Message) -> Any: \"\"\"|coro| Retrieves the", "== child or child.startswith(parent + \".\") class _DefaultRepr: def __repr__(self)", "must be dot separated like regular Python imports if accessing", "returned context is not guaranteed to be a valid invocation", "\"\"\" return self.__cogs.get(name) @property def cogs(self) -> Mapping[str, Cog]: \"\"\"Mapping[:class:`str`,", "await self.get_prefix(message) invoked_prefix = prefix if isinstance(prefix, str): if not", "try: ret = list(ret) except TypeError: # It's possible that", "once, even inside the default help command. .. note:: This", "raise TypeError( 'owner_ids must be a collection not ' '{0.__class__!r}'.format(self.owner_ids)", "error) asyncio.ensure_future(self._wait_for_error_return( futures, ctx, error )) else: self._print_error(ctx, error) async", "fail then the hooks are not called. Parameters ---------- coro", "child.startswith(parent + \".\") class _DefaultRepr: def __repr__(self) -> str: return", "This entry point must have a single argument, the ``bot``.", "\"\"\" cog = self.__cogs.pop(name, None) if cog is None: return", "is listening to with the message as a context. Parameters", "the prefix always matches, enabling prefix-less command invocation. The command", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "these, not ' '{}'.format(ret.__class__.__name__)) if not ret: raise ValueError('Iterable command_prefix", "description else '' self.owner_id = kwargs.get('owner_id') self.owner_ids = kwargs.get('owner_ids', set())", "def get_prefix(self, message: Message) -> Any: \"\"\"|coro| Retrieves the prefix", "class is a subclass of :class:`fortnitepy.Client` and as a result", "the sequence. For example, if the command prefix is ``('!',", "self.owner_id: return user_id == self.owner_id else: return user_id in self.owner_ids", "None self._before_invoke = None self._after_invoke = None if help_command is", "must set it to every group if you require group", "then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception:", "not valid then it is not a valid candidate to", "functionality to manage commands. Attributes ----------- command_prefix The command prefix", "hook. A pre-invoke hook is called directly before the command", "func: MaybeCoro, *, call_once: bool = False) -> None: \"\"\"Adds", "checks, this one is called only once per :meth:`Command.invoke` call.", "help_command and help_command.cog is cog: help_command.cog = None cog._eject(self) def", "Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message context to get", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "pass a prefix that matches a longer prefix occurring later", "\"\"\" if not isinstance(cog, Cog): raise TypeError('Cogs must derive from", "None) sys.modules.pop(key, None) name = lib.__name__ for module in list(sys.modules.keys()):", "timeout=timeout ) # Set should only contain one value for", "class _DefaultRepr: def __repr__(self) -> str: return '<default-help-command>' _default =", "or a single prefix that the bot is listening for.", "cannot set both `owner_id` and `owner_ids`. This is used by", "case. if isinstance(ret, collections.abc.Iterable): raise raise TypeError('command_prefix must be plain", "both `owner_id` and `owner_ids`. This is used by :meth:`.is_owner()` and", "called directly before the command is called. This makes it", "``None`` is returned instead. Parameters ----------- name: :class:`str` The name", "under the invocation context and handles all the internal event", "to the bot. Unlike regular global checks, this one is", "is found then this method has no effect. Parameters ----------", "message. help_command: Optional[:class:`.HelpCommand`] The help command implementation to use. This", "else: try: if message.content.startswith(tuple(prefix)): for element in prefix: if view.skip_string(element):", "if you want to import ``foo/test.py``. Raises ------ ExtensionNotFound The", "import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded.", "can be dynamically set at runtime. To remove the help", "bot. Raises ------ TypeError The cog does not inherit from", "'iterable of strings, or callable ' 'returning either of these,", "ctx else: try: if message.content.startswith(tuple(prefix)): for element in prefix: if", "await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout ) # Set should only", "to ``False``. This attribute does not carry over to groups.", "the commands that have been registered to the bot and", "Message) -> Any: \"\"\"|coro| Retrieves the prefix the bot is", "not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a coroutine.')", "of check bypasses that and ensures that it's called only", "= False) -> None: \"\"\"Removes a global check from the", "set up database connections or any type of set up", "self.dispatch_event('command_completion', ctx) elif ctx.invoked_with: exc = CommandNotFound('Command \"{}\" is not", "be an iterable of strings indicating that multiple checks for", "post-invoke hook is called directly after the command is called.", ".. note:: Similar to :meth:`~.Bot.before_invoke`\\, this is not called unless", "global check to the bot. This is the non-decorator interface", ":class:`set` for the collection. You cannot set both `owner_id` and", "in the :meth:`.Bot.add_check` call or using :meth:`.check_once`. \"\"\" list_ =", "what to do when the extension is loaded. This entry", "of this can change via the ``cls`` parameter. \"\"\" #", "to check for. Returns ------- :class:`bool` Whether the user is", "to be invoked under :meth:`~.Bot.invoke`. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`]", "sys modules modules = { name: module for name, module", "# Allows only party commands. return ctx.party is not None", "raise TypeError('help_command must be a subclass ' 'of HelpCommand') if", "name) self.load_extension(name) except Exception: # if the load failed, the", "second parameter and returns the prefix. This is to facilitate", "e: del sys.modules[key] raise ExtensionFailed(key, e) from e try: setup", "---------- cog: :class:`.Cog` The cog to register to the bot.", "insensitive. Defaults to ``False``. This attribute does not carry over", "module for name, module in sys.modules.items() if _is_submodule(lib.__name__, name) }", "the command prefix is ``('!', '!?')`` the ``'!?'`` prefix will", "the processing. The returned context is not guaranteed to be", "ctx, error )) else: self._print_error(ctx, error) async def invoke(self, ctx:", "None: \"\"\"Loads an extension. An extension is a python module", "= self.__extensions.get(name) if lib is None: raise ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib,", "collection. You cannot set both `owner_id` and `owner_ids`. This is", "invoked_prefix = prefix if isinstance(prefix, str): if not view.skip_string(prefix): return", "that multiple checks for the prefix should be used and", "in self.__extensions lib = importlib.util.module_from_spec(spec) sys.modules[key] = lib try: spec.loader.exec_module(lib)", "------------ name: :class:`str` The extension name to reload. It must", "this bot. This class also subclasses :class:`.GroupMixin` to provide the", "\"\"\" import logging import inspect import asyncio import types import", "fortnite bot. This class is a subclass of :class:`fortnitepy.Client` and", "bot will roll-back to the prior working state. Parameters ------------", "``'!?'`` prefix will never be matched to any message as", "if self.owner_id: return user_id == self.owner_id else: return user_id in", "argument parsing procedures fail then the hooks are not called.", "import _BaseCommand from .errors import (ExtensionFailed, ExtensionMissingEntryPoint, ExtensionNotLoaded, ExtensionAlreadyLoaded, ExtensionNotFound,", "parameter, :class:`.Context`, and can only raise exceptions inherited from :exc:`.CommandError`.", "self._help_command = None self._before_invoke = None self._after_invoke = None if", "finally: self.__extensions.pop(key, None) sys.modules.pop(key, None) name = lib.__name__ for module", "-> None: \"\"\"Loads an extension. An extension is a python", "operation fails mid-reload then the bot will roll-back to the", "note:: When passing multiple prefixes be careful to not pass", "used and the first one to match will be the", "be dynamically set at runtime. To remove the help command", "raise exceptions inherited from :exc:`.CommandError`. Example ------- .. code-block:: python3", "up required. This pre-invoke hook takes a sole parameter, a", "context. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message context to", "self._close( close_http=close_http, dispatch_close=dispatch_close ) def check(self, func: MaybeCoro) -> MaybeCoro:", "not inherit from :class:`.Cog`. CommandError An error happened during loading.", "-> Any: \"\"\"|coro| Retrieves the prefix the bot is listening", "with ``!?``. This is especially important when passing an empty", "asyncio import types import sys import importlib import collections import", "useful function to set up database connections or any type", "---------- func The function that was used as a global", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import", "commands should be case insensitive. Defaults to ``False``. This attribute", "self.__cogs.pop(name, None) if cog is None: return help_command = self.help_command", "help_command(self) -> Optional[HelpCommand]: return self._help_command @help_command.setter def help_command(self, value: Optional[HelpCommand])", "sys.modules back to normal and raise back to caller sys.modules.update(modules)", "the context is not valid then it is not a", "in pending_futures: if not p.cancelled(): p.cancel() pending = futures while", "remnants should have been # cleaned from the load_extension function", "bool = True) -> None: if dispatch_close: await asyncio.gather( self.dispatch_and_wait_event('before_close'),", "r\"\"\"|coro| Returns the invocation context from the message. This is", "extension can provide an optional global function, ``cog_teardown``, to do", "to cog. \"\"\" return types.MappingProxyType(self.__cogs) def _remove_module_references(self, name: str) ->", "return ctx else: try: if message.content.startswith(tuple(prefix)): for element in prefix:", "not ' '{}'.format(prefix.__class__.__name__)) for value in prefix: if not isinstance(value,", "is received. This is built using other low level tools,", "event listeners that the cog has registered will be removed", ":meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`. Parameters ----------- message:", "a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``.", "remove.append(index) for index in reversed(remove): del event_list[index] def _call_module_finalizers(self, lib:", "commands, cogs, or listeners. An extension must have a global", ") self.__cogs = {} self.__extensions = {} self._checks = []", "command is called. This makes it a useful function to", "error) async def invoke(self, ctx: Context) -> None: \"\"\"|coro| Invokes", "self.help_command if help_command and help_command.cog is cog: help_command.cog = None", "its setup function had an execution error. \"\"\" if name", "check: Optional[callable] = None, timeout: Optional[int] = None, cancel: bool", "element break else: invoked_prefix = None else: return ctx except", "own error if that's the case. if isinstance(ret, collections.abc.Iterable): raise", "are removed from the bot and the module is un-imported.", "spec is None: raise ExtensionNotFound(name) self._load_from_module_spec(spec, name) def unload_extension(self, name:", "if await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) else: raise CheckFailure('The global", "GroupMixin from .cog import Cog from .view import StringView from", "a single prefix that the bot is listening for. \"\"\"", "portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",", ":meth:`.check_once`. \"\"\" list_ = self._check_once if call_once else self._checks try:", "raise TypeError('Iterable command_prefix or list ' 'returned from get_prefix must", "prefix. You can get this prefix via :attr:`.Context.prefix`. To avoid", "self._after_invoke = coro return coro def add_cog(self, cog: Cog) ->", "found, ``None`` is returned instead. Parameters ----------- name: :class:`str` The", "._types import _BaseCommand from .errors import (ExtensionFailed, ExtensionMissingEntryPoint, ExtensionNotLoaded, ExtensionAlreadyLoaded,", "facilitate \"dynamic\" command prefixes. This callable can be either a", "The name of the cog you are requesting. This is", "should be case insensitive. Defaults to ``False``. This attribute does", "from the module for event_list in self._events.copy().values(): remove = []", "similar enough to :class:`.Context`\\'s interface. Returns ------- :class:`.Context` The invocation", "on what to do when the extension is loaded. This", "owner of the bot. Parameters ---------- user_id: :class:`str` The user", "Exception) -> None: print( 'Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr", "our old compiled library. lib.extension_setup(self) self.__extensions[name] = lib # revert", "self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message', self.process_commands) def register_methods(self) -> None: for _,", "# It's possible that a generator raised this exception. Don't", "modify, merge, publish, distribute, sublicense, and/or sell copies of the", "The help command implementation to use. This can be dynamically", "Parameters ---------- func The function that was used as a", "parameter, a :class:`.Context`. .. note:: Similar to :meth:`~.Bot.before_invoke`\\, this is", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "as well. description: :class:`str` The content prefixed into the default", "mapping of cog name to cog. \"\"\" return types.MappingProxyType(self.__cogs) def", "isinstance(prefix, list): raise TypeError('get_prefix must return either a string '", "used as a global check. call_once: :class:`bool` If the function", "``bot``. Parameters ---------- name: :class:`str` The extension name to load.", "reasons it is recommended to use a :class:`set` for the", "note:: The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are only called if", "to import ``foo/test.py``. Raises ------ ExtensionNotFound The extension could not", "as exc: await ctx.command.dispatch_error(ctx, exc) else: self.dispatch_event('command_completion', ctx) elif ctx.invoked_with:", ":meth:`.check_once`. Parameters ---------- func The function that was used as", "decorator that registers a coroutine as a post-invoke hook. A", "---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to get the invocation", "in command {}:'.format(ctx.command), file=sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__, file=sys.stderr", "Context from .help import HelpCommand, FortniteHelpCommand from .typedefs import Message", "working state. Parameters ------------ name: :class:`str` The extension name to", "are called whenever a command is called or :meth:`.Command.can_run` is", "any check or argument parsing procedures fail then the hooks", "self.__cogs.get(name) @property def cogs(self) -> Mapping[str, Cog]: \"\"\"Mapping[:class:`str`, :class:`Cog`]: A", "pass await self._close( close_http=close_http, dispatch_close=dispatch_close ) def check(self, func: MaybeCoro)", "\"\"\"Adds a \"cog\" to the bot. A cog is a", "not ret: raise ValueError('Iterable command_prefix must contain at ' 'least", "register as the pre-invoke hook. Raises ------ TypeError The coroutine", "[] self._help_command = None self._before_invoke = None self._after_invoke = None", "more low-level counter-part for :meth:`.process_commands` to allow users more fine", "up required. This post-invoke hook takes a sole parameter, a", "e try: setup = getattr(lib, 'extension_setup') except AttributeError: del sys.modules[key]", "string, ' 'iterable of strings, or callable ' 'returning either", "If the function was added with ``call_once=True`` in the :meth:`.Bot.add_check`", "sell copies of the Software, and to permit persons to", "load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception: #", "cog: Cog) -> None: \"\"\"Adds a \"cog\" to the bot.", "and _is_submodule(name, cmd.module): if isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name) # remove", "caller sys.modules.update(modules) raise @property def extensions(self) -> Mapping[str, types.ModuleType]: \"\"\"Mapping[:class:`str`,", "equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except done", "if all checks and argument parsing procedures pass without error.", "any type of set up required. This pre-invoke hook takes", ":class:`fortnitepy.Client` and as a result anything that you can do", "empty iterables are not allowed. .. note:: When passing multiple", "and checks that call this method. \"\"\" def __init__(self, command_prefix:", "CommandError: traceback.print_exc() continue super().register_methods() async def close(self, *, close_http: bool", "a more low-level counter-part for :meth:`.process_commands` to allow users more", "types.MappingProxyType(self.__cogs) def _remove_module_references(self, name: str) -> None: # find all", "MaybeCoro) -> MaybeCoro: \"\"\"A decorator that registers a coroutine as", "as its second parameter and returns the prefix. This is", "per :meth:`Command.invoke` call. Regular global checks are called whenever a", "copy, modify, merge, publish, distribute, sublicense, and/or sell copies of", "check_once(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that adds a", "is unloaded, all commands, listeners, and cogs are removed from", "cleaned from the load_extension function call # so let's load", "self._help_command._remove_from_bot(self) self._help_command = value value._add_to_bot(self) elif self._help_command is not None:", "invoked. This prefix could either be a string to indicate", "hooks are only called if all checks and argument parsing", "happened during loading. \"\"\" if not isinstance(cog, Cog): raise TypeError('Cogs", "_DefaultRepr: def __repr__(self) -> str: return '<default-help-command>' _default = _DefaultRepr()", "= self.all_commands.get(invoker) return ctx def _print_error(self, ctx: Context, error: Exception)", "or substantial portions of the Software. THE SOFTWARE IS PROVIDED", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "setup = getattr(lib, 'extension_setup') except AttributeError: del sys.modules[key] raise ExtensionMissingEntryPoint(key)", "\"\"\"Represents a fortnite bot. This class is a subclass of", "do with this bot. This class also subclasses :class:`.GroupMixin` to", "adds a \"call once\" global check to the bot. Unlike", "= inspect.cleandoc(description) if description else '' self.owner_id = kwargs.get('owner_id') self.owner_ids", "-> None: if dispatch_close: await asyncio.gather( self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'), ) for", "# find all references to the module # remove the", "[] for index, event in enumerate(event_list): if (event.__module__ is not", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "publish, distribute, sublicense, and/or sell copies of the Software, and", "return user_id == self.owner_id else: return user_id in self.owner_ids def", "from ._types import _BaseCommand from .errors import (ExtensionFailed, ExtensionMissingEntryPoint, ExtensionNotLoaded,", "= func(ctx) if not res: return False return True async", "extension. \"\"\" return types.MappingProxyType(self.__extensions) @property def help_command(self) -> Optional[HelpCommand]: return", "if cmd.module is not None and _is_submodule(name, cmd.module): if isinstance(cmd,", "TypeError The cog does not inherit from :class:`.Cog`. CommandError An", "are not called. Parameters ---------- coro The coroutine to register", "str) -> None: # find all references to the module", "is not None: self._help_command._remove_from_bot(self) self._help_command = value value._add_to_bot(self) elif self._help_command", "bot. This is the non-decorator interface to :meth:`.check` and :meth:`.check_once`.", "a post-invoke hook. A post-invoke hook is called directly after", "does not have a extension_setup function. ExtensionFailed The extension setup", "to facilitate \"dynamic\" command prefixes. This callable can be either", "valid then it is not a valid candidate to be", "bot. Parameters ---------- user_id: :class:`str` The user id to check", "child or child.startswith(parent + \".\") class _DefaultRepr: def __repr__(self) ->", "context. By default, this is :class:`.Context`. Should a custom class", "are not allowed. .. note:: When passing multiple prefixes be", "that matches a longer prefix occurring later in the sequence.", "_default, description: Optional[str] = None, **kwargs: Any) -> None: kwargs['case_insensitive']", "to every group if you require group commands to be", "pre-invoke hook. A pre-invoke hook is called directly before the", "call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`. Parameters", "must be checked to make sure it is. If the", "be included in all copies or substantial portions of the", "invocation context and handles all the internal event dispatch mechanisms.", "False) -> bool: data = self._check_once if call_once else self._checks", "decorator that registers a coroutine as a pre-invoke hook. A", "if necessary. This function takes a single parameter, the ``bot``,", "async def get_context(self, message: Message, *, cls: Context = Context)", "name: module for name, module in sys.modules.items() if _is_submodule(lib.__name__, name)", "coro The coroutine to register as the pre-invoke hook. Raises", "coro: MaybeCoro) -> MaybeCoro: \"\"\"A decorator that registers a coroutine", "not None: self._help_command._remove_from_bot(self) self._help_command = value value._add_to_bot(self) elif self._help_command is", "from :exc:`.CommandError`. Example ------- .. code-block:: python3 @bot.check def global_check(ctx):", "A pre-invoke hook is called directly before the command is", "TypeError( 'owner_ids must be a collection not ' '{0.__class__!r}'.format(self.owner_ids) )", "Any, List, Optional, Mapping, Set from fortnitepy.client import Client from", "raise TypeError('Both owner_id and owner_ids are set.') if (self.owner_ids and", "self.add_command(obj) except CommandError: traceback.print_exc() continue super().register_methods() async def close(self, *,", "By default, this is :class:`.Context`. Should a custom class be", "subclass ' 'of HelpCommand') if self._help_command is not None: self._help_command._remove_from_bot(self)", "``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound", "import Message log = logging.getLogger(__name__) def _is_submodule(parent: str, child: str)", "Cog.') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog def remove_cog(self, name:", "self.load_extension(name) except Exception: # if the load failed, the remnants", "found' ''.format(ctx.invoked_with)) self.dispatch_error(ctx, exc) async def process_commands(self, message: Message) ->", "called if all checks and argument parsing procedures pass without", "self.__extensions.get(name) if lib is None: raise ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name)", "error) def dispatch_error(self, ctx: Context, error: Exception) -> None: if", "message to get the invocation context from. cls The factory", "event.__module__)): remove.append(index) for index in reversed(remove): del event_list[index] def _call_module_finalizers(self,", "sys.modules[key] = lib try: spec.loader.exec_module(lib) except Exception as e: del", "Python imports if accessing a sub-module. e.g. ``foo.test`` if you", "occurring later in the sequence. For example, if the command", "type of check bypasses that and ensures that it's called", "un-imported. The extension can provide an optional global function, ``cog_teardown``,", "is. If the context is not valid then it is", "= await self.get_prefix(message) invoked_prefix = prefix if isinstance(prefix, str): if", "ctx) try: if await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) else: raise", "It must be dot separated like regular Python imports if", "from the message. This is a more low-level counter-part for", "bool = False) -> None: def _cancel_futs(pending_futures: Set[asyncio.Future]) -> None:", "raise invoker = view.get_word() ctx.invoked_with = invoker ctx.prefix = invoked_prefix", "This callable can be either a regular function or a", "import HelpCommand, FortniteHelpCommand from .typedefs import Message log = logging.getLogger(__name__)", "be a regular function or a coroutine. This function takes", "module states from sys modules modules = { name: module", "checks for the prefix should be used and the first", "of cog name to cog. \"\"\" return types.MappingProxyType(self.__cogs) def _remove_module_references(self,", ":class:`.Context` The invocation context. The type of this can change", ":class:`fortnitepy.PartyMessage` as its second parameter and returns the prefix. This", "user_id in self.owner_ids def before_invoke(self, coro: MaybeCoro) -> MaybeCoro: \"\"\"A", "and as a result anything that you can do with", "none of the commands will be triggered. By default, this", "an optional global function, ``cog_teardown``, to do miscellaneous clean-up if", "by :meth:`.is_owner()` and checks that call this method. \"\"\" def", "extension. When the extension is unloaded, all commands, listeners, and", "# remove all the listeners from the module for event_list", "ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension could", "is None: return help_command = self.help_command if help_command and help_command.cog", "func in data: if asyncio.iscoroutinefunction(func): res = await func(ctx) else:", "the user is the owner. \"\"\" if self.owner_id: return user_id", "_is_submodule(name, event.__module__)): remove.append(index) for index in reversed(remove): del event_list[index] def", "used by :meth:`.is_owner()` and checks that call this method. \"\"\"", "for value in prefix: if not isinstance(value, str): raise TypeError('Iterable", "the bot. Raises ------ TypeError The cog does not inherit", "**always** called regardless of the internal command callback raising an", "via keyword argument in class creation or the class name", "This function processes the commands that have been registered to", "------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The extension", "context and handles all the internal event dispatch mechanisms. Parameters", "def load_extension(self, name: str) -> None: \"\"\"Loads an extension. An", "The extension or its setup function had an execution error.", "from the global checks. call_once: :class:`bool` If the function was", "function to set up database connections or any type of", "is used by :meth:`.is_owner()` and checks that call this method.", "conditions: The above copyright notice and this permission notice shall", "the Software without restriction, including without limitation the rights to", "prefix. This is to facilitate \"dynamic\" command prefixes. This callable", "custom class be provided, it must be similar enough to", "THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "level tools, and is equivalent to a call to :meth:`~.Bot.get_context`", "a new message is received. This is built using other", "it to every group if you require group commands to", "invocation context to invoke. \"\"\" if ctx.command is not None:", "as a context. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message", "= None, cancel: bool = False) -> None: def _cancel_futs(pending_futures:", "event_list[index] def _call_module_finalizers(self, lib: object, key: str) -> None: try:", "multiple prefixes be careful to not pass a prefix that", "For more information on implementing a help command, see :ref:`ext_commands_help_command`.", "as well. If no cog is found then this method", "subclasses :class:`.GroupMixin` to provide the functionality to manage commands. Attributes", "name: :class:`str` The extension name to reload. It must be", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "from sys modules modules = { name: module for name,", "indicate what the prefix should be, or a callable that", "module # remove the cogs registered from the module for", "after the command is called. This makes it a useful", "The type of this can change via the ``cls`` parameter.", "processing. The returned context is not guaranteed to be a", "imported. ExtensionMissingEntryPoint The extension does not have a extension_setup function.", "-> None: \"\"\"Adds a global check to the bot. This", "\"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be", "decorator that adds a check globally to every command. ..", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "for the prefix should be used and the first one", "check from the bot. Parameters ---------- func The function to", "An extension must have a global function, ``extension_setup`` defined as", "index in reversed(remove): del event_list[index] def _call_module_finalizers(self, lib: object, key:", "should only contain one value for future in done: if", "close_http: bool = True, dispatch_close: bool = True) -> None:", "to every command. .. note:: This function can either be", "def _remove_module_references(self, name: str) -> None: # find all references", "for future in done: if check is None or check(future):", ":class:`.Cog`. CommandError An error happened during loading. \"\"\" if not", "check for. Returns ------- :class:`bool` Whether the user is the", "try: if message.content.startswith(tuple(prefix)): for element in prefix: if view.skip_string(element): invoked_prefix", "None if help_command is _default: self.help_command = FortniteHelpCommand() else: self.help_command", "_BaseCommand): obj.instance = self if obj.parent is None: try: self.add_command(obj)", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "-> None: try: func = getattr(lib, 'cog_teardown') except AttributeError: pass", "This attribute does not carry over to groups. You must", "argument, the ``bot``. Parameters ---------- name: :class:`str` The extension name", "mechanisms. Parameters ----------- ctx: :class:`.Context` The invocation context to invoke.", "for _, obj in inspect.getmembers(self): if isinstance(obj, _BaseCommand): obj.instance =", "from .view import StringView from .context import Context from .help", "dispatch mechanisms. Parameters ----------- ctx: :class:`.Context` The invocation context to", "This is similar to `owner_id`. For performance reasons it is", "the commands should be case insensitive. Defaults to ``False``. This", "function takes a single parameter, :class:`.Context`, and can only raise", "invoked_prefix = element break else: invoked_prefix = None else: return", "hook. A post-invoke hook is called directly after the command", "parameter and :class:`fortnitepy.FriendMessage` or :class:`fortnitepy.PartyMessage` as its second parameter and", "is not None \"\"\" self.add_check(func) return func def add_check(self, func:", "user IDs that owns the bot. This is similar to", "not have a extension_setup function. ExtensionFailed The extension setup function", "-> None: \"\"\"Atomically reloads an extension. This replaces the extension", "even inside the default help command. .. note:: This function", "strings, or callable ' 'returning either of these, not '", "TypeError('help_command must be a subclass ' 'of HelpCommand') if self._help_command", "bool = False) -> bool: data = self._check_once if call_once", "to permit persons to whom the Software is furnished to", "no cog is found then this method has no effect.", "regular function or a coroutine. An empty string as the", "except Exception as e: del sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key) raise", "once per :meth:`Command.invoke` call. \"\"\" if call_once: self._check_once.append(func) else: self._checks.append(func)", ") traceback.print_exception( type(error), error, error.__traceback__, file=sys.stderr ) async def wait_for_futures(self,", "extension does not have a extension_setup function. ExtensionFailed The extension", "= list(ret) except TypeError: # It's possible that a generator", "= False) -> None: \"\"\"Adds a global check to the", "importlib.util.find_spec(name) if spec is None: raise ExtensionNotFound(name) self._load_from_module_spec(spec, name) def", "pass for cog in tuple(self.__cogs): try: self.remove_cog(cog) except Exception: pass", "Optional[:class:`.HelpCommand`] The help command implementation to use. This can be", "can_run(self, ctx: Context, *, call_once: bool = False) -> bool:", "True for func in data: if asyncio.iscoroutinefunction(func): res = await", "coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must", "in enumerate(event_list): if (event.__module__ is not None and _is_submodule(name, event.__module__)):", "= importlib.util.module_from_spec(spec) sys.modules[key] = lib try: spec.loader.exec_module(lib) except Exception as", "def remove_cog(self, name: str) -> None: \"\"\"Removes a cog from", "message=message) prefix = await self.get_prefix(message) invoked_prefix = prefix if isinstance(prefix,", "and can only raise exceptions inherited from :exc:`.CommandError`. Example -------", "return ctx.message.author.id in my_whitelist \"\"\" self.add_check(func, call_once=True) return func async", "= {} self.__extensions = {} self._checks = [] self._check_once =", "name: :class:`str` The extension name to unload. It must be", "is ``('!', '!?')`` the ``'!?'`` prefix will never be matched", "module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception: # if the", "\"call once\" global check to the bot. Unlike regular global", "Regular global checks are called whenever a command is called", "Mapping[str, Cog]: \"\"\"Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog name", "# precondition: key not in self.__extensions lib = importlib.util.module_from_spec(spec) sys.modules[key]", "async def is_owner(self, user_id: str) -> bool: \"\"\"|coro| Checks if", ":class:`.Context`. .. note:: Similar to :meth:`~.Bot.before_invoke`\\, this is not called", "The invocation context to invoke. \"\"\" if ctx.command is not", "pass without error. If any check or argument parsing procedures", "ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "pre-invoke hook takes a sole parameter, a :class:`.Context`. .. note::", "internal command callback raising an error (i.e. :exc:`.CommandInvokeError`\\). This makes", "name in self.__extensions: raise ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name) if spec", "that call this method. owner_ids: Optional[Collection[:class:`int`]] The user IDs that", "later in the sequence. For example, if the command prefix", "if call_once else self._checks try: list_.remove(func) except ValueError: pass def", "a \"call once\" global check to the bot. Unlike regular", "requesting. This is equivalent to the name passed via keyword", "ctx def _print_error(self, ctx: Context, error: Exception) -> None: print(", "the default help message. help_command: Optional[:class:`.HelpCommand`] The help command implementation", "'extension_setup') except AttributeError: del sys.modules[key] raise ExtensionMissingEntryPoint(key) try: setup(self) except", "ExtensionNotFound The extension could not be imported. ExtensionMissingEntryPoint The extension", "None: raise ExtensionNotLoaded(name) # get the previous module states from", "command given under the invocation context and handles all the", "to any message as the previous one matches messages starting", "that takes in the bot as its first parameter and", "data = self._check_once if call_once else self._checks if len(data) ==", "self.dispatch_error(ctx, exc) async def process_commands(self, message: Message) -> None: \"\"\"|coro|", "a sole parameter, a :class:`.Context`. .. note:: Similar to :meth:`~.Bot.before_invoke`\\,", "passed is not actually a coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro):", "prefix-less command invocation. The command prefix could also be an", "a :class:`fortnitepy.Client` you can do with this bot. This class", "bot is listening for. \"\"\" # noqa prefix = ret", "command implementation to use. This can be dynamically set at", "error if that's the case. if isinstance(ret, collections.abc.Iterable): raise raise", "to whom the Software is furnished to do so, subject", "message context to get the prefix of. Returns -------- Union[List[:class:`str`],", "of the cog to remove. \"\"\" cog = self.__cogs.pop(name, None)", "for func in data: if asyncio.iscoroutinefunction(func): res = await func(ctx)", "------ TypeError The coroutine passed is not actually a coroutine.", "\"\"\" # noqa prefix = ret = self.command_prefix if callable(prefix):", "dispatch_close: bool = True) -> None: if dispatch_close: await asyncio.gather(", "This hook is, however, **always** called regardless of the internal", "e) from e else: self.__extensions[key] = lib def load_extension(self, name:", "was not loaded. ExtensionNotFound The extension could not be imported.", "is called. This makes it a useful function to clean-up", "the invocation prefix. You can get this prefix via :attr:`.Context.prefix`.", "prefix via :attr:`.Context.prefix`. To avoid confusion empty iterables are not", "file=sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__, file=sys.stderr ) async def", "error )) else: self._print_error(ctx, error) async def invoke(self, ctx: Context)", "ctx) elif ctx.invoked_with: exc = CommandNotFound('Command \"{}\" is not found'", "r\"\"\"A decorator that registers a coroutine as a post-invoke hook.", "'!?')`` the ``'!?'`` prefix will never be matched to any", "You cannot set both `owner_id` and `owner_ids`. This is used", "this method. owner_ids: Optional[Collection[:class:`int`]] The user IDs that owns the", "True) -> None: if dispatch_close: await asyncio.gather( self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'), )", "and ensures that it's called only once, even inside the", "extension is loaded. This entry point must have a single", "mid-reload then the bot will roll-back to the prior working", "to register as the pre-invoke hook. Raises ------ TypeError The", "name, module in sys.modules.items() if _is_submodule(lib.__name__, name) } try: #", "not ' '{0.__class__!r}'.format(self.owner_ids) ) self.__cogs = {} self.__extensions = {}", "invocation. The command prefix could also be an iterable of", "TypeError('Iterable command_prefix or list ' 'returned from get_prefix must '", "= _DefaultRepr() class Bot(GroupMixin, Client): \"\"\"Represents a fortnite bot. This", "prefixes. This callable can be either a regular function or", "Optional[HelpCommand] = _default, description: Optional[str] = None, **kwargs: Any) ->", "empty string as the prefix always matches, enabling prefix-less command", "This function takes a single parameter, the ``bot``, similar to", "refreshed. This is equivalent to a :meth:`unload_extension` followed by a", "of the Software, and to permit persons to whom the", "to normal and raise back to caller sys.modules.update(modules) raise @property", "well. description: :class:`str` The content prefixed into the default help", "to with the message as a context. Parameters ---------- message:", "a coroutine.') self._after_invoke = coro return coro def add_cog(self, cog:", "be the invocation prefix. You can get this prefix via", "self.remove_cog(cogname) # remove all the commands from the module for", "an iterable of strings indicating that multiple checks for the", "raise ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name) if spec is None: raise", ":class:`fortnitepy.PartyMessage`] The message to get the invocation context from. cls", "(the \"Software\"), to deal in the Software without restriction, including", "a valid invocation context, :attr:`.Context.valid` must be checked to make", "invocation context, :attr:`.Context.valid` must be checked to make sure it", "to set up database connections or any type of set", "*, check: Optional[callable] = None, timeout: Optional[int] = None, cancel:", "This is used by :meth:`.is_owner()` and checks that call this", "followed by a call to :meth:`~.Bot.invoke`. Parameters ----------- message: Union[:class:`fortnitepy.FriendMessage`,", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "and `owner_ids`. This is used by :meth:`.is_owner()` and checks that", "# Unload and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name)", "loaded. \"\"\" lib = self.__extensions.get(name) if lib is None: raise", "= logging.getLogger(__name__) def _is_submodule(parent: str, child: str) -> bool: return", "sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises", ":meth:`~.Bot.invoke`. Parameters ----------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to process", "replaces the extension with the same extension, only refreshed. This", "the ``bot``, similar to ``extension_setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name:", "coroutine. This function takes a single parameter, :class:`.Context`, and can", "This is especially important when passing an empty string, it", "None: if value is not None: if not isinstance(value, HelpCommand):", "in the Software without restriction, including without limitation the rights", "a call to :meth:`~.Bot.invoke`. Parameters ----------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The", "if lib is None: raise ExtensionNotLoaded(name) # get the previous", "ExtensionFailed(key, e) from e else: self.__extensions[key] = lib def load_extension(self,", "import Auth from fortnitepy.typedefs import MaybeCoro, ListOrTuple from ._types import", "and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except", "or its setup function had an execution error. \"\"\" if", "HelpCommand, FortniteHelpCommand from .typedefs import Message log = logging.getLogger(__name__) def", "at runtime. To remove the help command pass ``None``. For", "reload_extension(self, name: str) -> None: \"\"\"Atomically reloads an extension. This", "futures while pending: done, pending = await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED,", "can do with a :class:`fortnitepy.Client` you can do with this", "and raise back to caller sys.modules.update(modules) raise @property def extensions(self)", "str) -> None: try: func = getattr(lib, 'cog_teardown') except AttributeError:", "load_extension(self, name: str) -> None: \"\"\"Loads an extension. An extension", "None: if not isinstance(value, HelpCommand): raise TypeError('help_command must be a", "self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) def reload_extension(self, name: str) -> None: \"\"\"Atomically", "ExtensionFailed The extension setup function had an execution error. \"\"\"", "= help_command self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message', self.process_commands) def register_methods(self) -> None:", "' '{0.__class__!r}'.format(self.owner_ids) ) self.__cogs = {} self.__extensions = {} self._checks", "self.__extensions.pop(key, None) sys.modules.pop(key, None) name = lib.__name__ for module in", "that owns the bot. This is used by :meth:`.is_owner()` and", "required. This pre-invoke hook takes a sole parameter, a :class:`.Context`.", "-> None: # precondition: key not in self.__extensions lib =", "coroutine.') self._after_invoke = coro return coro def add_cog(self, cog: Cog)", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "extension_setup function. ExtensionFailed The extension or its setup function had", "call_once else self._checks if len(data) == 0: return True for", "lib try: spec.loader.exec_module(lib) except Exception as e: del sys.modules[key] raise", "checks. call_once: :class:`bool` If the function was added with ``call_once=True``", "takes a single parameter, :class:`.Context`, and can only raise exceptions", "same extension, only refreshed. This is equivalent to a :meth:`unload_extension`", "Whether the commands should be case insensitive. Defaults to ``False``.", "\"\"\" def __init__(self, command_prefix: Any, auth: Auth, *, help_command: Optional[HelpCommand]", "collection not ' '{0.__class__!r}'.format(self.owner_ids) ) self.__cogs = {} self.__extensions =", "check once functions ' 'failed.') except CommandError as exc: await", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"", "the cogs registered from the module for cogname, cog in", "let's load it from our old compiled library. lib.extension_setup(self) self.__extensions[name]", "'returning either of these, not ' '{}'.format(ret.__class__.__name__)) if not ret:", "exception in command {}:'.format(ctx.command), file=sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__,", "from .core import GroupMixin from .cog import Cog from .view", "own event listeners and commands. Parameters ---------- cog: :class:`.Cog` The", "remove all the commands from the module for cmd in", "\"\"\"Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog name to cog.", "raise ExtensionMissingEntryPoint(key) try: setup(self) except Exception as e: del sys.modules[key]", "False) super().__init__(auth, **kwargs) self.command_prefix = command_prefix self.description = inspect.cleandoc(description) if", "the listeners from the module for event_list in self._events.copy().values(): remove", "makes it ideal for clean-up scenarios. Parameters ---------- coro: The", "not ' '{}'.format(value.__class__.__name__)) raise invoker = view.get_word() ctx.invoked_with = invoker", "else: ret = prefix(self, message) if not isinstance(ret, str): try:", "plain string, ' 'iterable of strings, or callable ' 'returning", "as a post-invoke hook. A post-invoke hook is called directly", "= getattr(lib, 'cog_teardown') except AttributeError: pass else: try: func(self) except", "followed by a :meth:`load_extension` except done in an atomic way.", "or any type of clean up required. This post-invoke hook", "types import sys import importlib import collections import traceback from", "to have a command invoked. This prefix could either be", "----------- ctx: :class:`.Context` The invocation context to invoke. \"\"\" if", "to the prior working state. Parameters ------------ name: :class:`str` The", "dispatch_error(self, ctx: Context, error: Exception) -> None: if self._event_has_handler('command_error'): futures", "import collections import traceback from typing import Any, List, Optional,", "' 'contain only strings, not ' '{}'.format(value.__class__.__name__)) raise invoker =", "-> None: for _, obj in inspect.getmembers(self): if isinstance(obj, _BaseCommand):", "try: func = getattr(lib, 'cog_teardown') except AttributeError: pass else: try:", "ensures that it's called only once, even inside the default", "pending = futures while pending: done, pending = await asyncio.wait(", "is None or check(future): if cancel: _cancel_futs(pending) return future async", "do with a :class:`fortnitepy.Client` you can do with this bot.", "is called directly after the command is called. This makes", "\"\"\"|coro| Retrieves the prefix the bot is listening to with", "should always be last as no prefix after it will", "is listening for. \"\"\" # noqa prefix = ret =", "first parameter and :class:`fortnitepy.FriendMessage` or :class:`fortnitepy.PartyMessage` as its second parameter", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "string to indicate what the prefix should be, or a", "Context) -> Context: r\"\"\"|coro| Returns the invocation context from the", "in inspect.getmembers(self): if isinstance(obj, _BaseCommand): obj.instance = self if obj.parent", "command prefix is ``('!', '!?')`` the ``'!?'`` prefix will never", "you can do with a :class:`fortnitepy.Client` you can do with", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "key: str) -> None: try: func = getattr(lib, 'cog_teardown') except", "None: \"\"\"Atomically reloads an extension. This replaces the extension with", "callable can be either a regular function or a coroutine.", "passing an empty string, it should always be last as", "call_once=True) return func async def can_run(self, ctx: Context, *, call_once:", "ctx.invoked_with = invoker ctx.prefix = invoked_prefix ctx.command = self.all_commands.get(invoker) return", "that owns the bot. This is similar to `owner_id`. For", "pass def check_once(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that", "func(ctx) if not res: return False return True async def", "is called or :meth:`.Command.can_run` is called. This type of check", ":meth:`.Command.can_run` is called. This type of check bypasses that and", "= prefix(self, message) if not isinstance(ret, str): try: ret =", "(MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free", "the pre-invoke hook. Raises ------ TypeError The coroutine passed is", "global function, ``extension_setup`` defined as the entry point on what", "the module is un-imported. The extension can provide an optional", "@bot.check def global_check(ctx): # Allows only party commands. return ctx.party", "load_extension function call # so let's load it from our", "= self.__cogs.pop(name, None) if cog is None: return help_command =", "------- :class:`bool` Whether the user is the owner. \"\"\" if", "' 'of HelpCommand') if self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command", "\"\"\" self.add_check(func, call_once=True) return func async def can_run(self, ctx: Context,", "type of clean up required. This post-invoke hook takes a", "a :meth:`load_extension` except done in an atomic way. That is,", "None: self._help_command._remove_from_bot(self) self._help_command = value value._add_to_bot(self) elif self._help_command is not", "del event_list[index] def _call_module_finalizers(self, lib: object, key: str) -> None:", "so let's load it from our old compiled library. lib.extension_setup(self)", "if message.author.id == self.user.id: return ctx = await self.get_context(message) await", "is the owner of the bot. Parameters ---------- user_id: :class:`str`", ".typedefs import Message log = logging.getLogger(__name__) def _is_submodule(parent: str, child:", "pass ``None``. For more information on implementing a help command,", "isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name) # remove all the listeners from", "in my_whitelist \"\"\" self.add_check(func, call_once=True) return func async def can_run(self,", "name: :class:`str` The extension name to load. It must be", "a string ' 'or a list of string, not '", "if lib is None: raise ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) def", "return self._help_command @help_command.setter def help_command(self, value: Optional[HelpCommand]) -> None: if", "-> None: \"\"\"|coro| This function processes the commands that have", "change via the ``cls`` parameter. \"\"\" # noqa view =", "function can either be a regular function or a coroutine.", "above copyright notice and this permission notice shall be included", "Context, error: Exception) -> None: print( 'Ignoring exception in command", "is not None: self._help_command._remove_from_bot(self) self._help_command = None else: self._help_command =", "read-only mapping of extension name to extension. \"\"\" return types.MappingProxyType(self.__extensions)", "None: if self._event_has_handler('command_error'): futures = self.dispatch_event('command_error', ctx, error) asyncio.ensure_future(self._wait_for_error_return( futures,", "\"\"\"Removes a cog from the bot. All registered commands and", "= [] self._check_once = [] self._help_command = None self._before_invoke =", "returned instead. Parameters ----------- name: :class:`str` The name of the", "= await prefix(self, message) else: ret = prefix(self, message) if", "Attributes ----------- command_prefix The command prefix is what the message", "An extension is a python module that contains commands, cogs,", "remove. \"\"\" cog = self.__cogs.pop(name, None) if cog is None:", "a :class:`.Context`. .. note:: The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are", "else '' self.owner_id = kwargs.get('owner_id') self.owner_ids = kwargs.get('owner_ids', set()) if", "else: self._help_command = None async def get_prefix(self, message: Message) ->", "str) -> bool: \"\"\"|coro| Checks if a user id is", "its second parameter and returns the prefix. This is to", "_default: self.help_command = FortniteHelpCommand() else: self.help_command = help_command self.add_event_handler('friend_message', self.process_commands)", "passing multiple prefixes be careful to not pass a prefix", "r\"\"\"A decorator that adds a \"call once\" global check to", "either be a regular function or a coroutine. This function", "is not actually a coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro): raise", "important when passing an empty string, it should always be", "adds a check globally to every command. .. note:: This", "to any person obtaining a copy of this software and", "matches messages starting with ``!?``. This is especially important when", "a command is called or :meth:`.Command.can_run` is called. This type", "from. cls The factory class that will be used to", "was used as a global check. call_once: :class:`bool` If the", "mapping of extension name to extension. \"\"\" return types.MappingProxyType(self.__extensions) @property", "= {} self._checks = [] self._check_once = [] self._help_command =", "import sys import importlib import collections import traceback from typing", ":class:`.Context` The invocation context to invoke. \"\"\" if ctx.command is", "pre-invoke hook. Raises ------ TypeError The coroutine passed is not", "person obtaining a copy of this software and associated documentation", "def after_invoke(self, coro: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that registers", "return ret async def get_context(self, message: Message, *, cls: Context", "cls(prefix=None, view=view, bot=self, message=message) prefix = await self.get_prefix(message) invoked_prefix =", "This makes it ideal for clean-up scenarios. Parameters ---------- coro:", "def _wait_for_error_return(self, futures: List[asyncio.Future], ctx: Context, error: Exception) -> None:", "a :meth:`unload_extension` followed by a :meth:`load_extension` except done in an", "what the prefix should be, or a callable that takes", "only be called once per :meth:`Command.invoke` call. \"\"\" if call_once:", "traceback.print_exception( type(error), error, error.__traceback__, file=sys.stderr ) async def wait_for_futures(self, futures:", "and this permission notice shall be included in all copies", "self.dispatch_event('command_error', ctx, error) asyncio.ensure_future(self._wait_for_error_return( futures, ctx, error )) else: self._print_error(ctx,", "then the bot will roll-back to the prior working state.", "= getattr(lib, 'extension_setup') except AttributeError: del sys.modules[key] raise ExtensionMissingEntryPoint(key) try:", "no prefix after it will be matched. case_insensitive: :class:`bool` Whether", "the message content must contain initially to have a command", "asyncio.gather( self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'), ) for extension in tuple(self.__extensions): try: self.unload_extension(extension)", "message.content.startswith(tuple(prefix)): for element in prefix: if view.skip_string(element): invoked_prefix = element", "help message. help_command: Optional[:class:`.HelpCommand`] The help command implementation to use.", "Parameters ------------ name: :class:`str` The extension name to unload. It", "not have a extension_setup function. ExtensionFailed The extension or its", "' 'least one prefix') return ret async def get_context(self, message:", "\"\"\"A decorator that registers a coroutine as a pre-invoke hook.", "name to reload. It must be dot separated like regular", "if not res: return False return True async def is_owner(self,", "from the bot. All registered commands and event listeners that", "is not found' ''.format(ctx.invoked_with)) self.dispatch_error(ctx, exc) async def process_commands(self, message:", "bot=self, message=message) prefix = await self.get_prefix(message) invoked_prefix = prefix if", "parameter, a :class:`.Context`. .. note:: The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks", "future async def _wait_for_error_return(self, futures: List[asyncio.Future], ctx: Context, error: Exception)", "coroutine to register as the post-invoke hook. Raises ------ TypeError", "sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key) raise ExtensionFailed(key, e) from e else:", "to process commands for. \"\"\" # noqa if message.author.id ==", "contains commands, cogs, or listeners. An extension must have a", "Raises ------- ExtensionNotLoaded The extension was not loaded. \"\"\" lib", "by a call to :meth:`~.Bot.invoke`. Parameters ----------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`]", "Exception: pass await self._close( close_http=close_http, dispatch_close=dispatch_close ) def check(self, func:", "error happened during loading. \"\"\" if not isinstance(cog, Cog): raise", "a prefix that matches a longer prefix occurring later in", "= ret = self.command_prefix if callable(prefix): if asyncio.iscoroutinefunction(prefix): ret =", "{} self.__extensions = {} self._checks = [] self._check_once = []", "the post-invoke hook. Raises ------ TypeError The coroutine passed is", "# revert sys.modules back to normal and raise back to", "careful to not pass a prefix that matches a longer", "back to normal and raise back to caller sys.modules.update(modules) raise", "it will be matched. case_insensitive: :class:`bool` Whether the commands should", "prefix always matches, enabling prefix-less command invocation. The command prefix", "get the prefix of. Returns -------- Union[List[:class:`str`], :class:`str`] A list", "that will be used to create the context. By default,", "first one to match will be the invocation prefix. You", "is a class that has its own event listeners and", "documentation files (the \"Software\"), to deal in the Software without", "Exception as e: del sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key) raise ExtensionFailed(key,", "a :class:`set` for the collection. You cannot set both `owner_id`", ":class:`str` The extension name to load. It must be dot", "without restriction, including without limitation the rights to use, copy,", "be used and the first one to match will be", "to clean-up database connections or any type of clean up", "A cog is a class that has its own event", "False) -> None: def _cancel_futs(pending_futures: Set[asyncio.Future]) -> None: for p", "before the command is called. This makes it a useful", "the bot. This is similar to `owner_id`. For performance reasons", "are set.') if (self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection)): raise TypeError(", "makes it a useful function to clean-up database connections or", "``foo/test.py``. Raises ------ ExtensionNotFound The extension could not be imported.", "get the invocation context from. cls The factory class that", "Cog from .view import StringView from .context import Context from", "prefix will never be matched to any message as the", "string, it should always be last as no prefix after", "from :exc:`.CommandError`. Example ------- .. code-block:: python3 @bot.check_once def whitelist(ctx):", "be imported. ExtensionMissingEntryPoint The extension does not have a extension_setup", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "then this method has no effect. Parameters ---------- name: :class:`str`", "for cogname, cog in self.__cogs.copy().items(): if _is_submodule(name, cog.__module__): self.remove_cog(cogname) #", "---------- name: :class:`str` The extension name to load. It must", "import importlib import collections import traceback from typing import Any,", "None: if dispatch_close: await asyncio.gather( self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'), ) for extension", "extension is unloaded, all commands, listeners, and cogs are removed", "from Cog.') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog def remove_cog(self,", "a fortnite bot. This class is a subclass of :class:`fortnitepy.Client`", "@help_command.setter def help_command(self, value: Optional[HelpCommand]) -> None: if value is", "func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that adds a check", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies", ") for extension in tuple(self.__extensions): try: self.unload_extension(extension) except Exception: pass", "granted, free of charge, to any person obtaining a copy", "This can be dynamically set at runtime. To remove the", "the extension with the same extension, only refreshed. This is", "of :class:`fortnitepy.Client` and as a result anything that you can", "that adds a \"call once\" global check to the bot.", "func async def can_run(self, ctx: Context, *, call_once: bool =", "sole parameter, a :class:`.Context`. .. note:: The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke`", "registered from the module for cogname, cog in self.__cogs.copy().items(): if", "call_once=True): await ctx.command.invoke(ctx) else: raise CheckFailure('The global check once functions", "if self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command = value value._add_to_bot(self)", "Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to process commands for. \"\"\" #", "obj in inspect.getmembers(self): if isinstance(obj, _BaseCommand): obj.instance = self if", "result anything that you can do with a :class:`fortnitepy.Client` you", "raise TypeError('The post-invoke hook must be a coroutine.') self._after_invoke =", "_call_module_finalizers(self, lib: object, key: str) -> None: try: func =", "that was used as a global check. call_once: :class:`bool` If", "isinstance(prefix, str): if not view.skip_string(prefix): return ctx else: try: if", "provided, it must be similar enough to :class:`.Context`\\'s interface. Returns", "sys import importlib import collections import traceback from typing import", "close_http=close_http, dispatch_close=dispatch_close ) def check(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A", "will be removed as well. If no cog is found", "called. This type of check bypasses that and ensures that", "@bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist \"\"\" self.add_check(func, call_once=True)", "groups. You must set it to every group if you", "if not isinstance(value, str): raise TypeError('Iterable command_prefix or list '", "future in done: if check is None or check(future): if", "single parameter, :class:`.Context`, and can only raise exceptions inherited from", "None self._after_invoke = None if help_command is _default: self.help_command =", "= None self._after_invoke = None if help_command is _default: self.help_command", "have a extension_setup function. ExtensionFailed The extension or its setup", "invocation context from. cls The factory class that will be", "func def add_check(self, func: MaybeCoro, *, call_once: bool = False)", "to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`. Parameters -----------", "call # so let's load it from our old compiled", "= FortniteHelpCommand() else: self.help_command = help_command self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message', self.process_commands)", "contain one value for future in done: if check is", "in prefix: if not isinstance(value, str): raise TypeError('Iterable command_prefix or", "def help_command(self) -> Optional[HelpCommand]: return self._help_command @help_command.setter def help_command(self, value:", "the bot. A cog is a class that has its", "\".\") class _DefaultRepr: def __repr__(self) -> str: return '<default-help-command>' _default", "python module that contains commands, cogs, or listeners. An extension", "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "necessary. This function takes a single parameter, the ``bot``, similar", "only party commands. return ctx.party is not None \"\"\" self.add_check(func)", "self._checks if len(data) == 0: return True for func in", "extension or its setup function had an execution error. \"\"\"", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "the prefix should be used and the first one to", "function had an execution error. \"\"\" if name in self.__extensions:", "enabling prefix-less command invocation. The command prefix could also be", "except Exception: pass await self._close( close_http=close_http, dispatch_close=dispatch_close ) def check(self,", "have been registered to the bot and other groups. Without", "it is recommended to use a :class:`set` for the collection.", "ExtensionNotLoaded(name) # get the previous module states from sys modules", "has no effect. Parameters ---------- name: :class:`str` The name of", "None: for p in pending_futures: if not p.cancelled(): p.cancel() pending", "more information on implementing a help command, see :ref:`ext_commands_help_command`. owner_id:", "coro return coro def add_cog(self, cog: Cog) -> None: \"\"\"Adds", "self.__extensions = {} self._checks = [] self._check_once = [] self._help_command", "hook takes a sole parameter, a :class:`.Context`. .. note:: Similar", "a help command, see :ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`] The user ID", "*, help_command: Optional[HelpCommand] = _default, description: Optional[str] = None, **kwargs:", "removed from the bot and the module is un-imported. The", "= await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout ) # Set should", "lib is None: raise ExtensionNotLoaded(name) # get the previous module", "Raises ------ TypeError The cog does not inherit from :class:`.Cog`.", "Copyright (c) 2015-present Rapptz Permission is hereby granted, free of", "notice shall be included in all copies or substantial portions", "str) -> Optional[Cog]: \"\"\"Gets the cog instance requested. If the", "to provide the functionality to manage commands. Attributes ----------- command_prefix", "' '{}'.format(ret.__class__.__name__)) if not ret: raise ValueError('Iterable command_prefix must contain", "Message) -> None: \"\"\"|coro| This function processes the commands that", "None: \"\"\"Unloads an extension. When the extension is unloaded, all", "not res: return False return True async def is_owner(self, user_id:", "from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to", "be plain string, ' 'iterable of strings, or callable '", "---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message context to get the", "candidate to be invoked under :meth:`~.Bot.invoke`. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`,", "and :class:`fortnitepy.FriendMessage` or :class:`fortnitepy.PartyMessage` as its second parameter and returns", "parameter. \"\"\" # noqa view = StringView(message.content) ctx = cls(prefix=None,", "ret = list(ret) except TypeError: # It's possible that a", "global checks are called whenever a command is called or", "check to the bot. This is the non-decorator interface to", "Auth, *, help_command: Optional[HelpCommand] = _default, description: Optional[str] = None,", "import logging import inspect import asyncio import types import sys", "contain initially to have a command invoked. This prefix could", "None: # precondition: key not in self.__extensions lib = importlib.util.module_from_spec(spec)", "Raises ------- ExtensionNotLoaded The extension was not loaded. ExtensionNotFound The", "it ideal for clean-up scenarios. Parameters ---------- coro: The coroutine", "not isinstance(self.owner_ids, collections.abc.Collection)): raise TypeError( 'owner_ids must be a collection", "from .help import HelpCommand, FortniteHelpCommand from .typedefs import Message log", "else self._checks if len(data) == 0: return True for func", "None) if cog is None: return help_command = self.help_command if", "note:: Similar to :meth:`~.Bot.before_invoke`\\, this is not called unless checks", "extension is a python module that contains commands, cogs, or", "that the bot is listening for. \"\"\" # noqa prefix", "for :meth:`.process_commands` to allow users more fine grained control over", "MaybeCoro, *, call_once: bool = False) -> None: \"\"\"Removes a", "import inspect import asyncio import types import sys import importlib", "also be an iterable of strings indicating that multiple checks", "sure it is. If the context is not valid then", "is a more low-level counter-part for :meth:`.process_commands` to allow users", "ctx: Context) -> None: \"\"\"|coro| Invokes the command given under", "the internal command callback raising an error (i.e. :exc:`.CommandInvokeError`\\). This", "command prefixes. This callable can be either a regular function", "lib def load_extension(self, name: str) -> None: \"\"\"Loads an extension.", "self.command_prefix if callable(prefix): if asyncio.iscoroutinefunction(prefix): ret = await prefix(self, message)", "procedures fail then the hooks are not called. Parameters ----------", "return future.result() is False ret = await self.wait_for_futures(futures, check=check) if", "if asyncio.iscoroutinefunction(prefix): ret = await prefix(self, message) else: ret =", "be matched to any message as the previous one matches", "inherited from :exc:`.CommandError`. Example ------- .. code-block:: python3 @bot.check def", "only strings, not ' '{}'.format(value.__class__.__name__)) raise invoker = view.get_word() ctx.invoked_with", "atomic way. That is, if an operation fails mid-reload then", "try: func(self) except Exception: pass finally: self.__extensions.pop(key, None) sys.modules.pop(key, None)", "an operation fails mid-reload then the bot will roll-back to", "control over the processing. The returned context is not guaranteed", "futures: ListOrTuple, *, check: Optional[callable] = None, timeout: Optional[int] =", "-> None: \"\"\"Unloads an extension. When the extension is unloaded,", "the commands will be triggered. By default, this coroutine is", "spec.loader.exec_module(lib) except Exception as e: del sys.modules[key] raise ExtensionFailed(key, e)", "it is not a valid candidate to be invoked under", "if not view.skip_string(prefix): return ctx else: try: if message.content.startswith(tuple(prefix)): for", "return ctx def _print_error(self, ctx: Context, error: Exception) -> None:", "MaybeCoro: r\"\"\"A decorator that adds a \"call once\" global check", "remove = [] for index, event in enumerate(event_list): if (event.__module__", "copies of the Software, and to permit persons to whom", "def help_command(self, value: Optional[HelpCommand]) -> None: if value is not", "kwargs.get('owner_ids', set()) if self.owner_id and self.owner_ids: raise TypeError('Both owner_id and", "hook takes a sole parameter, a :class:`.Context`. .. note:: The", "to deal in the Software without restriction, including without limitation", "Message, *, cls: Context = Context) -> Context: r\"\"\"|coro| Returns", "This type of check bypasses that and ensures that it's", "a sole parameter, a :class:`.Context`. .. note:: The :meth:`~.Bot.before_invoke` and", "cog.__module__): self.remove_cog(cogname) # remove all the commands from the module", "passed via keyword argument in class creation or the class", "creation or the class name if unspecified. \"\"\" return self.__cogs.get(name)", "------ ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded The", "return ctx.party is not None \"\"\" self.add_check(func) return func def", "Exception) -> None: if self._event_has_handler('command_error'): futures = self.dispatch_event('command_error', ctx, error)", "context from. cls The factory class that will be used", "after it will be matched. case_insensitive: :class:`bool` Whether the commands", "or :class:`fortnitepy.PartyMessage` as its second parameter and returns the prefix.", "return user_id in self.owner_ids def before_invoke(self, coro: MaybeCoro) -> MaybeCoro:", "Returns the invocation context from the message. This is a", "<filename>fortnitepy/ext/commands/bot.py<gh_stars>100-1000 \"\"\" The MIT License (MIT) Copyright (c) 2015-present Rapptz", "self.__cogs = {} self.__extensions = {} self._checks = [] self._check_once", "self.add_check(func, call_once=True) return func async def can_run(self, ctx: Context, *,", "An error happened during loading. \"\"\" if not isinstance(cog, Cog):", "``cls`` parameter. \"\"\" # noqa view = StringView(message.content) ctx =", "unless checks and argument parsing procedures succeed. This hook is,", "the cog has registered will be removed as well. If", "self._checks.append(func) def remove_check(self, func: MaybeCoro, *, call_once: bool = False)", "spec = importlib.util.find_spec(name) if spec is None: raise ExtensionNotFound(name) self._load_from_module_spec(spec,", "message) if not isinstance(ret, str): try: ret = list(ret) except", ":class:`fortnitepy.FriendMessage` or :class:`fortnitepy.PartyMessage` as its second parameter and returns the", "while pending: done, pending = await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout", "self._print_error(ctx, error) async def invoke(self, ctx: Context) -> None: \"\"\"|coro|", "value: Optional[HelpCommand]) -> None: if value is not None: if", "ExtensionNotLoaded The extension was not loaded. \"\"\" lib = self.__extensions.get(name)", "not called. Parameters ---------- coro The coroutine to register as", "the command given under the invocation context and handles all", "self._checks = [] self._check_once = [] self._help_command = None self._before_invoke", "reloads an extension. This replaces the extension with the same", "spec: types.ModuleType, key: str) -> None: # precondition: key not", "MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby", "(i.e. :exc:`.CommandInvokeError`\\). This makes it ideal for clean-up scenarios. Parameters", "limitation the rights to use, copy, modify, merge, publish, distribute,", "subject to the following conditions: The above copyright notice and", "The cog to register to the bot. Raises ------ TypeError", "if not isinstance(prefix, list): raise TypeError('get_prefix must return either a", "module): del sys.modules[module] def _load_from_module_spec(self, spec: types.ModuleType, key: str) ->", "registered to the bot and other groups. Without this coroutine,", "The extension name to load. It must be dot separated", "the prefix. This is to facilitate \"dynamic\" command prefixes. This", "multiple checks for the prefix should be used and the", "if not p.cancelled(): p.cancel() pending = futures while pending: done,", "Parameters ----------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to process commands", "ctx.message.author.id in my_whitelist \"\"\" self.add_check(func, call_once=True) return func async def", "kwargs.get('owner_id') self.owner_ids = kwargs.get('owner_ids', set()) if self.owner_id and self.owner_ids: raise", "= element break else: invoked_prefix = None else: return ctx", "'or a list of string, not ' '{}'.format(prefix.__class__.__name__)) for value", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A", "you want to import ``foo/test.py``. Raises ------ ExtensionNotFound The extension", "self._help_command = value value._add_to_bot(self) elif self._help_command is not None: self._help_command._remove_from_bot(self)", "other groups. Without this coroutine, none of the commands will", "for cog in tuple(self.__cogs): try: self.remove_cog(cog) except Exception: pass await", "a valid candidate to be invoked under :meth:`~.Bot.invoke`. Parameters ----------", "load failed, the remnants should have been # cleaned from", "the message as a context. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`]", "example, if the command prefix is ``('!', '!?')`` the ``'!?'``", "Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "bot. All registered commands and event listeners that the cog", "cog._inject(self) self.__cogs[cog.__cog_name__] = cog def remove_cog(self, name: str) -> None:", "def get_context(self, message: Message, *, cls: Context = Context) ->", "``bot``, similar to ``extension_setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str`", "post-invoke hook takes a sole parameter, a :class:`.Context`. .. note::", "done in an atomic way. That is, if an operation", "Context) -> None: \"\"\"|coro| Invokes the command given under the", "lib: object, key: str) -> None: try: func = getattr(lib,", "have a extension_setup function. ExtensionFailed The extension setup function had", "TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = coro", "of extension name to extension. \"\"\" return types.MappingProxyType(self.__extensions) @property def", "view.skip_string(prefix): return ctx else: try: if message.content.startswith(tuple(prefix)): for element in", "previous one matches messages starting with ``!?``. This is especially", "HelpCommand): raise TypeError('help_command must be a subclass ' 'of HelpCommand')", "way. That is, if an operation fails mid-reload then the", "method. owner_ids: Optional[Collection[:class:`int`]] The user IDs that owns the bot.", "DEALINGS IN THE SOFTWARE. \"\"\" import logging import inspect import", "string ' 'or a list of string, not ' '{}'.format(prefix.__class__.__name__))", "to :meth:`~.Bot.invoke`. Parameters ----------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to", "\"\"\" return types.MappingProxyType(self.__cogs) def _remove_module_references(self, name: str) -> None: #", "invocation context from the message. This is a more low-level", "of the commands will be triggered. By default, this coroutine", ")) else: self._print_error(ctx, error) async def invoke(self, ctx: Context) ->", "registers a coroutine as a post-invoke hook. A post-invoke hook", "len(data) == 0: return True for func in data: if", "connections or any type of clean up required. This post-invoke", "miscellaneous clean-up if necessary. This function takes a single parameter,", "error: Exception) -> None: if self._event_has_handler('command_error'): futures = self.dispatch_event('command_error', ctx,", "ListOrTuple from ._types import _BaseCommand from .errors import (ExtensionFailed, ExtensionMissingEntryPoint,", "requested. If the cog is not found, ``None`` is returned", "None: kwargs['case_insensitive'] = kwargs.get('case_insensitive', False) super().__init__(auth, **kwargs) self.command_prefix = command_prefix", "or a coroutine. An empty string as the prefix always", "\"\"\"Removes a global check from the bot. Parameters ---------- func", "especially important when passing an empty string, it should always", "a coroutine as a pre-invoke hook. A pre-invoke hook is", "a coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook", "self.process_commands) self.add_event_handler('party_message', self.process_commands) def register_methods(self) -> None: for _, obj", "\"{}\" is not found' ''.format(ctx.invoked_with)) self.dispatch_error(ctx, exc) async def process_commands(self,", "find all references to the module # remove the cogs", "list_ = self._check_once if call_once else self._checks try: list_.remove(func) except", "collections.abc.Iterable): raise raise TypeError('command_prefix must be plain string, ' 'iterable", "it should always be last as no prefix after it", "command_prefix self.description = inspect.cleandoc(description) if description else '' self.owner_id =", "list of prefixes or a single prefix that the bot", ":meth:`.is_owner()` and checks that call this method. \"\"\" def __init__(self,", "\"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be", "view.get_word() ctx.invoked_with = invoker ctx.prefix = invoked_prefix ctx.command = self.all_commands.get(invoker)", "implementation to use. This can be dynamically set at runtime.", "carry over to groups. You must set it to every", "help_command: Optional[HelpCommand] = _default, description: Optional[str] = None, **kwargs: Any)", "Parameters ----------- ctx: :class:`.Context` The invocation context to invoke. \"\"\"", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "triggered. By default, this coroutine is called automatically when a", "in the bot as its first parameter and :class:`fortnitepy.FriendMessage` or", "''.format(ctx.invoked_with)) self.dispatch_error(ctx, exc) async def process_commands(self, message: Message) -> None:", "prefix should be used and the first one to match", "and help_command.cog is cog: help_command.cog = None cog._eject(self) def get_cog(self,", "-> None: # find all references to the module #", "set it to every group if you require group commands", "raise ExtensionNotLoaded(name) # get the previous module states from sys", "import Any, List, Optional, Mapping, Set from fortnitepy.client import Client", "cog to register to the bot. Raises ------ TypeError The", "a pre-invoke hook. A pre-invoke hook is called directly before", "does not inherit from :class:`.Cog`. CommandError An error happened during", "Client): \"\"\"Represents a fortnite bot. This class is a subclass", "must derive from Cog.') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog", "None) name = lib.__name__ for module in list(sys.modules.keys()): if _is_submodule(name,", "inspect.getmembers(self): if isinstance(obj, _BaseCommand): obj.instance = self if obj.parent is", "-> Optional[HelpCommand]: return self._help_command @help_command.setter def help_command(self, value: Optional[HelpCommand]) ->", "check(future): return future.result() is False ret = await self.wait_for_futures(futures, check=check)", "super().__init__(auth, **kwargs) self.command_prefix = command_prefix self.description = inspect.cleandoc(description) if description", "`owner_ids`. This is used by :meth:`.is_owner()` and checks that call", "e: del sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key) raise ExtensionFailed(key, e) from", "# Set should only contain one value for future in", "called regardless of the internal command callback raising an error", "``extension_setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name", "' '{}'.format(prefix.__class__.__name__)) for value in prefix: if not isinstance(value, str):", "Optional[int] = None, cancel: bool = False) -> None: def", "call. Regular global checks are called whenever a command is", "hook must be a coroutine.') self._after_invoke = coro return coro", "prefix could also be an iterable of strings indicating that", "else: try: func(self) except Exception: pass finally: self.__extensions.pop(key, None) sys.modules.pop(key,", "prefix occurring later in the sequence. For example, if the", "event_list in self._events.copy().values(): remove = [] for index, event in", "import MaybeCoro, ListOrTuple from ._types import _BaseCommand from .errors import", "checked to make sure it is. If the context is", "async def _wait_for_error_return(self, futures: List[asyncio.Future], ctx: Context, error: Exception) ->", "self._call_module_finalizers(lib, name) self.load_extension(name) except Exception: # if the load failed,", "ID that owns the bot. This is used by :meth:`.is_owner()`", "ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) def reload_extension(self, name: str) -> None:", "and argument parsing procedures pass without error. If any check", "func(self) except Exception: pass finally: self.__extensions.pop(key, None) sys.modules.pop(key, None) name", "except TypeError: if not isinstance(prefix, list): raise TypeError('get_prefix must return", "from the bot and the module is un-imported. The extension", "-> str: return '<default-help-command>' _default = _DefaultRepr() class Bot(GroupMixin, Client):", "bool = True, dispatch_close: bool = True) -> None: if", "succeed. This hook is, however, **always** called regardless of the", "not carry over to groups. You must set it to", "TypeError('Both owner_id and owner_ids are set.') if (self.owner_ids and not", "When passing multiple prefixes be careful to not pass a", "to remove. \"\"\" cog = self.__cogs.pop(name, None) if cog is", "Parameters ---------- name: :class:`str` The extension name to load. It", "a global check from the bot. Parameters ---------- func The", "-> Optional[Cog]: \"\"\"Gets the cog instance requested. If the cog", "@property def cogs(self) -> Mapping[str, Cog]: \"\"\"Mapping[:class:`str`, :class:`Cog`]: A read-only", "the following conditions: The above copyright notice and this permission", "is a subclass of :class:`fortnitepy.Client` and as a result anything", "have a command invoked. This prefix could either be a", "you require group commands to be case insensitive as well.", "AttributeError: pass else: try: func(self) except Exception: pass finally: self.__extensions.pop(key,", "raise ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) def reload_extension(self, name: str) ->", "ctx.party is not None \"\"\" self.add_check(func) return func def add_check(self,", "= importlib.util.find_spec(name) if spec is None: raise ExtensionNotFound(name) self._load_from_module_spec(spec, name)", "modules = { name: module for name, module in sys.modules.items()", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF", "raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke =", "strings, not ' '{}'.format(value.__class__.__name__)) raise invoker = view.get_word() ctx.invoked_with =", "this method. \"\"\" def __init__(self, command_prefix: Any, auth: Auth, *,", "via :attr:`.Context.prefix`. To avoid confusion empty iterables are not allowed.", "ctx: Context, error: Exception) -> None: print( 'Ignoring exception in", "help_command(self, value: Optional[HelpCommand]) -> None: if value is not None:", "parsing procedures succeed. This hook is, however, **always** called regardless", "prefix: if not isinstance(value, str): raise TypeError('Iterable command_prefix or list", "bot. Parameters ---------- func The function to remove from the", "None async def get_prefix(self, message: Message) -> Any: \"\"\"|coro| Retrieves", "If no cog is found then this method has no", "future.result() is False ret = await self.wait_for_futures(futures, check=check) if isinstance(ret,", "self.__cogs[cog.__cog_name__] = cog def remove_cog(self, name: str) -> None: \"\"\"Removes", "if spec is None: raise ExtensionNotFound(name) self._load_from_module_spec(spec, name) def unload_extension(self,", "if self._event_has_handler('command_error'): futures = self.dispatch_event('command_error', ctx, error) asyncio.ensure_future(self._wait_for_error_return( futures, ctx,", "async def invoke(self, ctx: Context) -> None: \"\"\"|coro| Invokes the", "self._print_error(ctx, error) def dispatch_error(self, ctx: Context, error: Exception) -> None:", "Optional[Cog]: \"\"\"Gets the cog instance requested. If the cog is", "self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'), ) for extension in tuple(self.__extensions): try: self.unload_extension(extension) except", "None: \"\"\"Removes a global check from the bot. Parameters ----------", "(ExtensionFailed, ExtensionMissingEntryPoint, ExtensionNotLoaded, ExtensionAlreadyLoaded, ExtensionNotFound, CheckFailure, CommandError, CommandNotFound) from .core", "auth: Auth, *, help_command: Optional[HelpCommand] = _default, description: Optional[str] =", "only refreshed. This is equivalent to a :meth:`unload_extension` followed by", "help_command self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message', self.process_commands) def register_methods(self) -> None: for", "a coroutine. An empty string as the prefix always matches,", "def before_invoke(self, coro: MaybeCoro) -> MaybeCoro: \"\"\"A decorator that registers", "with a :class:`fortnitepy.Client` you can do with this bot. This", "This post-invoke hook takes a sole parameter, a :class:`.Context`. ..", "user_id: str) -> bool: \"\"\"|coro| Checks if a user id", "else self._checks try: list_.remove(func) except ValueError: pass def check_once(self, func:", "can do with this bot. This class also subclasses :class:`.GroupMixin`", "add_cog(self, cog: Cog) -> None: \"\"\"Adds a \"cog\" to the", "single parameter, the ``bot``, similar to ``extension_setup`` from :meth:`~.Bot.load_extension`. Parameters", "of strings, or callable ' 'returning either of these, not", "bot is listening to with the message as a context.", "if call_once: self._check_once.append(func) else: self._checks.append(func) def remove_check(self, func: MaybeCoro, *,", "= await func(ctx) else: res = func(ctx) if not res:", "clean-up if necessary. This function takes a single parameter, the", "if message.content.startswith(tuple(prefix)): for element in prefix: if view.skip_string(element): invoked_prefix =", "if len(data) == 0: return True for func in data:", "then the hooks are not called. Parameters ---------- coro The", "should be, or a callable that takes in the bot", "on implementing a help command, see :ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`] The", "when the extension is loaded. This entry point must have", "prefix = await self.get_prefix(message) invoked_prefix = prefix if isinstance(prefix, str):", "instead. Parameters ----------- name: :class:`str` The name of the cog", "Any) -> None: kwargs['case_insensitive'] = kwargs.get('case_insensitive', False) super().__init__(auth, **kwargs) self.command_prefix", "listening for. \"\"\" # noqa prefix = ret = self.command_prefix", "either be a string to indicate what the prefix should", "If any check or argument parsing procedures fail then the", "_is_submodule(lib.__name__, name) } try: # Unload and then load the", ":class:`str` The extension name to reload. It must be dot", ":class:`.Context`. Should a custom class be provided, it must be", "except ValueError: pass def check_once(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A", "and owner_ids are set.') if (self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection)):", "------- .. code-block:: python3 @bot.check_once def whitelist(ctx): return ctx.message.author.id in", "pass finally: self.__extensions.pop(key, None) sys.modules.pop(key, None) name = lib.__name__ for", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "Exception) -> None: def check(future): return future.result() is False ret", "registered will be removed as well. If no cog is", "call_once: :class:`bool` If the function was added with ``call_once=True`` in", "Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to get the invocation context from.", "Raises ------ ExtensionNotFound The extension could not be imported. ExtensionAlreadyLoaded", "== 0: return True for func in data: if asyncio.iscoroutinefunction(func):", "cog does not inherit from :class:`.Cog`. CommandError An error happened", "callback raising an error (i.e. :exc:`.CommandInvokeError`\\). This makes it ideal", "when a new message is received. This is built using", "per :meth:`Command.invoke` call. \"\"\" if call_once: self._check_once.append(func) else: self._checks.append(func) def", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`.", "context from the message. This is a more low-level counter-part", "cog you are requesting. This is equivalent to the name", "empty string, it should always be last as no prefix", "default help message. help_command: Optional[:class:`.HelpCommand`] The help command implementation to", "{ name: module for name, module in sys.modules.items() if _is_submodule(lib.__name__,", "value is not None: if not isinstance(value, HelpCommand): raise TypeError('help_command", "indicating that multiple checks for the prefix should be used", "states from sys modules modules = { name: module for", "Optional[callable] = None, timeout: Optional[int] = None, cancel: bool =", "prefixed into the default help message. help_command: Optional[:class:`.HelpCommand`] The help", "call_once else self._checks try: list_.remove(func) except ValueError: pass def check_once(self,", "TypeError('The post-invoke hook must be a coroutine.') self._after_invoke = coro", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "is None: raise ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) def reload_extension(self, name:", "to use a :class:`set` for the collection. You cannot set", "This function takes a single parameter, :class:`.Context`, and can only", "bot. This is similar to `owner_id`. For performance reasons it", "raise CheckFailure('The global check once functions ' 'failed.') except CommandError", "exceptions inherited from :exc:`.CommandError`. Example ------- .. code-block:: python3 @bot.check_once", "setup(self) except Exception as e: del sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key)", ":ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`] The user ID that owns the bot.", "context to invoke. \"\"\" if ctx.command is not None: self.dispatch_event('command',", "been registered to the bot and other groups. Without this", "'' self.owner_id = kwargs.get('owner_id') self.owner_ids = kwargs.get('owner_ids', set()) if self.owner_id", "the load failed, the remnants should have been # cleaned", "load it from our old compiled library. lib.extension_setup(self) self.__extensions[name] =", "if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke hook must be a", "**kwargs: Any) -> None: kwargs['case_insensitive'] = kwargs.get('case_insensitive', False) super().__init__(auth, **kwargs)", "error, error.__traceback__, file=sys.stderr ) async def wait_for_futures(self, futures: ListOrTuple, *,", ".cog import Cog from .view import StringView from .context import", "be careful to not pass a prefix that matches a", "to manage commands. Attributes ----------- command_prefix The command prefix is", "or argument parsing procedures fail then the hooks are not", "check is None or check(future): if cancel: _cancel_futs(pending) return future", "p in pending_futures: if not p.cancelled(): p.cancel() pending = futures", "self.add_check(func) return func def add_check(self, func: MaybeCoro, *, call_once: bool", "all the listeners from the module for event_list in self._events.copy().values():", "getattr(lib, 'extension_setup') except AttributeError: del sys.modules[key] raise ExtensionMissingEntryPoint(key) try: setup(self)", "remove all the listeners from the module for event_list in", "The extension is already loaded. ExtensionMissingEntryPoint The extension does not", "None: raise ExtensionNotFound(name) self._load_from_module_spec(spec, name) def unload_extension(self, name: str) ->", "Example ------- .. code-block:: python3 @bot.check_once def whitelist(ctx): return ctx.message.author.id", "to be a valid invocation context, :attr:`.Context.valid` must be checked", "built using other low level tools, and is equivalent to", "coro: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that registers a coroutine", "is called only once per :meth:`Command.invoke` call. Regular global checks", "match will be the invocation prefix. You can get this", "CommandError as exc: await ctx.command.dispatch_error(ctx, exc) else: self.dispatch_event('command_completion', ctx) elif", "``('!', '!?')`` the ``'!?'`` prefix will never be matched to", "------- :class:`.Context` The invocation context. The type of this can", "message: Message) -> Any: \"\"\"|coro| Retrieves the prefix the bot", "check globally to every command. .. note:: This function can", "error: Exception) -> None: print( 'Ignoring exception in command {}:'.format(ctx.command),", "Without this coroutine, none of the commands will be triggered.", "clean-up database connections or any type of clean up required.", "error. \"\"\" if name in self.__extensions: raise ExtensionAlreadyLoaded(name) spec =", "List, Optional, Mapping, Set from fortnitepy.client import Client from fortnitepy.auth", "owner_ids are set.') if (self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection)): raise", "False return True async def is_owner(self, user_id: str) -> bool:", "This class is a subclass of :class:`fortnitepy.Client` and as a", "Optional[Collection[:class:`int`]] The user IDs that owns the bot. This is", "res: return False return True async def is_owner(self, user_id: str)", "print( 'Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr ) traceback.print_exception( type(error),", "that the cog has registered will be removed as well.", "message.author.id == self.user.id: return ctx = await self.get_context(message) await self.invoke(ctx)", "return True async def is_owner(self, user_id: str) -> bool: \"\"\"|coro|", "try: setup(self) except Exception as e: del sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib,", "the module for cogname, cog in self.__cogs.copy().items(): if _is_submodule(name, cog.__module__):", "command_prefix or list ' 'returned from get_prefix must ' 'contain", "-> None: kwargs['case_insensitive'] = kwargs.get('case_insensitive', False) super().__init__(auth, **kwargs) self.command_prefix =", "never be matched to any message as the previous one", "ctx: Context, error: Exception) -> None: def check(future): return future.result()", "once functions ' 'failed.') except CommandError as exc: await ctx.command.dispatch_error(ctx,", "self.help_command = FortniteHelpCommand() else: self.help_command = help_command self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message',", "distribute, sublicense, and/or sell copies of the Software, and to", "'returned from get_prefix must ' 'contain only strings, not '", "-> bool: data = self._check_once if call_once else self._checks if", "to a call to :meth:`~.Bot.get_context` followed by a call to", "None: \"\"\"Removes a cog from the bot. All registered commands", "------------ name: :class:`str` The extension name to unload. It must", "a custom class be provided, it must be similar enough", "remove the cogs registered from the module for cogname, cog", "# noqa if message.author.id == self.user.id: return ctx = await", "TypeError The coroutine passed is not actually a coroutine. \"\"\"", "has registered will be removed as well. If no cog", "to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not", "raise raise TypeError('command_prefix must be plain string, ' 'iterable of", "function should only be called once per :meth:`Command.invoke` call. \"\"\"", "can change via the ``cls`` parameter. \"\"\" # noqa view", "all references to the module # remove the cogs registered", "e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------", "not actually a coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The", ":meth:`Command.invoke` call. \"\"\" if call_once: self._check_once.append(func) else: self._checks.append(func) def remove_check(self,", "getattr(lib, 'cog_teardown') except AttributeError: pass else: try: func(self) except Exception:", "self.owner_ids: raise TypeError('Both owner_id and owner_ids are set.') if (self.owner_ids", "= coro return coro def add_cog(self, cog: Cog) -> None:", "the invocation context from. cls The factory class that will", ".. code-block:: python3 @bot.check def global_check(ctx): # Allows only party", "command_prefix The command prefix is what the message content must", "loaded. ExtensionMissingEntryPoint The extension does not have a extension_setup function.", "cog name to cog. \"\"\" return types.MappingProxyType(self.__cogs) def _remove_module_references(self, name:", "ctx.command.dispatch_error(ctx, exc) else: self.dispatch_event('command_completion', ctx) elif ctx.invoked_with: exc = CommandNotFound('Command", "extension is already loaded. ExtensionMissingEntryPoint The extension does not have", "and is equivalent to a call to :meth:`~.Bot.get_context` followed by", "optional global function, ``cog_teardown``, to do miscellaneous clean-up if necessary.", "extension was not loaded. ExtensionNotFound The extension could not be", "self._check_once.append(func) else: self._checks.append(func) def remove_check(self, func: MaybeCoro, *, call_once: bool", "MaybeCoro: r\"\"\"A decorator that registers a coroutine as a post-invoke", "return False return True async def is_owner(self, user_id: str) ->", "and argument parsing procedures succeed. This hook is, however, **always**", "ValueError('Iterable command_prefix must contain at ' 'least one prefix') return", "execution error. \"\"\" lib = self.__extensions.get(name) if lib is None:", "extension was not loaded. \"\"\" lib = self.__extensions.get(name) if lib", "prefixes be careful to not pass a prefix that matches", "actually a coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The post-invoke", "futures = self.dispatch_event('command_error', ctx, error) asyncio.ensure_future(self._wait_for_error_return( futures, ctx, error ))", "The user id to check for. Returns ------- :class:`bool` Whether", "bot. This class also subclasses :class:`.GroupMixin` to provide the functionality", "import traceback from typing import Any, List, Optional, Mapping, Set", "raise ExtensionNotFound(name) self._load_from_module_spec(spec, name) def unload_extension(self, name: str) -> None:", "= self.__extensions.get(name) if lib is None: raise ExtensionNotLoaded(name) # get", "for. \"\"\" # noqa if message.author.id == self.user.id: return ctx", "in sys.modules.items() if _is_submodule(lib.__name__, name) } try: # Unload and", "invoke. \"\"\" if ctx.command is not None: self.dispatch_event('command', ctx) try:", "if cog is None: return help_command = self.help_command if help_command", "``extension_setup`` defined as the entry point on what to do", "recommended to use a :class:`set` for the collection. You cannot", "message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to process commands for. \"\"\"", "self.owner_id and self.owner_ids: raise TypeError('Both owner_id and owner_ids are set.')", "view.skip_string(element): invoked_prefix = element break else: invoked_prefix = None else:", "The factory class that will be used to create the", "as no prefix after it will be matched. case_insensitive: :class:`bool`", "return func async def can_run(self, ctx: Context, *, call_once: bool", "references to the module # remove the cogs registered from", "pass else: try: func(self) except Exception: pass finally: self.__extensions.pop(key, None)", "the bot is listening for. \"\"\" # noqa prefix =", "as e: del sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key) raise ExtensionFailed(key, e)", "str): try: ret = list(ret) except TypeError: # It's possible", "it a useful function to clean-up database connections or any", "to :meth:`.check` and :meth:`.check_once`. Parameters ---------- func The function that", "Message log = logging.getLogger(__name__) def _is_submodule(parent: str, child: str) ->", "not p.cancelled(): p.cancel() pending = futures while pending: done, pending", "message as a context. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The", "to do so, subject to the following conditions: The above", "the function was added with ``call_once=True`` in the :meth:`.Bot.add_check` call", "= self.dispatch_event('command_error', ctx, error) asyncio.ensure_future(self._wait_for_error_return( futures, ctx, error )) else:", "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "only called if all checks and argument parsing procedures pass", "async def close(self, *, close_http: bool = True, dispatch_close: bool", "Exception: # if the load failed, the remnants should have", "StringView from .context import Context from .help import HelpCommand, FortniteHelpCommand", "not view.skip_string(prefix): return ctx else: try: if message.content.startswith(tuple(prefix)): for element", "that have been registered to the bot and other groups.", "\"\"\" # noqa if message.author.id == self.user.id: return ctx =", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "or check(future): if cancel: _cancel_futs(pending) return future async def _wait_for_error_return(self,", "MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that adds a check globally", "extension could not be imported. ExtensionMissingEntryPoint The extension does not", "= CommandNotFound('Command \"{}\" is not found' ''.format(ctx.invoked_with)) self.dispatch_error(ctx, exc) async", "*, call_once: bool = False) -> None: \"\"\"Removes a global", "list(sys.modules.keys()): if _is_submodule(name, module): del sys.modules[module] def _load_from_module_spec(self, spec: types.ModuleType,", "importlib.util.module_from_spec(spec) sys.modules[key] = lib try: spec.loader.exec_module(lib) except Exception as e:", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "HelpCommand') if self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command = value", "----------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to process commands for.", "with this bot. This class also subclasses :class:`.GroupMixin` to provide", "if ctx.command is not None: self.dispatch_event('command', ctx) try: if await", "sys.modules.update(modules) raise @property def extensions(self) -> Mapping[str, types.ModuleType]: \"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]:", "the module for event_list in self._events.copy().values(): remove = [] for", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "revert sys.modules back to normal and raise back to caller", "for name, module in sys.modules.items() if _is_submodule(lib.__name__, name) } try:", "bool = False) -> None: \"\"\"Adds a global check to", "-------- Union[List[:class:`str`], :class:`str`] A list of prefixes or a single", "not isinstance(ret, str): try: ret = list(ret) except TypeError: #", "dot separated like regular Python imports if accessing a sub-module.", "object, key: str) -> None: try: func = getattr(lib, 'cog_teardown')", "message: Message) -> None: \"\"\"|coro| This function processes the commands", "be matched. case_insensitive: :class:`bool` Whether the commands should be case", "command. .. note:: This function can either be a regular", "is returned instead. Parameters ----------- name: :class:`str` The name of", "None: def _cancel_futs(pending_futures: Set[asyncio.Future]) -> None: for p in pending_futures:", "ctx: :class:`.Context` The invocation context to invoke. \"\"\" if ctx.command", "of strings indicating that multiple checks for the prefix should", "Whether the user is the owner. \"\"\" if self.owner_id: return", "None: return help_command = self.help_command if help_command and help_command.cog is", "the bot. Unlike regular global checks, this one is called", "' 'failed.') except CommandError as exc: await ctx.command.dispatch_error(ctx, exc) else:", "longer prefix occurring later in the sequence. For example, if", "have been # cleaned from the load_extension function call #", "copyright notice and this permission notice shall be included in", "cog def remove_cog(self, name: str) -> None: \"\"\"Removes a cog", "unload_extension(self, name: str) -> None: \"\"\"Unloads an extension. When the", "parameter, the ``bot``, similar to ``extension_setup`` from :meth:`~.Bot.load_extension`. Parameters ------------", "is not None: self.dispatch_event('command', ctx) try: if await self.can_run(ctx, call_once=True):", "This is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension`", "make sure it is. If the context is not valid", "name: :class:`str` The name of the cog to remove. \"\"\"", "name = lib.__name__ for module in list(sys.modules.keys()): if _is_submodule(name, module):", "= None cog._eject(self) def get_cog(self, name: str) -> Optional[Cog]: \"\"\"Gets", "coro def add_cog(self, cog: Cog) -> None: \"\"\"Adds a \"cog\"", "_load_from_module_spec(self, spec: types.ModuleType, key: str) -> None: # precondition: key", "of prefixes or a single prefix that the bot is", "the case. if isinstance(ret, collections.abc.Iterable): raise raise TypeError('command_prefix must be", "and to permit persons to whom the Software is furnished", "-> None: def check(future): return future.result() is False ret =", "user_id: :class:`str` The user id to check for. Returns -------", "= await self.wait_for_futures(futures, check=check) if isinstance(ret, asyncio.Future): self._print_error(ctx, error) def", "asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke", "as its first parameter and :class:`fortnitepy.FriendMessage` or :class:`fortnitepy.PartyMessage` as its", "= coro return coro def after_invoke(self, coro: MaybeCoro) -> MaybeCoro:", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "name: str) -> Optional[Cog]: \"\"\"Gets the cog instance requested. If", "prefix after it will be matched. case_insensitive: :class:`bool` Whether the", "must ' 'contain only strings, not ' '{}'.format(value.__class__.__name__)) raise invoker", "description: Optional[str] = None, **kwargs: Any) -> None: kwargs['case_insensitive'] =", "-> Mapping[str, Cog]: \"\"\"Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog", "help command implementation to use. This can be dynamically set", "that's the case. if isinstance(ret, collections.abc.Iterable): raise raise TypeError('command_prefix must", "self.description = inspect.cleandoc(description) if description else '' self.owner_id = kwargs.get('owner_id')", "whom the Software is furnished to do so, subject to", "from fortnitepy.client import Client from fortnitepy.auth import Auth from fortnitepy.typedefs", "log = logging.getLogger(__name__) def _is_submodule(parent: str, child: str) -> bool:", "type of set up required. This pre-invoke hook takes a", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "Defaults to ``False``. This attribute does not carry over to", "if obj.parent is None: try: self.add_command(obj) except CommandError: traceback.print_exc() continue", "sys.modules[key] raise ExtensionMissingEntryPoint(key) try: setup(self) except Exception as e: del", "in all copies or substantial portions of the Software. THE", "if not ret: raise ValueError('Iterable command_prefix must contain at '", "``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`. \"\"\" list_", "message) else: ret = prefix(self, message) if not isinstance(ret, str):", "e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises -------", "matches a longer prefix occurring later in the sequence. For", "to :meth:`~.Bot.before_invoke`\\, this is not called unless checks and argument", "check=check) if isinstance(ret, asyncio.Future): self._print_error(ctx, error) def dispatch_error(self, ctx: Context,", "if asyncio.iscoroutinefunction(func): res = await func(ctx) else: res = func(ctx)", "effect. Parameters ---------- name: :class:`str` The name of the cog", "get_cog(self, name: str) -> Optional[Cog]: \"\"\"Gets the cog instance requested.", "help command. .. note:: This function can either be a", "user id is the owner of the bot. Parameters ----------", "of this software and associated documentation files (the \"Software\"), to", "either a regular function or a coroutine. An empty string", "have a global function, ``extension_setup`` defined as the entry point", "if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a", "a coroutine.') self._before_invoke = coro return coro def after_invoke(self, coro:", "should have been # cleaned from the load_extension function call", "The message to process commands for. \"\"\" # noqa if", "-> MaybeCoro: r\"\"\"A decorator that adds a \"call once\" global", "_remove_module_references(self, name: str) -> None: # find all references to", "sublicense, and/or sell copies of the Software, and to permit", "be similar enough to :class:`.Context`\\'s interface. Returns ------- :class:`.Context` The", "USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import logging", "parsing procedures pass without error. If any check or argument", "derive from Cog.') cog = cog._inject(self) self.__cogs[cog.__cog_name__] = cog def", "None or check(future): if cancel: _cancel_futs(pending) return future async def", ":class:`.Context`. .. note:: The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are only", "pending = await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout ) # Set", "``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was not loaded. \"\"\"", "regular Python imports if accessing a sub-module. e.g. ``foo.test`` if", "owner_id and owner_ids are set.') if (self.owner_ids and not isinstance(self.owner_ids,", "invoke(self, ctx: Context) -> None: \"\"\"|coro| Invokes the command given", "if self.owner_id and self.owner_ids: raise TypeError('Both owner_id and owner_ids are", "for index in reversed(remove): del event_list[index] def _call_module_finalizers(self, lib: object,", "The coroutine to register as the post-invoke hook. Raises ------", "async def process_commands(self, message: Message) -> None: \"\"\"|coro| This function", "function to clean-up database connections or any type of clean", "cog: help_command.cog = None cog._eject(self) def get_cog(self, name: str) ->", "This is to facilitate \"dynamic\" command prefixes. This callable can", "in tuple(self.__cogs): try: self.remove_cog(cog) except Exception: pass await self._close( close_http=close_http,", "to indicate what the prefix should be, or a callable", "this permission notice shall be included in all copies or", "to load. It must be dot separated like regular Python", "ret async def get_context(self, message: Message, *, cls: Context =", "from fortnitepy.auth import Auth from fortnitepy.typedefs import MaybeCoro, ListOrTuple from", "the functionality to manage commands. Attributes ----------- command_prefix The command", "*, call_once: bool = False) -> bool: data = self._check_once", "is cog: help_command.cog = None cog._eject(self) def get_cog(self, name: str)", "to :class:`.Context`\\'s interface. Returns ------- :class:`.Context` The invocation context. The", "to allow users more fine grained control over the processing.", "try: list_.remove(func) except ValueError: pass def check_once(self, func: MaybeCoro) ->", "function, ``extension_setup`` defined as the entry point on what to", "guaranteed to be a valid invocation context, :attr:`.Context.valid` must be", "for p in pending_futures: if not p.cancelled(): p.cancel() pending =", "check(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that adds a", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "be case insensitive as well. description: :class:`str` The content prefixed", "in self.owner_ids def before_invoke(self, coro: MaybeCoro) -> MaybeCoro: \"\"\"A decorator", "to a :meth:`unload_extension` followed by a :meth:`load_extension` except done in", "bot as its first parameter and :class:`fortnitepy.FriendMessage` or :class:`fortnitepy.PartyMessage` as", "func The function that was used as a global check.", "the bot is listening to with the message as a", "\"cog\" to the bot. A cog is a class that", "was added with ``call_once=True`` in the :meth:`.Bot.add_check` call or using", "global checks, this one is called only once per :meth:`Command.invoke`", "self._check_once if call_once else self._checks if len(data) == 0: return", "does not have a extension_setup function. ExtensionFailed The extension or", "await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) else: raise CheckFailure('The global check", "ctx.command = self.all_commands.get(invoker) return ctx def _print_error(self, ctx: Context, error:", "pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout ) # Set should only contain one", "None: # find all references to the module # remove", "this method has no effect. Parameters ---------- name: :class:`str` The", "CommandNotFound('Command \"{}\" is not found' ''.format(ctx.invoked_with)) self.dispatch_error(ctx, exc) async def", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING", "KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "TypeError('command_prefix must be plain string, ' 'iterable of strings, or", "to `owner_id`. For performance reasons it is recommended to use", "confusion empty iterables are not allowed. .. note:: When passing", "**kwargs) self.command_prefix = command_prefix self.description = inspect.cleandoc(description) if description else", "if value is not None: if not isinstance(value, HelpCommand): raise", "-> None: if self._event_has_handler('command_error'): futures = self.dispatch_event('command_error', ctx, error) asyncio.ensure_future(self._wait_for_error_return(", "prefix that matches a longer prefix occurring later in the", "if help_command is _default: self.help_command = FortniteHelpCommand() else: self.help_command =", "method has no effect. Parameters ---------- name: :class:`str` The name", "that has its own event listeners and commands. Parameters ----------", "as the entry point on what to do when the", "list of string, not ' '{}'.format(prefix.__class__.__name__)) for value in prefix:", "from .cog import Cog from .view import StringView from .context", "every group if you require group commands to be case", "as a result anything that you can do with a", "or child.startswith(parent + \".\") class _DefaultRepr: def __repr__(self) -> str:", "all the commands from the module for cmd in self.all_commands.copy().values():", "shall be included in all copies or substantial portions of", "The name of the cog to remove. \"\"\" cog =", "str) -> bool: return parent == child or child.startswith(parent +", "a global function, ``extension_setup`` defined as the entry point on", "setup function had an execution error. \"\"\" lib = self.__extensions.get(name)", "one prefix') return ret async def get_context(self, message: Message, *,", "FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "context is not guaranteed to be a valid invocation context,", "of the cog you are requesting. This is equivalent to", "def _is_submodule(parent: str, child: str) -> bool: return parent ==", "listeners that the cog has registered will be removed as", "reversed(remove): del event_list[index] def _call_module_finalizers(self, lib: object, key: str) ->", "a class that has its own event listeners and commands.", "and the first one to match will be the invocation", "This class also subclasses :class:`.GroupMixin` to provide the functionality to", "to the bot. This is the non-decorator interface to :meth:`.check`", "You can get this prefix via :attr:`.Context.prefix`. To avoid confusion", "the cog instance requested. If the cog is not found,", "process_commands(self, message: Message) -> None: \"\"\"|coro| This function processes the", "else: self.__extensions[key] = lib def load_extension(self, name: str) -> None:", "ret: raise ValueError('Iterable command_prefix must contain at ' 'least one", "= _default, description: Optional[str] = None, **kwargs: Any) -> None:", "str) -> None: \"\"\"Atomically reloads an extension. This replaces the", "CheckFailure('The global check once functions ' 'failed.') except CommandError as", "code-block:: python3 @bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist \"\"\"", "IDs that owns the bot. This is similar to `owner_id`.", ".errors import (ExtensionFailed, ExtensionMissingEntryPoint, ExtensionNotLoaded, ExtensionAlreadyLoaded, ExtensionNotFound, CheckFailure, CommandError, CommandNotFound)", "description: :class:`str` The content prefixed into the default help message.", "def whitelist(ctx): return ctx.message.author.id in my_whitelist \"\"\" self.add_check(func, call_once=True) return", "coroutine as a pre-invoke hook. A pre-invoke hook is called", ":meth:`~.Bot.after_invoke` hooks are only called if all checks and argument", "this is not called unless checks and argument parsing procedures", "is the owner. \"\"\" if self.owner_id: return user_id == self.owner_id", "commands, listeners, and cogs are removed from the bot and", "} try: # Unload and then load the module... self._remove_module_references(lib.__name__)", "' 'returned from get_prefix must ' 'contain only strings, not", "Set[asyncio.Future]) -> None: for p in pending_futures: if not p.cancelled():", "kwargs['case_insensitive'] = kwargs.get('case_insensitive', False) super().__init__(auth, **kwargs) self.command_prefix = command_prefix self.description", "default, this is :class:`.Context`. Should a custom class be provided,", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", "-> None: def _cancel_futs(pending_futures: Set[asyncio.Future]) -> None: for p in", "bot and other groups. Without this coroutine, none of the", "None: \"\"\"|coro| This function processes the commands that have been", "set()) if self.owner_id and self.owner_ids: raise TypeError('Both owner_id and owner_ids", "the previous one matches messages starting with ``!?``. This is", "check or argument parsing procedures fail then the hooks are", "called whenever a command is called or :meth:`.Command.can_run` is called.", "the Software is furnished to do so, subject to the", "found then this method has no effect. Parameters ---------- name:", "function had an execution error. \"\"\" lib = self.__extensions.get(name) if", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "ExtensionNotFound, CheckFailure, CommandError, CommandNotFound) from .core import GroupMixin from .cog", "one matches messages starting with ``!?``. This is especially important", "sys.modules.pop(key, None) name = lib.__name__ for module in list(sys.modules.keys()): if", "sys.modules.items() if _is_submodule(lib.__name__, name) } try: # Unload and then", "is_owner(self, user_id: str) -> bool: \"\"\"|coro| Checks if a user", "'{0.__class__!r}'.format(self.owner_ids) ) self.__cogs = {} self.__extensions = {} self._checks =", ":class:`bool` If the function should only be called once per", "True async def is_owner(self, user_id: str) -> bool: \"\"\"|coro| Checks", "attribute does not carry over to groups. You must set", "get_context(self, message: Message, *, cls: Context = Context) -> Context:", "None: print( 'Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr ) traceback.print_exception(", "is False ret = await self.wait_for_futures(futures, check=check) if isinstance(ret, asyncio.Future):", "self._check_once = [] self._help_command = None self._before_invoke = None self._after_invoke", "raise back to caller sys.modules.update(modules) raise @property def extensions(self) ->", "noqa if message.author.id == self.user.id: return ctx = await self.get_context(message)", "hook must be a coroutine.') self._before_invoke = coro return coro", "the bot and other groups. Without this coroutine, none of", "Parameters ---------- cog: :class:`.Cog` The cog to register to the", "= lib.__name__ for module in list(sys.modules.keys()): if _is_submodule(name, module): del", "in self.all_commands.copy().values(): if cmd.module is not None and _is_submodule(name, cmd.module):", "extensions(self) -> Mapping[str, types.ModuleType]: \"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of", "get the previous module states from sys modules modules =", "and commands. Parameters ---------- cog: :class:`.Cog` The cog to register", "Invokes the command given under the invocation context and handles", "connections or any type of set up required. This pre-invoke", "The coroutine passed is not actually a coroutine. \"\"\" if", "= futures while pending: done, pending = await asyncio.wait( pending,", "dispatch_close=dispatch_close ) def check(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator", "await prefix(self, message) else: ret = prefix(self, message) if not", "cog: :class:`.Cog` The cog to register to the bot. Raises", "set up required. This pre-invoke hook takes a sole parameter,", "sole parameter, a :class:`.Context`. .. note:: Similar to :meth:`~.Bot.before_invoke`\\, this", "def __repr__(self) -> str: return '<default-help-command>' _default = _DefaultRepr() class", "the help command pass ``None``. For more information on implementing", "is not None: if not isinstance(value, HelpCommand): raise TypeError('help_command must", "bot. Unlike regular global checks, this one is called only", ":exc:`.CommandInvokeError`\\). This makes it ideal for clean-up scenarios. Parameters ----------", "if the command prefix is ``('!', '!?')`` the ``'!?'`` prefix", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "super().register_methods() async def close(self, *, close_http: bool = True, dispatch_close:", "= self._check_once if call_once else self._checks if len(data) == 0:", "check. call_once: :class:`bool` If the function should only be called", "self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command = value value._add_to_bot(self) elif", "global check from the bot. Parameters ---------- func The function", "# so let's load it from our old compiled library.", "name of the cog to remove. \"\"\" cog = self.__cogs.pop(name,", "during loading. \"\"\" if not isinstance(cog, Cog): raise TypeError('Cogs must", "once\" global check to the bot. Unlike regular global checks,", "= invoked_prefix ctx.command = self.all_commands.get(invoker) return ctx def _print_error(self, ctx:", "groups. Without this coroutine, none of the commands will be", "The extension setup function had an execution error. \"\"\" lib", "def _cancel_futs(pending_futures: Set[asyncio.Future]) -> None: for p in pending_futures: if", "FortniteHelpCommand from .typedefs import Message log = logging.getLogger(__name__) def _is_submodule(parent:", "{} self._checks = [] self._check_once = [] self._help_command = None", "ExtensionAlreadyLoaded The extension is already loaded. ExtensionMissingEntryPoint The extension does", "An empty string as the prefix always matches, enabling prefix-less", "THE SOFTWARE. \"\"\" import logging import inspect import asyncio import", "must return either a string ' 'or a list of", "continue super().register_methods() async def close(self, *, close_http: bool = True,", "----------- name: :class:`str` The name of the cog you are", "SOFTWARE. \"\"\" import logging import inspect import asyncio import types", "None and _is_submodule(name, event.__module__)): remove.append(index) for index in reversed(remove): del", "Permission is hereby granted, free of charge, to any person", "if isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name) # remove all the listeners", "else: self._print_error(ctx, error) async def invoke(self, ctx: Context) -> None:", "argument parsing procedures succeed. This hook is, however, **always** called", "already loaded. ExtensionMissingEntryPoint The extension does not have a extension_setup", "\"\"\"Loads an extension. An extension is a python module that", "new message is received. This is built using other low", "if help_command and help_command.cog is cog: help_command.cog = None cog._eject(self)", "ExtensionMissingEntryPoint(key) try: setup(self) except Exception as e: del sys.modules[key] self._remove_module_references(lib.__name__)", "False ret = await self.wait_for_futures(futures, check=check) if isinstance(ret, asyncio.Future): self._print_error(ctx,", "None: raise ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) def reload_extension(self, name: str)", "def wait_for_futures(self, futures: ListOrTuple, *, check: Optional[callable] = None, timeout:", "\"\"\" lib = self.__extensions.get(name) if lib is None: raise ExtensionNotLoaded(name)", "extension must have a global function, ``extension_setup`` defined as the", "call_once: bool = False) -> bool: data = self._check_once if", "given under the invocation context and handles all the internal", "import Context from .help import HelpCommand, FortniteHelpCommand from .typedefs import", "All registered commands and event listeners that the cog has", "Unlike regular global checks, this one is called only once", "add_check(self, func: MaybeCoro, *, call_once: bool = False) -> None:", "name of the cog you are requesting. This is equivalent", "default help command. .. note:: This function can either be", "The extension does not have a extension_setup function. ExtensionFailed The", "do when the extension is loaded. This entry point must", "an extension. When the extension is unloaded, all commands, listeners,", "call_once: :class:`bool` If the function should only be called once", "the prefix should be, or a callable that takes in", "removed as well. If no cog is found then this", "inherit from :class:`.Cog`. CommandError An error happened during loading. \"\"\"", "p.cancel() pending = futures while pending: done, pending = await", "called automatically when a new message is received. This is", "is built using other low level tools, and is equivalent", "a longer prefix occurring later in the sequence. For example,", "ret = self.command_prefix if callable(prefix): if asyncio.iscoroutinefunction(prefix): ret = await", "del sys.modules[key] self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, key) raise ExtensionFailed(key, e) from e", "Context: r\"\"\"|coro| Returns the invocation context from the message. This", "or any type of set up required. This pre-invoke hook", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "point on what to do when the extension is loaded.", "generator raised this exception. Don't # replace it with our", "failed, the remnants should have been # cleaned from the", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "def _call_module_finalizers(self, lib: object, key: str) -> None: try: func", "cogname, cog in self.__cogs.copy().items(): if _is_submodule(name, cog.__module__): self.remove_cog(cogname) # remove", "be used to create the context. By default, this is", "return ctx except TypeError: if not isinstance(prefix, list): raise TypeError('get_prefix", "message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message to get the invocation context", "a extension_setup function. ExtensionFailed The extension or its setup function", "will be the invocation prefix. You can get this prefix", "is not guaranteed to be a valid invocation context, :attr:`.Context.valid`", "def remove_check(self, func: MaybeCoro, *, call_once: bool = False) ->", "self._help_command @help_command.setter def help_command(self, value: Optional[HelpCommand]) -> None: if value", "invoker ctx.prefix = invoked_prefix ctx.command = self.all_commands.get(invoker) return ctx def", "raised this exception. Don't # replace it with our own", "the class name if unspecified. \"\"\" return self.__cogs.get(name) @property def", "callable(prefix): if asyncio.iscoroutinefunction(prefix): ret = await prefix(self, message) else: ret", "is not valid then it is not a valid candidate", "be invoked under :meth:`~.Bot.invoke`. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The", "also subclasses :class:`.GroupMixin` to provide the functionality to manage commands.", "isinstance(cog, Cog): raise TypeError('Cogs must derive from Cog.') cog =", "prior working state. Parameters ------------ name: :class:`str` The extension name", "= cog def remove_cog(self, name: str) -> None: \"\"\"Removes a", "a list of string, not ' '{}'.format(prefix.__class__.__name__)) for value in", "the bot. Parameters ---------- user_id: :class:`str` The user id to", "context to get the prefix of. Returns -------- Union[List[:class:`str`], :class:`str`]", "ListOrTuple, *, check: Optional[callable] = None, timeout: Optional[int] = None,", "try: if await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) else: raise CheckFailure('The", "import StringView from .context import Context from .help import HelpCommand,", "does not carry over to groups. You must set it", "is equivalent to a call to :meth:`~.Bot.get_context` followed by a", "None: self.dispatch_event('command', ctx) try: if await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx)", "\"\"\" self.add_check(func) return func def add_check(self, func: MaybeCoro, *, call_once:", "\"\"\"Adds a global check to the bot. This is the", "want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension was", "be a coroutine.') self._after_invoke = coro return coro def add_cog(self,", ":meth:`.process_commands` to allow users more fine grained control over the", "r\"\"\"A decorator that adds a check globally to every command.", "back to caller sys.modules.update(modules) raise @property def extensions(self) -> Mapping[str,", "cmd in self.all_commands.copy().values(): if cmd.module is not None and _is_submodule(name,", "the command is called. This makes it a useful function", "and :meth:`.check_once`. Parameters ---------- func The function that was used", "error.__traceback__, file=sys.stderr ) async def wait_for_futures(self, futures: ListOrTuple, *, check:", "grained control over the processing. The returned context is not", "could either be a string to indicate what the prefix", "the cog is not found, ``None`` is returned instead. Parameters", "MaybeCoro, ListOrTuple from ._types import _BaseCommand from .errors import (ExtensionFailed,", ":class:`str` The user id to check for. Returns ------- :class:`bool`", "collections.abc.Collection)): raise TypeError( 'owner_ids must be a collection not '", "data: if asyncio.iscoroutinefunction(func): res = await func(ctx) else: res =", "argument parsing procedures pass without error. If any check or", "Software without restriction, including without limitation the rights to use,", "and the module is un-imported. The extension can provide an", "automatically when a new message is received. This is built", "name: str) -> None: \"\"\"Removes a cog from the bot.", "cog to remove. \"\"\" cog = self.__cogs.pop(name, None) if cog", "to get the invocation context from. cls The factory class", ":meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension name to unload.", "True, dispatch_close: bool = True) -> None: if dispatch_close: await", "the same extension, only refreshed. This is equivalent to a", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "hereby granted, free of charge, to any person obtaining a", "is equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` except", "key not in self.__extensions lib = importlib.util.module_from_spec(spec) sys.modules[key] = lib", "parameter and returns the prefix. This is to facilitate \"dynamic\"", "lib is None: raise ExtensionNotLoaded(name) self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) def reload_extension(self,", "Union[List[:class:`str`], :class:`str`] A list of prefixes or a single prefix", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "call_once: self._check_once.append(func) else: self._checks.append(func) def remove_check(self, func: MaybeCoro, *, call_once:", "types.MappingProxyType(self.__extensions) @property def help_command(self) -> Optional[HelpCommand]: return self._help_command @help_command.setter def", "CommandError An error happened during loading. \"\"\" if not isinstance(cog,", "class name if unspecified. \"\"\" return self.__cogs.get(name) @property def cogs(self)", "not isinstance(prefix, list): raise TypeError('get_prefix must return either a string", "isinstance(value, HelpCommand): raise TypeError('help_command must be a subclass ' 'of", ":attr:`.Context.prefix`. To avoid confusion empty iterables are not allowed. ..", "futures, ctx, error )) else: self._print_error(ctx, error) async def invoke(self,", "internal event dispatch mechanisms. Parameters ----------- ctx: :class:`.Context` The invocation", "is a python module that contains commands, cogs, or listeners.", "register as the post-invoke hook. Raises ------ TypeError The coroutine", "prefix(self, message) if not isinstance(ret, str): try: ret = list(ret)", "cog is None: return help_command = self.help_command if help_command and", "to match will be the invocation prefix. You can get", "its first parameter and :class:`fortnitepy.FriendMessage` or :class:`fortnitepy.PartyMessage` as its second", "provide an optional global function, ``cog_teardown``, to do miscellaneous clean-up", "prefix could either be a string to indicate what the", "Mapping[str, types.ModuleType]: \"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension name", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "it must be similar enough to :class:`.Context`\\'s interface. Returns -------", "as a global check. call_once: :class:`bool` If the function should", "self._help_command = None else: self._help_command = None async def get_prefix(self,", "without error. If any check or argument parsing procedures fail", "an execution error. \"\"\" if name in self.__extensions: raise ExtensionAlreadyLoaded(name)", "fortnitepy.auth import Auth from fortnitepy.typedefs import MaybeCoro, ListOrTuple from ._types", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "in list(sys.modules.keys()): if _is_submodule(name, module): del sys.modules[module] def _load_from_module_spec(self, spec:", "has its own event listeners and commands. Parameters ---------- cog:", "def global_check(ctx): # Allows only party commands. return ctx.party is", "elif ctx.invoked_with: exc = CommandNotFound('Command \"{}\" is not found' ''.format(ctx.invoked_with))", "prefix should be, or a callable that takes in the", "'{}'.format(value.__class__.__name__)) raise invoker = view.get_word() ctx.invoked_with = invoker ctx.prefix =", "use a :class:`set` for the collection. You cannot set both", "\"\"\"Unloads an extension. When the extension is unloaded, all commands,", "---------- func The function to remove from the global checks.", "def is_owner(self, user_id: str) -> bool: \"\"\"|coro| Checks if a", "else: invoked_prefix = None else: return ctx except TypeError: if", "@property def help_command(self) -> Optional[HelpCommand]: return self._help_command @help_command.setter def help_command(self,", "to unload. It must be dot separated like regular Python", "defined as the entry point on what to do when", "no effect. Parameters ---------- name: :class:`str` The name of the", "if not isinstance(value, HelpCommand): raise TypeError('help_command must be a subclass", "function or a coroutine. This function takes a single parameter,", "self._call_module_finalizers(lib, name) def reload_extension(self, name: str) -> None: \"\"\"Atomically reloads", "similar to ``extension_setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The", "List[asyncio.Future], ctx: Context, error: Exception) -> None: def check(future): return", "before_invoke(self, coro: MaybeCoro) -> MaybeCoro: \"\"\"A decorator that registers a", ":exc:`.CommandError`. Example ------- .. code-block:: python3 @bot.check def global_check(ctx): #", "_cancel_futs(pending_futures: Set[asyncio.Future]) -> None: for p in pending_futures: if not", "database connections or any type of set up required. This", "Software is furnished to do so, subject to the following", "This prefix could either be a string to indicate what", "listeners, and cogs are removed from the bot and the", "Cog): raise TypeError('Cogs must derive from Cog.') cog = cog._inject(self)", "using :meth:`.check_once`. \"\"\" list_ = self._check_once if call_once else self._checks", "over to groups. You must set it to every group", "the extension is unloaded, all commands, listeners, and cogs are", "if isinstance(obj, _BaseCommand): obj.instance = self if obj.parent is None:", "By default, this coroutine is called automatically when a new", "a extension_setup function. ExtensionFailed The extension setup function had an", "case insensitive as well. description: :class:`str` The content prefixed into", "a global check. call_once: :class:`bool` If the function should only", "included in all copies or substantial portions of the Software.", "await asyncio.gather( self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'), ) for extension in tuple(self.__extensions): try:", "= lib # revert sys.modules back to normal and raise", "value._add_to_bot(self) elif self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command = None", "name to extension. \"\"\" return types.MappingProxyType(self.__extensions) @property def help_command(self) ->", "This is a more low-level counter-part for :meth:`.process_commands` to allow", "Set should only contain one value for future in done:", "pending_futures: if not p.cancelled(): p.cancel() pending = futures while pending:", "value for future in done: if check is None or", "owns the bot. This is used by :meth:`.is_owner()` and checks", "must be a collection not ' '{0.__class__!r}'.format(self.owner_ids) ) self.__cogs =", "a single argument, the ``bot``. Parameters ---------- name: :class:`str` The", "to the name passed via keyword argument in class creation", "ctx.command is not None: self.dispatch_event('command', ctx) try: if await self.can_run(ctx,", "class that has its own event listeners and commands. Parameters", "as e: del sys.modules[key] raise ExtensionFailed(key, e) from e try:", "procedures succeed. This hook is, however, **always** called regardless of", "import Client from fortnitepy.auth import Auth from fortnitepy.typedefs import MaybeCoro,", "manage commands. Attributes ----------- command_prefix The command prefix is what", "possible that a generator raised this exception. Don't # replace", "This function can either be a regular function or a", "cogs(self) -> Mapping[str, Cog]: \"\"\"Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of", "_is_submodule(name, module): del sys.modules[module] def _load_from_module_spec(self, spec: types.ModuleType, key: str)", "context is not valid then it is not a valid", "avoid confusion empty iterables are not allowed. .. note:: When", "id is the owner of the bot. Parameters ---------- user_id:", "isinstance(ret, asyncio.Future): self._print_error(ctx, error) def dispatch_error(self, ctx: Context, error: Exception)", "try: self.remove_cog(cog) except Exception: pass await self._close( close_http=close_http, dispatch_close=dispatch_close )", "scenarios. Parameters ---------- coro: The coroutine to register as the", "performance reasons it is recommended to use a :class:`set` for", "that a generator raised this exception. Don't # replace it", "actually a coroutine. \"\"\" if not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke", "event in enumerate(event_list): if (event.__module__ is not None and _is_submodule(name,", "in the sequence. For example, if the command prefix is", "is None: raise ExtensionNotFound(name) self._load_from_module_spec(spec, name) def unload_extension(self, name: str)", "be checked to make sure it is. If the context", "'of HelpCommand') if self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command =", "ExtensionMissingEntryPoint, ExtensionNotLoaded, ExtensionAlreadyLoaded, ExtensionNotFound, CheckFailure, CommandError, CommandNotFound) from .core import", "raising an error (i.e. :exc:`.CommandInvokeError`\\). This makes it ideal for", "takes a sole parameter, a :class:`.Context`. .. note:: Similar to", "e else: self.__extensions[key] = lib def load_extension(self, name: str) ->", "self.__extensions[key] = lib def load_extension(self, name: str) -> None: \"\"\"Loads", ".. note:: This function can either be a regular function", "is the non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ----------", "str) -> None: \"\"\"Removes a cog from the bot. All", "if isinstance(ret, asyncio.Future): self._print_error(ctx, error) def dispatch_error(self, ctx: Context, error:", "be a string to indicate what the prefix should be,", ".core import GroupMixin from .cog import Cog from .view import", "with ``call_once=True`` in the :meth:`.Bot.add_check` call or using :meth:`.check_once`. \"\"\"", "---------- coro The coroutine to register as the pre-invoke hook.", "to register to the bot. Raises ------ TypeError The cog", "lib = self.__extensions.get(name) if lib is None: raise ExtensionNotLoaded(name) #", "and other groups. Without this coroutine, none of the commands", "ExtensionNotLoaded, ExtensionAlreadyLoaded, ExtensionNotFound, CheckFailure, CommandError, CommandNotFound) from .core import GroupMixin", "parsing procedures fail then the hooks are not called. Parameters", "inherited from :exc:`.CommandError`. Example ------- .. code-block:: python3 @bot.check_once def", "or list ' 'returned from get_prefix must ' 'contain only", "help_command is _default: self.help_command = FortniteHelpCommand() else: self.help_command = help_command", "interface to :meth:`.check` and :meth:`.check_once`. Parameters ---------- func The function", "to register as the post-invoke hook. Raises ------ TypeError The", "await self._close( close_http=close_http, dispatch_close=dispatch_close ) def check(self, func: MaybeCoro) ->", "interface. Returns ------- :class:`.Context` The invocation context. The type of", "\"\"\" if call_once: self._check_once.append(func) else: self._checks.append(func) def remove_check(self, func: MaybeCoro,", "def unload_extension(self, name: str) -> None: \"\"\"Unloads an extension. When", "the bot. All registered commands and event listeners that the", "the ``'!?'`` prefix will never be matched to any message", "not found, ``None`` is returned instead. Parameters ----------- name: :class:`str`", "for cmd in self.all_commands.copy().values(): if cmd.module is not None and", "the first one to match will be the invocation prefix.", "function, ``cog_teardown``, to do miscellaneous clean-up if necessary. This function", "' '{}'.format(value.__class__.__name__)) raise invoker = view.get_word() ctx.invoked_with = invoker ctx.prefix", "extension_setup function. ExtensionFailed The extension setup function had an execution", "asyncio.ensure_future(self._wait_for_error_return( futures, ctx, error )) else: self._print_error(ctx, error) async def", "point must have a single argument, the ``bot``. Parameters ----------", "Returns -------- Union[List[:class:`str`], :class:`str`] A list of prefixes or a", "This pre-invoke hook takes a sole parameter, a :class:`.Context`. ..", "not ' '{}'.format(ret.__class__.__name__)) if not ret: raise ValueError('Iterable command_prefix must", "CommandError, CommandNotFound) from .core import GroupMixin from .cog import Cog", "import (ExtensionFailed, ExtensionMissingEntryPoint, ExtensionNotLoaded, ExtensionAlreadyLoaded, ExtensionNotFound, CheckFailure, CommandError, CommandNotFound) from", "set.') if (self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection)): raise TypeError( 'owner_ids", "\"\"\"|coro| Invokes the command given under the invocation context and", "= kwargs.get('owner_id') self.owner_ids = kwargs.get('owner_ids', set()) if self.owner_id and self.owner_ids:", "The extension could not be imported. ExtensionAlreadyLoaded The extension is", "Exception as e: del sys.modules[key] raise ExtensionFailed(key, e) from e", "required. This post-invoke hook takes a sole parameter, a :class:`.Context`.", ":class:`str` The extension name to unload. It must be dot", "command_prefix: Any, auth: Auth, *, help_command: Optional[HelpCommand] = _default, description:", "user id to check for. Returns ------- :class:`bool` Whether the", "' 'iterable of strings, or callable ' 'returning either of", ".. code-block:: python3 @bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist", "is not None and _is_submodule(name, event.__module__)): remove.append(index) for index in", "= [] self._help_command = None self._before_invoke = None self._after_invoke =", "return True for func in data: if asyncio.iscoroutinefunction(func): res =", "be either a regular function or a coroutine. An empty", "cls The factory class that will be used to create", "compiled library. lib.extension_setup(self) self.__extensions[name] = lib # revert sys.modules back", ":class:`.Context`\\'s interface. Returns ------- :class:`.Context` The invocation context. The type", "self.dispatch_event('command', ctx) try: if await self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) else:", ":class:`str` The content prefixed into the default help message. help_command:", "except CommandError: traceback.print_exc() continue super().register_methods() async def close(self, *, close_http:", "returns the prefix. This is to facilitate \"dynamic\" command prefixes.", "inside the default help command. .. note:: This function can", "`owner_id`. For performance reasons it is recommended to use a", "unload. It must be dot separated like regular Python imports", "(c) 2015-present Rapptz Permission is hereby granted, free of charge,", "takes a sole parameter, a :class:`.Context`. .. note:: The :meth:`~.Bot.before_invoke`", "for. Returns ------- :class:`bool` Whether the user is the owner.", "notice and this permission notice shall be included in all", "function or a coroutine. An empty string as the prefix", "the invocation context from the message. This is a more", "-> None: \"\"\"Removes a global check from the bot. Parameters", "import GroupMixin from .cog import Cog from .view import StringView", "= cog._inject(self) self.__cogs[cog.__cog_name__] = cog def remove_cog(self, name: str) ->", "a collection not ' '{0.__class__!r}'.format(self.owner_ids) ) self.__cogs = {} self.__extensions", "remove the help command pass ``None``. For more information on", "help_command.cog is cog: help_command.cog = None cog._eject(self) def get_cog(self, name:", "call or using :meth:`.check_once`. \"\"\" list_ = self._check_once if call_once", "message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message context to get the prefix", "was not loaded. \"\"\" lib = self.__extensions.get(name) if lib is", "should be used and the first one to match will", "error (i.e. :exc:`.CommandInvokeError`\\). This makes it ideal for clean-up scenarios.", "prefix = ret = self.command_prefix if callable(prefix): if asyncio.iscoroutinefunction(prefix): ret", "command pass ``None``. For more information on implementing a help", "the owner. \"\"\" if self.owner_id: return user_id == self.owner_id else:", "in data: if asyncio.iscoroutinefunction(func): res = await func(ctx) else: res", "unloaded, all commands, listeners, and cogs are removed from the", "-> Context: r\"\"\"|coro| Returns the invocation context from the message.", "command, see :ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`] The user ID that owns", "could not be imported. ExtensionMissingEntryPoint The extension does not have", "ret = await self.wait_for_futures(futures, check=check) if isinstance(ret, asyncio.Future): self._print_error(ctx, error)", "key: str) -> None: # precondition: key not in self.__extensions", "is especially important when passing an empty string, it should", ":meth:`load_extension` except done in an atomic way. That is, if", "if cancel: _cancel_futs(pending) return future async def _wait_for_error_return(self, futures: List[asyncio.Future],", "The content prefixed into the default help message. help_command: Optional[:class:`.HelpCommand`]", "return types.MappingProxyType(self.__extensions) @property def help_command(self) -> Optional[HelpCommand]: return self._help_command @help_command.setter", "The invocation context. The type of this can change via", "sequence. For example, if the command prefix is ``('!', '!?')``", "self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command = None else: self._help_command", "Any: \"\"\"|coro| Retrieves the prefix the bot is listening to", "res = await func(ctx) else: res = func(ctx) if not", "and/or sell copies of the Software, and to permit persons", "a call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`.", "command invocation. The command prefix could also be an iterable", "the bot as its first parameter and :class:`fortnitepy.FriendMessage` or :class:`fortnitepy.PartyMessage`", "else: self.help_command = help_command self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message', self.process_commands) def register_methods(self)", "'cog_teardown') except AttributeError: pass else: try: func(self) except Exception: pass", "strings indicating that multiple checks for the prefix should be", "prefix that the bot is listening for. \"\"\" # noqa", "of string, not ' '{}'.format(prefix.__class__.__name__)) for value in prefix: if", "The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are only called if all", "cog = self.__cogs.pop(name, None) if cog is None: return help_command", "received. This is built using other low level tools, and", "class that will be used to create the context. By", "anything that you can do with a :class:`fortnitepy.Client` you can", "def register_methods(self) -> None: for _, obj in inspect.getmembers(self): if", "# remove the cogs registered from the module for cogname,", "(self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection)): raise TypeError( 'owner_ids must be", "not pass a prefix that matches a longer prefix occurring", "extension, only refreshed. This is equivalent to a :meth:`unload_extension` followed", "all the internal event dispatch mechanisms. Parameters ----------- ctx: :class:`.Context`", "commands will be triggered. By default, this coroutine is called", "copy of this software and associated documentation files (the \"Software\"),", "provide the functionality to manage commands. Attributes ----------- command_prefix The", "This makes it a useful function to set up database", "call_once: bool = False) -> None: \"\"\"Adds a global check", "that and ensures that it's called only once, even inside", "could not be imported. ExtensionAlreadyLoaded The extension is already loaded.", "'least one prefix') return ret async def get_context(self, message: Message,", "in self.__cogs.copy().items(): if _is_submodule(name, cog.__module__): self.remove_cog(cogname) # remove all the", "reload. It must be dot separated like regular Python imports", "string as the prefix always matches, enabling prefix-less command invocation.", "to ``extension_setup`` from :meth:`~.Bot.load_extension`. Parameters ------------ name: :class:`str` The extension", "__init__(self, command_prefix: Any, auth: Auth, *, help_command: Optional[HelpCommand] = _default,", "been # cleaned from the load_extension function call # so", "an empty string, it should always be last as no", "list_.remove(func) except ValueError: pass def check_once(self, func: MaybeCoro) -> MaybeCoro:", "not loaded. \"\"\" lib = self.__extensions.get(name) if lib is None:", ":meth:`Command.invoke` call. Regular global checks are called whenever a command", "Context, *, call_once: bool = False) -> bool: data =", "\"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension name to extension.", ":class:`fortnitepy.PartyMessage`] The message context to get the prefix of. Returns", "class creation or the class name if unspecified. \"\"\" return", "del sys.modules[key] raise ExtensionFailed(key, e) from e try: setup =", "``None``. For more information on implementing a help command, see", "ctx.prefix = invoked_prefix ctx.command = self.all_commands.get(invoker) return ctx def _print_error(self,", "cog._eject(self) def get_cog(self, name: str) -> Optional[Cog]: \"\"\"Gets the cog", "if check is None or check(future): if cancel: _cancel_futs(pending) return", "(event.__module__ is not None and _is_submodule(name, event.__module__)): remove.append(index) for index", "futures: List[asyncio.Future], ctx: Context, error: Exception) -> None: def check(future):", "-> Mapping[str, types.ModuleType]: \"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension", "prefix is what the message content must contain initially to", "-> None: \"\"\"|coro| Invokes the command given under the invocation", "set at runtime. To remove the help command pass ``None``.", "class also subclasses :class:`.GroupMixin` to provide the functionality to manage", "def __init__(self, command_prefix: Any, auth: Auth, *, help_command: Optional[HelpCommand] =", "self.dispatch_and_wait_event('close'), ) for extension in tuple(self.__extensions): try: self.unload_extension(extension) except Exception:", "bot. A cog is a class that has its own", "restriction, including without limitation the rights to use, copy, modify,", "list ' 'returned from get_prefix must ' 'contain only strings,", "from e try: setup = getattr(lib, 'extension_setup') except AttributeError: del", "logging import inspect import asyncio import types import sys import", "---------- name: :class:`str` The name of the cog to remove.", "cog has registered will be removed as well. If no", "must have a global function, ``extension_setup`` defined as the entry", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "the prefix the bot is listening to with the message", "information on implementing a help command, see :ref:`ext_commands_help_command`. owner_id: Optional[:class:`int`]", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "coroutine to register as the pre-invoke hook. Raises ------ TypeError", "self._before_invoke = coro return coro def after_invoke(self, coro: MaybeCoro) ->", "or using :meth:`.check_once`. \"\"\" list_ = self._check_once if call_once else", "coro def after_invoke(self, coro: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that", "will be matched. case_insensitive: :class:`bool` Whether the commands should be", "matches, enabling prefix-less command invocation. The command prefix could also", "replace it with our own error if that's the case.", ".view import StringView from .context import Context from .help import", "fine grained control over the processing. The returned context is", "= None self._before_invoke = None self._after_invoke = None if help_command", "cog in tuple(self.__cogs): try: self.remove_cog(cog) except Exception: pass await self._close(", "raise TypeError('get_prefix must return either a string ' 'or a", "error. If any check or argument parsing procedures fail then", "elif self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command = None else:", "for the collection. You cannot set both `owner_id` and `owner_ids`.", "the load_extension function call # so let's load it from", "commands. Parameters ---------- cog: :class:`.Cog` The cog to register to", "For example, if the command prefix is ``('!', '!?')`` the", "decorator that adds a \"call once\" global check to the", "the prior working state. Parameters ------------ name: :class:`str` The extension", "be a valid invocation context, :attr:`.Context.valid` must be checked to", "in self._events.copy().values(): remove = [] for index, event in enumerate(event_list):", "The returned context is not guaranteed to be a valid", "argument in class creation or the class name if unspecified.", "valid candidate to be invoked under :meth:`~.Bot.invoke`. Parameters ---------- message:", "using other low level tools, and is equivalent to a", "= kwargs.get('owner_ids', set()) if self.owner_id and self.owner_ids: raise TypeError('Both owner_id", "must be similar enough to :class:`.Context`\\'s interface. Returns ------- :class:`.Context`", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR", "only once per :meth:`Command.invoke` call. Regular global checks are called", "self.command_prefix = command_prefix self.description = inspect.cleandoc(description) if description else ''", "_is_submodule(name, cmd.module): if isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name) # remove all", "raise TypeError('command_prefix must be plain string, ' 'iterable of strings,", "check to the bot. Unlike regular global checks, this one", "callable that takes in the bot as its first parameter", "the Software, and to permit persons to whom the Software", "-> None: \"\"\"Adds a \"cog\" to the bot. A cog", "and associated documentation files (the \"Software\"), to deal in the", "MaybeCoro: r\"\"\"A decorator that adds a check globally to every", "self.all_commands.copy().values(): if cmd.module is not None and _is_submodule(name, cmd.module): if", "_DefaultRepr() class Bot(GroupMixin, Client): \"\"\"Represents a fortnite bot. This class", "module that contains commands, cogs, or listeners. An extension must", "the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "= [] for index, event in enumerate(event_list): if (event.__module__ is", "module in sys.modules.items() if _is_submodule(lib.__name__, name) } try: # Unload", "cls: Context = Context) -> Context: r\"\"\"|coro| Returns the invocation", "a useful function to clean-up database connections or any type", "cogs, or listeners. An extension must have a global function,", "= False) -> None: def _cancel_futs(pending_futures: Set[asyncio.Future]) -> None: for", "of the internal command callback raising an error (i.e. :exc:`.CommandInvokeError`\\).", "asyncio.Future): self._print_error(ctx, error) def dispatch_error(self, ctx: Context, error: Exception) ->", "\"\"\" if name in self.__extensions: raise ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name)", "Set from fortnitepy.client import Client from fortnitepy.auth import Auth from", "= self.command_prefix if callable(prefix): if asyncio.iscoroutinefunction(prefix): ret = await prefix(self,", "import types import sys import importlib import collections import traceback", "try: setup = getattr(lib, 'extension_setup') except AttributeError: del sys.modules[key] raise", "not isinstance(cog, Cog): raise TypeError('Cogs must derive from Cog.') cog", "my_whitelist \"\"\" self.add_check(func, call_once=True) return func async def can_run(self, ctx:", "iterable of strings indicating that multiple checks for the prefix", "Unload and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name)", "asyncio.iscoroutinefunction(prefix): ret = await prefix(self, message) else: ret = prefix(self,", "cmd.module): if isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name) # remove all the", "\"\"\"Atomically reloads an extension. This replaces the extension with the", "inspect.cleandoc(description) if description else '' self.owner_id = kwargs.get('owner_id') self.owner_ids =", "func The function to remove from the global checks. call_once:", "registers a coroutine as a pre-invoke hook. A pre-invoke hook", "self._event_has_handler('command_error'): futures = self.dispatch_event('command_error', ctx, error) asyncio.ensure_future(self._wait_for_error_return( futures, ctx, error", "owner. \"\"\" if self.owner_id: return user_id == self.owner_id else: return", "coroutine.') self._before_invoke = coro return coro def after_invoke(self, coro: MaybeCoro)", "ctx: Context, error: Exception) -> None: if self._event_has_handler('command_error'): futures =", "help_command = self.help_command if help_command and help_command.cog is cog: help_command.cog", "event listeners and commands. Parameters ---------- cog: :class:`.Cog` The cog", "this software and associated documentation files (the \"Software\"), to deal", "ValueError: pass def check_once(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator", "in class creation or the class name if unspecified. \"\"\"", "prefix(self, message) else: ret = prefix(self, message) if not isinstance(ret,", "a coroutine as a post-invoke hook. A post-invoke hook is", "commands. return ctx.party is not None \"\"\" self.add_check(func) return func", "all copies or substantial portions of the Software. THE SOFTWARE", "return self.__cogs.get(name) @property def cogs(self) -> Mapping[str, Cog]: \"\"\"Mapping[:class:`str`, :class:`Cog`]:", "must be a subclass ' 'of HelpCommand') if self._help_command is", "cog. \"\"\" return types.MappingProxyType(self.__cogs) def _remove_module_references(self, name: str) -> None:", "\"\"\"Gets the cog instance requested. If the cog is not", "procedures pass without error. If any check or argument parsing", "clean-up scenarios. Parameters ---------- coro: The coroutine to register as", "None, **kwargs: Any) -> None: kwargs['case_insensitive'] = kwargs.get('case_insensitive', False) super().__init__(auth,", "def check(self, func: MaybeCoro) -> MaybeCoro: r\"\"\"A decorator that adds", "# remove all the commands from the module for cmd", "imported. ExtensionAlreadyLoaded The extension is already loaded. ExtensionMissingEntryPoint The extension", "self.can_run(ctx, call_once=True): await ctx.command.invoke(ctx) else: raise CheckFailure('The global check once", "for index, event in enumerate(event_list): if (event.__module__ is not None", "\"\"\" if self.owner_id: return user_id == self.owner_id else: return user_id", ":meth:`unload_extension` followed by a :meth:`load_extension` except done in an atomic", "bot and the module is un-imported. The extension can provide", "command callback raising an error (i.e. :exc:`.CommandInvokeError`\\). This makes it", "checks and argument parsing procedures succeed. This hook is, however,", "if that's the case. if isinstance(ret, collections.abc.Iterable): raise raise TypeError('command_prefix", "commands. Attributes ----------- command_prefix The command prefix is what the", "following conditions: The above copyright notice and this permission notice", "set both `owner_id` and `owner_ids`. This is used by :meth:`.is_owner()`", "self.unload_extension(extension) except Exception: pass for cog in tuple(self.__cogs): try: self.remove_cog(cog)", "can either be a regular function or a coroutine. This", "self.__extensions: raise ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name) if spec is None:", "can provide an optional global function, ``cog_teardown``, to do miscellaneous", "return '<default-help-command>' _default = _DefaultRepr() class Bot(GroupMixin, Client): \"\"\"Represents a", "return future async def _wait_for_error_return(self, futures: List[asyncio.Future], ctx: Context, error:", "Parameters ---------- func The function to remove from the global", "matched. case_insensitive: :class:`bool` Whether the commands should be case insensitive.", "view=view, bot=self, message=message) prefix = await self.get_prefix(message) invoked_prefix = prefix", "= None async def get_prefix(self, message: Message) -> Any: \"\"\"|coro|", "_, obj in inspect.getmembers(self): if isinstance(obj, _BaseCommand): obj.instance = self", "can get this prefix via :attr:`.Context.prefix`. To avoid confusion empty", "non-decorator interface to :meth:`.check` and :meth:`.check_once`. Parameters ---------- func The", "ExtensionFailed(key, e) from e try: setup = getattr(lib, 'extension_setup') except", "Should a custom class be provided, it must be similar", "ExtensionMissingEntryPoint The extension does not have a extension_setup function. ExtensionFailed", "# get the previous module states from sys modules modules", "will never be matched to any message as the previous", "is equivalent to the name passed via keyword argument in", "note:: This function can either be a regular function or", "index, event in enumerate(event_list): if (event.__module__ is not None and", "must contain at ' 'least one prefix') return ret async", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "are requesting. This is equivalent to the name passed via", "in reversed(remove): del event_list[index] def _call_module_finalizers(self, lib: object, key: str)", "must be plain string, ' 'iterable of strings, or callable", "by a :meth:`load_extension` except done in an atomic way. That", "self._call_module_finalizers(lib, key) raise ExtensionFailed(key, e) from e else: self.__extensions[key] =", "if (self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection)): raise TypeError( 'owner_ids must", "as the pre-invoke hook. Raises ------ TypeError The coroutine passed", "and _is_submodule(name, event.__module__)): remove.append(index) for index in reversed(remove): del event_list[index]", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS", "ideal for clean-up scenarios. Parameters ---------- coro: The coroutine to", "is, if an operation fails mid-reload then the bot will", "only once, even inside the default help command. .. note::", "coro return coro def after_invoke(self, coro: MaybeCoro) -> MaybeCoro: r\"\"\"A", "lib = self.__extensions.get(name) if lib is None: raise ExtensionNotLoaded(name) self._remove_module_references(lib.__name__)", "whenever a command is called or :meth:`.Command.can_run` is called. This", "of these, not ' '{}'.format(ret.__class__.__name__)) if not ret: raise ValueError('Iterable", "This is built using other low level tools, and is", "an extension. An extension is a python module that contains", "def cogs(self) -> Mapping[str, Cog]: \"\"\"Mapping[:class:`str`, :class:`Cog`]: A read-only mapping", "name to unload. It must be dot separated like regular", "e) from e try: setup = getattr(lib, 'extension_setup') except AttributeError:", "is None: raise ExtensionNotLoaded(name) # get the previous module states", "0: return True for func in data: if asyncio.iscoroutinefunction(func): res", "could also be an iterable of strings indicating that multiple", "extension name to load. It must be dot separated like", "if accessing a sub-module. e.g. ``foo.test`` if you want to", "an execution error. \"\"\" lib = self.__extensions.get(name) if lib is", "copies or substantial portions of the Software. THE SOFTWARE IS", "message as the previous one matches messages starting with ``!?``.", "OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "be imported. ExtensionAlreadyLoaded The extension is already loaded. ExtensionMissingEntryPoint The", "execution error. \"\"\" if name in self.__extensions: raise ExtensionAlreadyLoaded(name) spec", "be a collection not ' '{0.__class__!r}'.format(self.owner_ids) ) self.__cogs = {}", "logging.getLogger(__name__) def _is_submodule(parent: str, child: str) -> bool: return parent", "a string to indicate what the prefix should be, or", "is called. This type of check bypasses that and ensures", "or :meth:`.Command.can_run` is called. This type of check bypasses that", "None and _is_submodule(name, cmd.module): if isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name) #", "------- .. code-block:: python3 @bot.check def global_check(ctx): # Allows only", "and :meth:`~.Bot.after_invoke` hooks are only called if all checks and", "Similar to :meth:`~.Bot.before_invoke`\\, this is not called unless checks and", "bot. This class is a subclass of :class:`fortnitepy.Client` and as", "whitelist(ctx): return ctx.message.author.id in my_whitelist \"\"\" self.add_check(func, call_once=True) return func", "name: str) -> None: \"\"\"Loads an extension. An extension is", "cogs are removed from the bot and the module is", "to be case insensitive as well. description: :class:`str` The content", "help command pass ``None``. For more information on implementing a", "message: Message, *, cls: Context = Context) -> Context: r\"\"\"|coro|", "exc = CommandNotFound('Command \"{}\" is not found' ''.format(ctx.invoked_with)) self.dispatch_error(ctx, exc)", "= value value._add_to_bot(self) elif self._help_command is not None: self._help_command._remove_from_bot(self) self._help_command", "*, call_once: bool = False) -> None: \"\"\"Adds a global", "case insensitive. Defaults to ``False``. This attribute does not carry", "if isinstance(prefix, str): if not view.skip_string(prefix): return ctx else: try:", "initially to have a command invoked. This prefix could either", "ctx.command.invoke(ctx) else: raise CheckFailure('The global check once functions ' 'failed.')", "via the ``cls`` parameter. \"\"\" # noqa view = StringView(message.content)", ":meth:`~.Bot.before_invoke`\\, this is not called unless checks and argument parsing", "factory class that will be used to create the context.", "if a user id is the owner of the bot.", "GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name) # remove all the listeners from the", "Optional[HelpCommand]: return self._help_command @help_command.setter def help_command(self, value: Optional[HelpCommand]) -> None:", "dynamically set at runtime. To remove the help command pass", "Raises ------ TypeError The coroutine passed is not actually a", "= None if help_command is _default: self.help_command = FortniteHelpCommand() else:", "a cog from the bot. All registered commands and event", "await self.wait_for_futures(futures, check=check) if isinstance(ret, asyncio.Future): self._print_error(ctx, error) def dispatch_error(self,", "self._checks try: list_.remove(func) except ValueError: pass def check_once(self, func: MaybeCoro)", "python3 @bot.check def global_check(ctx): # Allows only party commands. return", "it from our old compiled library. lib.extension_setup(self) self.__extensions[name] = lib", "key) raise ExtensionFailed(key, e) from e else: self.__extensions[key] = lib", ":class:`Cog`]: A read-only mapping of cog name to cog. \"\"\"", "for module in list(sys.modules.keys()): if _is_submodule(name, module): del sys.modules[module] def", "cmd.module is not None and _is_submodule(name, cmd.module): if isinstance(cmd, GroupMixin):", "the bot and the module is un-imported. The extension can", "else: res = func(ctx) if not res: return False return", "not called unless checks and argument parsing procedures succeed. This", "_default = _DefaultRepr() class Bot(GroupMixin, Client): \"\"\"Represents a fortnite bot.", "exc) async def process_commands(self, message: Message) -> None: \"\"\"|coro| This", "To avoid confusion empty iterables are not allowed. .. note::", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR", "inspect import asyncio import types import sys import importlib import", "if callable(prefix): if asyncio.iscoroutinefunction(prefix): ret = await prefix(self, message) else:", "except Exception: pass finally: self.__extensions.pop(key, None) sys.modules.pop(key, None) name =", "user_id == self.owner_id else: return user_id in self.owner_ids def before_invoke(self,", "hooks are not called. Parameters ---------- coro The coroutine to", "a command invoked. This prefix could either be a string", "globally to every command. .. note:: This function can either", "this one is called only once per :meth:`Command.invoke` call. Regular", "module is un-imported. The extension can provide an optional global", "used to create the context. By default, this is :class:`.Context`.", "+ \".\") class _DefaultRepr: def __repr__(self) -> str: return '<default-help-command>'", "process commands for. \"\"\" # noqa if message.author.id == self.user.id:", "more fine grained control over the processing. The returned context", "only raise exceptions inherited from :exc:`.CommandError`. Example ------- .. code-block::", "OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "a generator raised this exception. Don't # replace it with", "owns the bot. This is similar to `owner_id`. For performance", "similar to `owner_id`. For performance reasons it is recommended to", "else: self._checks.append(func) def remove_check(self, func: MaybeCoro, *, call_once: bool =", "---------- user_id: :class:`str` The user id to check for. Returns", "'<default-help-command>' _default = _DefaultRepr() class Bot(GroupMixin, Client): \"\"\"Represents a fortnite", "= Context) -> Context: r\"\"\"|coro| Returns the invocation context from", "False) -> None: \"\"\"Adds a global check to the bot.", "= self._check_once if call_once else self._checks try: list_.remove(func) except ValueError:", "commands from the module for cmd in self.all_commands.copy().values(): if cmd.module", "isinstance(value, str): raise TypeError('Iterable command_prefix or list ' 'returned from", "name passed via keyword argument in class creation or the", "bool = False) -> None: \"\"\"Removes a global check from", "invoked under :meth:`~.Bot.invoke`. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message", "once per :meth:`Command.invoke` call. Regular global checks are called whenever", "self.owner_id else: return user_id in self.owner_ids def before_invoke(self, coro: MaybeCoro)", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "that contains commands, cogs, or listeners. An extension must have", "cog is a class that has its own event listeners", "called once per :meth:`Command.invoke` call. \"\"\" if call_once: self._check_once.append(func) else:", "or listeners. An extension must have a global function, ``extension_setup``", "not asyncio.iscoroutinefunction(coro): raise TypeError('The pre-invoke hook must be a coroutine.')", "code-block:: python3 @bot.check def global_check(ctx): # Allows only party commands.", ":class:`str` The name of the cog to remove. \"\"\" cog", "str) -> None: \"\"\"Unloads an extension. When the extension is", "prefix: if view.skip_string(element): invoked_prefix = element break else: invoked_prefix =", "call_once: bool = False) -> None: \"\"\"Removes a global check", "checks are called whenever a command is called or :meth:`.Command.can_run`", "except TypeError: # It's possible that a generator raised this", "= invoker ctx.prefix = invoked_prefix ctx.command = self.all_commands.get(invoker) return ctx", "raise @property def extensions(self) -> Mapping[str, types.ModuleType]: \"\"\"Mapping[:class:`str`, :class:`py:types.ModuleType`]: A", "from .typedefs import Message log = logging.getLogger(__name__) def _is_submodule(parent: str,", "used by :meth:`.is_owner()` and checks that call this method. owner_ids:", "in prefix: if view.skip_string(element): invoked_prefix = element break else: invoked_prefix", "Any, auth: Auth, *, help_command: Optional[HelpCommand] = _default, description: Optional[str]", ") async def wait_for_futures(self, futures: ListOrTuple, *, check: Optional[callable] =", ") # Set should only contain one value for future", "The command prefix is what the message content must contain", "the name passed via keyword argument in class creation or", "to the module # remove the cogs registered from the", "*, cls: Context = Context) -> Context: r\"\"\"|coro| Returns the", ":class:`fortnitepy.PartyMessage`] The message to process commands for. \"\"\" # noqa", "------ TypeError The cog does not inherit from :class:`.Cog`. CommandError", "\"dynamic\" command prefixes. This callable can be either a regular", "not None and _is_submodule(name, cmd.module): if isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands() self.remove_command(cmd.name)", "the invocation context and handles all the internal event dispatch", "---------- coro: The coroutine to register as the post-invoke hook.", "error. \"\"\" lib = self.__extensions.get(name) if lib is None: raise", "to remove from the global checks. call_once: :class:`bool` If the", "else: raise CheckFailure('The global check once functions ' 'failed.') except", "the bot. This is used by :meth:`.is_owner()` and checks that", "def can_run(self, ctx: Context, *, call_once: bool = False) ->", "a global check to the bot. This is the non-decorator", "the previous module states from sys modules modules = {", "global function, ``cog_teardown``, to do miscellaneous clean-up if necessary. This", "# noqa view = StringView(message.content) ctx = cls(prefix=None, view=view, bot=self,", "this can change via the ``cls`` parameter. \"\"\" # noqa", "func = getattr(lib, 'cog_teardown') except AttributeError: pass else: try: func(self)", "pre-invoke hook must be a coroutine.') self._before_invoke = coro return", "coroutine is called automatically when a new message is received.", "name to cog. \"\"\" return types.MappingProxyType(self.__cogs) def _remove_module_references(self, name: str)", "always be last as no prefix after it will be", "return either a string ' 'or a list of string,", "# cleaned from the load_extension function call # so let's", "The extension was not loaded. \"\"\" lib = self.__extensions.get(name) if", "_cancel_futs(pending) return future async def _wait_for_error_return(self, futures: List[asyncio.Future], ctx: Context,", "cog from the bot. All registered commands and event listeners", ".. note:: The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are only called", "# if the load failed, the remnants should have been", "cog instance requested. If the cog is not found, ``None``", "name: str) -> None: \"\"\"Unloads an extension. When the extension", "Context = Context) -> Context: r\"\"\"|coro| Returns the invocation context", "register_methods(self) -> None: for _, obj in inspect.getmembers(self): if isinstance(obj,", "for element in prefix: if view.skip_string(element): invoked_prefix = element break", "a python module that contains commands, cogs, or listeners. An", "cog is found then this method has no effect. Parameters", "the message. This is a more low-level counter-part for :meth:`.process_commands`", "= None, timeout: Optional[int] = None, cancel: bool = False)", "pending: done, pending = await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout )", "global check. call_once: :class:`bool` If the function should only be", "free of charge, to any person obtaining a copy of", "'{}'.format(prefix.__class__.__name__)) for value in prefix: if not isinstance(value, str): raise", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "None, timeout: Optional[int] = None, cancel: bool = False) ->", "Software, and to permit persons to whom the Software is", "it a useful function to set up database connections or", "is already loaded. ExtensionMissingEntryPoint The extension does not have a", "roll-back to the prior working state. Parameters ------------ name: :class:`str`", "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or", "directly before the command is called. This makes it a", "invoked_prefix = None else: return ctx except TypeError: if not", "Exception: pass finally: self.__extensions.pop(key, None) sys.modules.pop(key, None) name = lib.__name__", "in tuple(self.__extensions): try: self.unload_extension(extension) except Exception: pass for cog in", "Mapping, Set from fortnitepy.client import Client from fortnitepy.auth import Auth", "id to check for. Returns ------- :class:`bool` Whether the user", "\"\"\" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission", "value in prefix: if not isinstance(value, str): raise TypeError('Iterable command_prefix", "to caller sys.modules.update(modules) raise @property def extensions(self) -> Mapping[str, types.ModuleType]:", "StringView(message.content) ctx = cls(prefix=None, view=view, bot=self, message=message) prefix = await", "The extension name to unload. It must be dot separated", "cogs registered from the module for cogname, cog in self.__cogs.copy().items():", "-> bool: return parent == child or child.startswith(parent + \".\")", "to the bot and other groups. Without this coroutine, none", "to not pass a prefix that matches a longer prefix", "= lib try: spec.loader.exec_module(lib) except Exception as e: del sys.modules[key]", "be removed as well. If no cog is found then", "traceback from typing import Any, List, Optional, Mapping, Set from", "await ctx.command.dispatch_error(ctx, exc) else: self.dispatch_event('command_completion', ctx) elif ctx.invoked_with: exc =", "The command prefix could also be an iterable of strings", "self.__extensions lib = importlib.util.module_from_spec(spec) sys.modules[key] = lib try: spec.loader.exec_module(lib) except", "its own event listeners and commands. Parameters ---------- cog: :class:`.Cog`", "None \"\"\" self.add_check(func) return func def add_check(self, func: MaybeCoro, *,", ":class:`str`] A list of prefixes or a single prefix that", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "have a single argument, the ``bot``. Parameters ---------- name: :class:`str`", "return help_command = self.help_command if help_command and help_command.cog is cog:", "MaybeCoro, *, call_once: bool = False) -> None: \"\"\"Adds a", "If the cog is not found, ``None`` is returned instead.", "The user ID that owns the bot. This is used", "precondition: key not in self.__extensions lib = importlib.util.module_from_spec(spec) sys.modules[key] =", "dispatch_close: await asyncio.gather( self.dispatch_and_wait_event('before_close'), self.dispatch_and_wait_event('close'), ) for extension in tuple(self.__extensions):", "the commands from the module for cmd in self.all_commands.copy().values(): if", "self._remove_module_references(lib.__name__) self._call_module_finalizers(lib, name) self.load_extension(name) except Exception: # if the load", "The user IDs that owns the bot. This is similar", "are only called if all checks and argument parsing procedures", "is un-imported. The extension can provide an optional global function,", "post-invoke hook. Raises ------ TypeError The coroutine passed is not", "tuple(self.__cogs): try: self.remove_cog(cog) except Exception: pass await self._close( close_http=close_http, dispatch_close=dispatch_close", "MaybeCoro: \"\"\"A decorator that registers a coroutine as a pre-invoke", "of. Returns -------- Union[List[:class:`str`], :class:`str`] A list of prefixes or", "you want to import ``foo/test.py``. Raises ------- ExtensionNotLoaded The extension", "'owner_ids must be a collection not ' '{0.__class__!r}'.format(self.owner_ids) ) self.__cogs", "if call_once else self._checks if len(data) == 0: return True", "be a subclass ' 'of HelpCommand') if self._help_command is not", "\"\"\"|coro| Checks if a user id is the owner of", "A read-only mapping of cog name to cog. \"\"\" return", "ExtensionFailed The extension or its setup function had an execution", "except Exception as e: del sys.modules[key] raise ExtensionFailed(key, e) from", "break else: invoked_prefix = None else: return ctx except TypeError:", "it with our own error if that's the case. if", "is similar to `owner_id`. For performance reasons it is recommended", "hook is called directly after the command is called. This", "the cog you are requesting. This is equivalent to the", "the extension is loaded. This entry point must have a", "wait_for_futures(self, futures: ListOrTuple, *, check: Optional[callable] = None, timeout: Optional[int]", "must be a coroutine.') self._after_invoke = coro return coro def", "loading. \"\"\" if not isinstance(cog, Cog): raise TypeError('Cogs must derive", "string, not ' '{}'.format(prefix.__class__.__name__)) for value in prefix: if not", "a \"cog\" to the bot. A cog is a class", "type of this can change via the ``cls`` parameter. \"\"\"", "lib.__name__ for module in list(sys.modules.keys()): if _is_submodule(name, module): del sys.modules[module]", "a context. Parameters ---------- message: Union[:class:`fortnitepy.FriendMessage`, :class:`fortnitepy.PartyMessage`] The message context", "of charge, to any person obtaining a copy of this", "if _is_submodule(lib.__name__, name) } try: # Unload and then load", "self._help_command = None async def get_prefix(self, message: Message) -> Any:", "if isinstance(ret, collections.abc.Iterable): raise raise TypeError('command_prefix must be plain string,", "listeners and commands. Parameters ---------- cog: :class:`.Cog` The cog to", ":class:`bool` Whether the user is the owner. \"\"\" if self.owner_id:", "instance requested. If the cog is not found, ``None`` is", "extension could not be imported. ExtensionAlreadyLoaded The extension is already", ":attr:`.Context.valid` must be checked to make sure it is. If", "type(error), error, error.__traceback__, file=sys.stderr ) async def wait_for_futures(self, futures: ListOrTuple,", "command is called or :meth:`.Command.can_run` is called. This type of", "called. This makes it a useful function to clean-up database", "should only be called once per :meth:`Command.invoke` call. \"\"\" if", "ctx except TypeError: if not isinstance(prefix, list): raise TypeError('get_prefix must", "The above copyright notice and this permission notice shall be", "function that was used as a global check. call_once: :class:`bool`", "`owner_id` and `owner_ids`. This is used by :meth:`.is_owner()` and checks", "coroutine as a post-invoke hook. A post-invoke hook is called", "is not None and _is_submodule(name, cmd.module): if isinstance(cmd, GroupMixin): cmd.recursively_remove_all_commands()", "a callable that takes in the bot as its first", "check bypasses that and ensures that it's called only once,", "``cog_teardown``, to do miscellaneous clean-up if necessary. This function takes", "be case insensitive. Defaults to ``False``. This attribute does not", "import asyncio import types import sys import importlib import collections", "Rapptz Permission is hereby granted, free of charge, to any", "either a string ' 'or a list of string, not", "Returns ------- :class:`bool` Whether the user is the owner. \"\"\"", "traceback.print_exc() continue super().register_methods() async def close(self, *, close_http: bool =", "module in list(sys.modules.keys()): if _is_submodule(name, module): del sys.modules[module] def _load_from_module_spec(self,", "listeners. An extension must have a global function, ``extension_setup`` defined", "associated documentation files (the \"Software\"), to deal in the Software", "try: # Unload and then load the module... self._remove_module_references(lib.__name__) self._call_module_finalizers(lib,", "any type of clean up required. This post-invoke hook takes", "self._after_invoke = None if help_command is _default: self.help_command = FortniteHelpCommand()", "always matches, enabling prefix-less command invocation. The command prefix could", "clean up required. This post-invoke hook takes a sole parameter,", "from the bot. Parameters ---------- func The function to remove", "try: self.unload_extension(extension) except Exception: pass for cog in tuple(self.__cogs): try:", "To remove the help command pass ``None``. For more information" ]
[ "grid): \"\"\" :type grid: List[List[int]] :rtype: int \"\"\" m, n", "if i == 0 and j == 0: dp[i][j] =", "m, n = len(grid), len(grid[0]) dp = [[0] * n", "1][j], dp[i][j - 1]) return dp[m - 1][n - 1]", "= grid[i][j] + dp[i][j - 1] elif j == 0:", "range(n): if i == 0 and j == 0: dp[i][j]", "def minPathSum(self, grid): \"\"\" :type grid: List[List[int]] :rtype: int \"\"\"", "range(m): for j in range(n): if i == 0 and", "and j == 0: dp[i][j] = grid[0][0] elif i ==", "Solution(object): def minPathSum(self, grid): \"\"\" :type grid: List[List[int]] :rtype: int", "for _ in range(m)] for i in range(m): for j", "[[0] * n for _ in range(m)] for i in", "len(grid), len(grid[0]) dp = [[0] * n for _ in", "j == 0: dp[i][j] = grid[0][0] elif i == 0:", "for j in range(n): if i == 0 and j", "dp[i - 1][j] else: dp[i][j] = grid[i][j] + min(dp[i -", "for i in range(m): for j in range(n): if i", "0: dp[i][j] = grid[i][j] + dp[i - 1][j] else: dp[i][j]", "+ min(dp[i - 1][j], dp[i][j - 1]) return dp[m -", "+ dp[i - 1][j] else: dp[i][j] = grid[i][j] + min(dp[i", "n for _ in range(m)] for i in range(m): for", "\"\"\" m, n = len(grid), len(grid[0]) dp = [[0] *", "in range(m)] for i in range(m): for j in range(n):", "grid[0][0] elif i == 0: dp[i][j] = grid[i][j] + dp[i][j", "+ dp[i][j - 1] elif j == 0: dp[i][j] =", "j == 0: dp[i][j] = grid[i][j] + dp[i - 1][j]", "- 1][j] else: dp[i][j] = grid[i][j] + min(dp[i - 1][j],", "_ in range(m)] for i in range(m): for j in", "minPathSum(self, grid): \"\"\" :type grid: List[List[int]] :rtype: int \"\"\" m,", "range(m)] for i in range(m): for j in range(n): if", "= grid[i][j] + dp[i - 1][j] else: dp[i][j] = grid[i][j]", "<filename>LeetCodeSolutions/python/64_Minimum_Path_Sum.py class Solution(object): def minPathSum(self, grid): \"\"\" :type grid: List[List[int]]", "= [[0] * n for _ in range(m)] for i", "dp[i][j - 1] elif j == 0: dp[i][j] = grid[i][j]", "1][j] else: dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j", "i in range(m): for j in range(n): if i ==", "i == 0: dp[i][j] = grid[i][j] + dp[i][j - 1]", "else: dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j -", "dp[i][j] = grid[0][0] elif i == 0: dp[i][j] = grid[i][j]", "grid: List[List[int]] :rtype: int \"\"\" m, n = len(grid), len(grid[0])", "= grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]) return", "- 1][j], dp[i][j - 1]) return dp[m - 1][n -", "min(dp[i - 1][j], dp[i][j - 1]) return dp[m - 1][n", "elif j == 0: dp[i][j] = grid[i][j] + dp[i -", "elif i == 0: dp[i][j] = grid[i][j] + dp[i][j -", "= len(grid), len(grid[0]) dp = [[0] * n for _", "\"\"\" :type grid: List[List[int]] :rtype: int \"\"\" m, n =", "i == 0 and j == 0: dp[i][j] = grid[0][0]", "dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])", "0: dp[i][j] = grid[0][0] elif i == 0: dp[i][j] =", "grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]) return dp[m", "0: dp[i][j] = grid[i][j] + dp[i][j - 1] elif j", "1] elif j == 0: dp[i][j] = grid[i][j] + dp[i", "dp[i][j] = grid[i][j] + dp[i][j - 1] elif j ==", "dp[i][j] = grid[i][j] + dp[i - 1][j] else: dp[i][j] =", "- 1] elif j == 0: dp[i][j] = grid[i][j] +", ":rtype: int \"\"\" m, n = len(grid), len(grid[0]) dp =", "class Solution(object): def minPathSum(self, grid): \"\"\" :type grid: List[List[int]] :rtype:", "== 0: dp[i][j] = grid[i][j] + dp[i][j - 1] elif", "j in range(n): if i == 0 and j ==", ":type grid: List[List[int]] :rtype: int \"\"\" m, n = len(grid),", "List[List[int]] :rtype: int \"\"\" m, n = len(grid), len(grid[0]) dp", "n = len(grid), len(grid[0]) dp = [[0] * n for", "in range(n): if i == 0 and j == 0:", "== 0: dp[i][j] = grid[0][0] elif i == 0: dp[i][j]", "== 0: dp[i][j] = grid[i][j] + dp[i - 1][j] else:", "* n for _ in range(m)] for i in range(m):", "len(grid[0]) dp = [[0] * n for _ in range(m)]", "0 and j == 0: dp[i][j] = grid[0][0] elif i", "in range(m): for j in range(n): if i == 0", "grid[i][j] + dp[i][j - 1] elif j == 0: dp[i][j]", "== 0 and j == 0: dp[i][j] = grid[0][0] elif", "= grid[0][0] elif i == 0: dp[i][j] = grid[i][j] +", "dp = [[0] * n for _ in range(m)] for", "int \"\"\" m, n = len(grid), len(grid[0]) dp = [[0]", "grid[i][j] + dp[i - 1][j] else: dp[i][j] = grid[i][j] +" ]
[ "_winreg.HKEY_CURRENT_USER) try: key = _winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") path, _ = _winreg.QueryValueEx(key,", "import _winreg import os def get_shared_cache_folder(): \"\"\" Look in the", "= _winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") path, _ = _winreg.QueryValueEx(key, \"CACHEFOLDER\") except OSError:", "_winreg.QueryValueEx(key, \"CACHEFOLDER\") except OSError: return None return path def set_shared_cache_folder(folder_path):", "\"CACHEFOLDER\") except OSError: return None return path def set_shared_cache_folder(folder_path): if", "set_shared_cache_folder(folder_path): if not os.path.isdir(folder_path): try: os.makedirs(folder_path) except OSError: raise ValueError(\"Could", "the configured cache folder. If there is no entry, then", "not create directory {}\".format(folder_path)) folder_path = os.path.normpath(folder_path) + os.sep key_eveonline", "def get_shared_cache_folder(): \"\"\" Look in the registry for the configured", "_winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) key_eveprobe = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe,", "r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) def get_index_path(hint): return hint", "try: os.makedirs(folder_path) except OSError: raise ValueError(\"Could not create directory {}\".format(folder_path))", "If there is no entry, then we create one. :return:", "we create one. :return: \"\"\" _winreg.aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try:", "no entry, then we create one. :return: \"\"\" _winreg.aReg =", "os def get_shared_cache_folder(): \"\"\" Look in the registry for the", ":return: \"\"\" _winreg.aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try: key = _winreg.OpenKey(_winreg.aReg,", "create directory {}\".format(folder_path)) folder_path = os.path.normpath(folder_path) + os.sep key_eveonline =", "\"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) key_eveprobe = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe, \"CACHEFOLDER\",", "key_eveonline = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) key_eveprobe", "path def set_shared_cache_folder(folder_path): if not os.path.isdir(folder_path): try: os.makedirs(folder_path) except OSError:", "= _winreg.QueryValueEx(key, \"CACHEFOLDER\") except OSError: return None return path def", "_winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) def get_index_path(hint): return", "create one. :return: \"\"\" _winreg.aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try: key", "except OSError: raise ValueError(\"Could not create directory {}\".format(folder_path)) folder_path =", "def set_shared_cache_folder(folder_path): if not os.path.isdir(folder_path): try: os.makedirs(folder_path) except OSError: raise", "= _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) def get_index_path(hint):", "_winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) key_eveprobe = _winreg.CreateKey(_winreg.aReg,", "return path def set_shared_cache_folder(folder_path): if not os.path.isdir(folder_path): try: os.makedirs(folder_path) except", "there is no entry, then we create one. :return: \"\"\"", "configured cache folder. If there is no entry, then we", "then we create one. :return: \"\"\" _winreg.aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)", "one. :return: \"\"\" _winreg.aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try: key =", "r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) key_eveprobe = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\")", "+ os.sep key_eveonline = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\", 0, _winreg.REG_SZ,", "os.path.normpath(folder_path) + os.sep key_eveonline = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\", 0,", "{}\".format(folder_path)) folder_path = os.path.normpath(folder_path) + os.sep key_eveonline = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\")", "_winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") path, _ = _winreg.QueryValueEx(key, \"CACHEFOLDER\") except OSError: return", "path, _ = _winreg.QueryValueEx(key, \"CACHEFOLDER\") except OSError: return None return", "folder_path = os.path.normpath(folder_path) + os.sep key_eveonline = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline,", "= os.path.normpath(folder_path) + os.sep key_eveonline = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\",", "_ = _winreg.QueryValueEx(key, \"CACHEFOLDER\") except OSError: return None return path", "if not os.path.isdir(folder_path): try: os.makedirs(folder_path) except OSError: raise ValueError(\"Could not", "the registry for the configured cache folder. If there is", "key = _winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") path, _ = _winreg.QueryValueEx(key, \"CACHEFOLDER\") except", "= _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try: key = _winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") path, _", "key_eveprobe = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) def", "for the configured cache folder. If there is no entry,", "OSError: return None return path def set_shared_cache_folder(folder_path): if not os.path.isdir(folder_path):", "registry for the configured cache folder. If there is no", "Look in the registry for the configured cache folder. If", "return None return path def set_shared_cache_folder(folder_path): if not os.path.isdir(folder_path): try:", "in the registry for the configured cache folder. If there", "is no entry, then we create one. :return: \"\"\" _winreg.aReg", "os.path.isdir(folder_path): try: os.makedirs(folder_path) except OSError: raise ValueError(\"Could not create directory", "_winreg.REG_SZ, folder_path) key_eveprobe = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe, \"CACHEFOLDER\", 0, _winreg.REG_SZ,", "0, _winreg.REG_SZ, folder_path) key_eveprobe = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe, \"CACHEFOLDER\", 0,", "get_shared_cache_folder(): \"\"\" Look in the registry for the configured cache", "None return path def set_shared_cache_folder(folder_path): if not os.path.isdir(folder_path): try: os.makedirs(folder_path)", "_winreg import os def get_shared_cache_folder(): \"\"\" Look in the registry", "OSError: raise ValueError(\"Could not create directory {}\".format(folder_path)) folder_path = os.path.normpath(folder_path)", "r\"SOFTWARE\\CCP\\EVEONLINE\") path, _ = _winreg.QueryValueEx(key, \"CACHEFOLDER\") except OSError: return None", "os.makedirs(folder_path) except OSError: raise ValueError(\"Could not create directory {}\".format(folder_path)) folder_path", "try: key = _winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") path, _ = _winreg.QueryValueEx(key, \"CACHEFOLDER\")", "cache folder. If there is no entry, then we create", "folder_path) key_eveprobe = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEPROBE\") _winreg.SetValueEx(key_eveprobe, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path)", "not os.path.isdir(folder_path): try: os.makedirs(folder_path) except OSError: raise ValueError(\"Could not create", "raise ValueError(\"Could not create directory {}\".format(folder_path)) folder_path = os.path.normpath(folder_path) +", "directory {}\".format(folder_path)) folder_path = os.path.normpath(folder_path) + os.sep key_eveonline = _winreg.CreateKey(_winreg.aReg,", "ValueError(\"Could not create directory {}\".format(folder_path)) folder_path = os.path.normpath(folder_path) + os.sep", "entry, then we create one. :return: \"\"\" _winreg.aReg = _winreg.ConnectRegistry(None,", "folder. If there is no entry, then we create one.", "import os def get_shared_cache_folder(): \"\"\" Look in the registry for", "except OSError: return None return path def set_shared_cache_folder(folder_path): if not", "\"\"\" _winreg.aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try: key = _winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\")", "_winreg.aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try: key = _winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") path,", "_winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) try: key = _winreg.OpenKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") path, _ =", "os.sep key_eveonline = _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path)", "= _winreg.CreateKey(_winreg.aReg, r\"SOFTWARE\\CCP\\EVEONLINE\") _winreg.SetValueEx(key_eveonline, \"CACHEFOLDER\", 0, _winreg.REG_SZ, folder_path) key_eveprobe =", "\"\"\" Look in the registry for the configured cache folder." ]
[ "[ \"last year\" ], \"0 year ago\": [ \"this year\"", "wa kathatũ\", \"kat\" ], \"april\": [ \"mweri wa kana\", \"kan\"", "\"date_order\": \"DMY\", \"january\": [ \"mweri wa mbere\", \"mbe\" ], \"february\":", "[ \"ndagĩka\" ], \"second\": [ \"sekondi\" ], \"relative-type\": { \"1", "= { \"name\": \"ebu\", \"date_order\": \"DMY\", \"january\": [ \"mweri wa", "\" \", \".\", \",\", \";\", \"-\", \"/\", \"'\", \"|\", \"@\",", "wa kanana\", \"knn\" ], \"september\": [ \"mweri wa kenda\", \"ken\"", "month\": [ \"next month\" ], \"1 week ago\": [ \"last", "[ \"this month\" ], \"in 1 month\": [ \"next month\"", "\"friday\": [ \"njumaa\", \"maa\" ], \"saturday\": [ \"njumamothii\", \"nmm\" ],", "\"0 hour ago\": [ \"this hour\" ], \"0 minute ago\":", "year\" ], \"in 1 year\": [ \"next year\" ], \"1", "], \"in 1 week\": [ \"next week\" ], \"1 day", "\"mug\" ], \"august\": [ \"mweri wa kanana\", \"knn\" ], \"september\":", "\"pm\": [ \"ut\" ], \"year\": [ \"mwaka\" ], \"month\": [", "[ \"this minute\" ], \"0 second ago\": [ \"now\" ]", "\";\", \"-\", \"/\", \"'\", \"|\", \"@\", \"[\", \"]\", \",\" ]", "[ \"ĩgoro\" ], \"0 day ago\": [ \"ũmũnthĩ\" ], \"in", "\"kan\" ], \"may\": [ \"mweri wa gatano\", \"gat\" ], \"june\":", "[ \"ut\" ], \"year\": [ \"mwaka\" ], \"month\": [ \"mweri\"", "\"next month\" ], \"1 week ago\": [ \"last week\" ],", "ago\": [ \"last year\" ], \"0 year ago\": [ \"this", "\"kiumia\", \"kma\" ], \"am\": [ \"ki\" ], \"pm\": [ \"ut\"", "\"ine\" ], \"wednesday\": [ \"njumatano\", \"tan\" ], \"thursday\": [ \"aramithi\",", "kenda\", \"ken\" ], \"october\": [ \"mweri wa ikũmi\", \"iku\" ],", "\"mweri wa gatano\", \"gat\" ], \"june\": [ \"mweri wa gatantatũ\",", "], \"october\": [ \"mweri wa ikũmi\", \"iku\" ], \"november\": [", "[ \"njumamothii\", \"nmm\" ], \"sunday\": [ \"kiumia\", \"kma\" ], \"am\":", "\"in 1 day\": [ \"rũciũ\" ], \"0 hour ago\": [", "\".\", \",\", \";\", \"-\", \"/\", \"'\", \"|\", \"@\", \"[\", \"]\",", "month\" ], \"in 1 month\": [ \"next month\" ], \"1", "week\": [ \"next week\" ], \"1 day ago\": [ \"ĩgoro\"", "], \"0 hour ago\": [ \"this hour\" ], \"0 minute", "wa kaĩri\", \"kai\" ], \"march\": [ \"mweri wa kathatũ\", \"kat\"", "\"sekondi\" ], \"relative-type\": { \"1 year ago\": [ \"last year\"", "year ago\": [ \"this year\" ], \"in 1 year\": [", "\"august\": [ \"mweri wa kanana\", \"knn\" ], \"september\": [ \"mweri", "\"tan\" ], \"thursday\": [ \"aramithi\", \"arm\" ], \"friday\": [ \"njumaa\",", "\"this minute\" ], \"0 second ago\": [ \"now\" ] },", "wa mbere\", \"mbe\" ], \"february\": [ \"mweri wa kaĩri\", \"kai\"", "mbere\", \"mbe\" ], \"february\": [ \"mweri wa kaĩri\", \"kai\" ],", "], \"september\": [ \"mweri wa kenda\", \"ken\" ], \"october\": [", "[ \"mweri wa ikũmi na ũmwe\", \"imw\" ], \"december\": [", "\"year\": [ \"mwaka\" ], \"month\": [ \"mweri\" ], \"week\": [", "{ \"1 year ago\": [ \"last year\" ], \"0 year", "\"locale_specific\": {}, \"skip\": [ \" \", \".\", \",\", \";\", \"-\",", "\"mweri wa ikũmi\", \"iku\" ], \"november\": [ \"mweri wa ikũmi", "\"mweri wa kathatũ\", \"kat\" ], \"april\": [ \"mweri wa kana\",", "\"this week\" ], \"in 1 week\": [ \"next week\" ],", "[ \"mweri wa mbere\", \"mbe\" ], \"february\": [ \"mweri wa", "1 year\": [ \"next year\" ], \"1 month ago\": [", "], \"1 month ago\": [ \"last month\" ], \"0 month", "\"in 1 year\": [ \"next year\" ], \"1 month ago\":", "\"this month\" ], \"in 1 month\": [ \"next month\" ],", "\"sunday\": [ \"kiumia\", \"kma\" ], \"am\": [ \"ki\" ], \"pm\":", "\"mweri wa kenda\", \"ken\" ], \"october\": [ \"mweri wa ikũmi\",", "\"in 1 week\": [ \"next week\" ], \"1 day ago\":", "\"ken\" ], \"october\": [ \"mweri wa ikũmi\", \"iku\" ], \"november\":", "], \"0 day ago\": [ \"ũmũnthĩ\" ], \"in 1 day\":", "year\": [ \"next year\" ], \"1 month ago\": [ \"last", "na ũmwe\", \"imw\" ], \"december\": [ \"mweri wa ikũmi na", "{}, \"skip\": [ \" \", \".\", \",\", \";\", \"-\", \"/\",", "], \"0 second ago\": [ \"now\" ] }, \"locale_specific\": {},", "], \"year\": [ \"mwaka\" ], \"month\": [ \"mweri\" ], \"week\":", "minute\" ], \"0 second ago\": [ \"now\" ] }, \"locale_specific\":", "[ \"last month\" ], \"0 month ago\": [ \"this month\"", "ago\": [ \"ĩgoro\" ], \"0 day ago\": [ \"ũmũnthĩ\" ],", "[ \"mweri wa kathatũ\", \"kat\" ], \"april\": [ \"mweri wa", "\"july\": [ \"mweri wa mũgwanja\", \"mug\" ], \"august\": [ \"mweri", "], \"second\": [ \"sekondi\" ], \"relative-type\": { \"1 year ago\":", "ago\": [ \"this minute\" ], \"0 second ago\": [ \"now\"", "second ago\": [ \"now\" ] }, \"locale_specific\": {}, \"skip\": [", "\"relative-type\": { \"1 year ago\": [ \"last year\" ], \"0", "wa mũgwanja\", \"mug\" ], \"august\": [ \"mweri wa kanana\", \"knn\"", "ago\": [ \"this hour\" ], \"0 minute ago\": [ \"this", "{ \"name\": \"ebu\", \"date_order\": \"DMY\", \"january\": [ \"mweri wa mbere\",", "\"1 year ago\": [ \"last year\" ], \"0 year ago\":", "], \"1 week ago\": [ \"last week\" ], \"0 week", "\"april\": [ \"mweri wa kana\", \"kan\" ], \"may\": [ \"mweri", "day ago\": [ \"ĩgoro\" ], \"0 day ago\": [ \"ũmũnthĩ\"", "\"rũciũ\" ], \"0 hour ago\": [ \"this hour\" ], \"0", "wa ikũmi na ũmwe\", \"imw\" ], \"december\": [ \"mweri wa", "\"imw\" ], \"december\": [ \"mweri wa ikũmi na kaĩrĩ\", \"igi\"", "\"knn\" ], \"september\": [ \"mweri wa kenda\", \"ken\" ], \"october\":", "[ \"mweri wa kanana\", \"knn\" ], \"september\": [ \"mweri wa", "\"kma\" ], \"am\": [ \"ki\" ], \"pm\": [ \"ut\" ],", "[ \"ki\" ], \"pm\": [ \"ut\" ], \"year\": [ \"mwaka\"", "\"mweri wa kanana\", \"knn\" ], \"september\": [ \"mweri wa kenda\",", "ago\": [ \"ũmũnthĩ\" ], \"in 1 day\": [ \"rũciũ\" ],", "], \"wednesday\": [ \"njumatano\", \"tan\" ], \"thursday\": [ \"aramithi\", \"arm\"", "], \"friday\": [ \"njumaa\", \"maa\" ], \"saturday\": [ \"njumamothii\", \"nmm\"", "ũmwe\", \"imw\" ], \"december\": [ \"mweri wa ikũmi na kaĩrĩ\",", "ago\": [ \"this year\" ], \"in 1 year\": [ \"next", "[ \"mweri wa gatano\", \"gat\" ], \"june\": [ \"mweri wa", "month\" ], \"1 week ago\": [ \"last week\" ], \"0", "hour ago\": [ \"this hour\" ], \"0 minute ago\": [", "[ \"njumatatu\", \"tat\" ], \"tuesday\": [ \"njumaine\", \"ine\" ], \"wednesday\":", "[ \"next week\" ], \"1 day ago\": [ \"ĩgoro\" ],", "\"saturday\": [ \"njumamothii\", \"nmm\" ], \"sunday\": [ \"kiumia\", \"kma\" ],", "[ \"now\" ] }, \"locale_specific\": {}, \"skip\": [ \" \",", "kaĩri\", \"kai\" ], \"march\": [ \"mweri wa kathatũ\", \"kat\" ],", "\"minute\": [ \"ndagĩka\" ], \"second\": [ \"sekondi\" ], \"relative-type\": {", "\"mweri wa gatantatũ\", \"gan\" ], \"july\": [ \"mweri wa mũgwanja\",", "\"now\" ] }, \"locale_specific\": {}, \"skip\": [ \" \", \".\",", "\"next year\" ], \"1 month ago\": [ \"last month\" ],", "], \"week\": [ \"kiumia\" ], \"day\": [ \"mũthenya\" ], \"hour\":", "\"december\": [ \"mweri wa ikũmi na kaĩrĩ\", \"igi\" ], \"monday\":", "[ \"mweri wa gatantatũ\", \"gan\" ], \"july\": [ \"mweri wa", "week ago\": [ \"last week\" ], \"0 week ago\": [", "\"-\", \"/\", \"'\", \"|\", \"@\", \"[\", \"]\", \",\" ] }", "\",\", \";\", \"-\", \"/\", \"'\", \"|\", \"@\", \"[\", \"]\", \",\"", "\"gan\" ], \"july\": [ \"mweri wa mũgwanja\", \"mug\" ], \"august\":", "\"thursday\": [ \"aramithi\", \"arm\" ], \"friday\": [ \"njumaa\", \"maa\" ],", "[ \"mweri wa kana\", \"kan\" ], \"may\": [ \"mweri wa", "mũgwanja\", \"mug\" ], \"august\": [ \"mweri wa kanana\", \"knn\" ],", "], \"november\": [ \"mweri wa ikũmi na ũmwe\", \"imw\" ],", "[ \"rũciũ\" ], \"0 hour ago\": [ \"this hour\" ],", "minute ago\": [ \"this minute\" ], \"0 second ago\": [", "], \"relative-type\": { \"1 year ago\": [ \"last year\" ],", "[ \"next month\" ], \"1 week ago\": [ \"last week\"", "[ \"aramithi\", \"arm\" ], \"friday\": [ \"njumaa\", \"maa\" ], \"saturday\":", "[ \"mweri wa ikũmi na kaĩrĩ\", \"igi\" ], \"monday\": [", "\"last week\" ], \"0 week ago\": [ \"this week\" ],", "gatano\", \"gat\" ], \"june\": [ \"mweri wa gatantatũ\", \"gan\" ],", "\"iku\" ], \"november\": [ \"mweri wa ikũmi na ũmwe\", \"imw\"", "\"njumaa\", \"maa\" ], \"saturday\": [ \"njumamothii\", \"nmm\" ], \"sunday\": [", "\"nmm\" ], \"sunday\": [ \"kiumia\", \"kma\" ], \"am\": [ \"ki\"", "\"igi\" ], \"monday\": [ \"njumatatu\", \"tat\" ], \"tuesday\": [ \"njumaine\",", "kanana\", \"knn\" ], \"september\": [ \"mweri wa kenda\", \"ken\" ],", "\"ndagĩka\" ], \"second\": [ \"sekondi\" ], \"relative-type\": { \"1 year", "[ \"this year\" ], \"in 1 year\": [ \"next year\"", "], \"0 week ago\": [ \"this week\" ], \"in 1", "kaĩrĩ\", \"igi\" ], \"monday\": [ \"njumatatu\", \"tat\" ], \"tuesday\": [", "\"ebu\", \"date_order\": \"DMY\", \"january\": [ \"mweri wa mbere\", \"mbe\" ],", "week\" ], \"in 1 week\": [ \"next week\" ], \"1", "-*- coding: utf-8 -*- info = { \"name\": \"ebu\", \"date_order\":", "\"kat\" ], \"april\": [ \"mweri wa kana\", \"kan\" ], \"may\":", "\"mweri wa ikũmi na ũmwe\", \"imw\" ], \"december\": [ \"mweri", "[ \"ũmũnthĩ\" ], \"in 1 day\": [ \"rũciũ\" ], \"0", "[ \" \", \".\", \",\", \";\", \"-\", \"/\", \"'\", \"|\",", "[ \"njumatano\", \"tan\" ], \"thursday\": [ \"aramithi\", \"arm\" ], \"friday\":", "[ \"njumaine\", \"ine\" ], \"wednesday\": [ \"njumatano\", \"tan\" ], \"thursday\":", "[ \"mwaka\" ], \"month\": [ \"mweri\" ], \"week\": [ \"kiumia\"", "year\" ], \"0 year ago\": [ \"this year\" ], \"in", "1 day\": [ \"rũciũ\" ], \"0 hour ago\": [ \"this", "\"kai\" ], \"march\": [ \"mweri wa kathatũ\", \"kat\" ], \"april\":", "[ \"mweri\" ], \"week\": [ \"kiumia\" ], \"day\": [ \"mũthenya\"", "\"ĩgoro\" ], \"0 day ago\": [ \"ũmũnthĩ\" ], \"in 1", "\"may\": [ \"mweri wa gatano\", \"gat\" ], \"june\": [ \"mweri", "\"tuesday\": [ \"njumaine\", \"ine\" ], \"wednesday\": [ \"njumatano\", \"tan\" ],", "], \"thursday\": [ \"aramithi\", \"arm\" ], \"friday\": [ \"njumaa\", \"maa\"", "wa kenda\", \"ken\" ], \"october\": [ \"mweri wa ikũmi\", \"iku\"", "[ \"njumaa\", \"maa\" ], \"saturday\": [ \"njumamothii\", \"nmm\" ], \"sunday\":", "\"gat\" ], \"june\": [ \"mweri wa gatantatũ\", \"gan\" ], \"july\":", "\"0 year ago\": [ \"this year\" ], \"in 1 year\":", "[ \"last week\" ], \"0 week ago\": [ \"this week\"", "\"mwaka\" ], \"month\": [ \"mweri\" ], \"week\": [ \"kiumia\" ],", "\"0 month ago\": [ \"this month\" ], \"in 1 month\":", "\"day\": [ \"mũthenya\" ], \"hour\": [ \"ithaa\" ], \"minute\": [", "\"mũthenya\" ], \"hour\": [ \"ithaa\" ], \"minute\": [ \"ndagĩka\" ],", "\"june\": [ \"mweri wa gatantatũ\", \"gan\" ], \"july\": [ \"mweri", "\"in 1 month\": [ \"next month\" ], \"1 week ago\":", "\"ki\" ], \"pm\": [ \"ut\" ], \"year\": [ \"mwaka\" ],", "[ \"kiumia\" ], \"day\": [ \"mũthenya\" ], \"hour\": [ \"ithaa\"", "day ago\": [ \"ũmũnthĩ\" ], \"in 1 day\": [ \"rũciũ\"", "[ \"ithaa\" ], \"minute\": [ \"ndagĩka\" ], \"second\": [ \"sekondi\"", "\"njumatatu\", \"tat\" ], \"tuesday\": [ \"njumaine\", \"ine\" ], \"wednesday\": [", "[ \"sekondi\" ], \"relative-type\": { \"1 year ago\": [ \"last", "\"0 second ago\": [ \"now\" ] }, \"locale_specific\": {}, \"skip\":", "], \"august\": [ \"mweri wa kanana\", \"knn\" ], \"september\": [", "], \"saturday\": [ \"njumamothii\", \"nmm\" ], \"sunday\": [ \"kiumia\", \"kma\"", "[ \"next year\" ], \"1 month ago\": [ \"last month\"", "day\": [ \"rũciũ\" ], \"0 hour ago\": [ \"this hour\"", "], \"0 minute ago\": [ \"this minute\" ], \"0 second", "\"am\": [ \"ki\" ], \"pm\": [ \"ut\" ], \"year\": [", "-*- info = { \"name\": \"ebu\", \"date_order\": \"DMY\", \"january\": [", "], \"april\": [ \"mweri wa kana\", \"kan\" ], \"may\": [", "\"njumatano\", \"tan\" ], \"thursday\": [ \"aramithi\", \"arm\" ], \"friday\": [", "ago\": [ \"this month\" ], \"in 1 month\": [ \"next", "[ \"mũthenya\" ], \"hour\": [ \"ithaa\" ], \"minute\": [ \"ndagĩka\"", "kana\", \"kan\" ], \"may\": [ \"mweri wa gatano\", \"gat\" ],", "coding: utf-8 -*- info = { \"name\": \"ebu\", \"date_order\": \"DMY\",", "], \"july\": [ \"mweri wa mũgwanja\", \"mug\" ], \"august\": [", "], \"0 month ago\": [ \"this month\" ], \"in 1", "ikũmi na ũmwe\", \"imw\" ], \"december\": [ \"mweri wa ikũmi", "ago\": [ \"this week\" ], \"in 1 week\": [ \"next", "ago\": [ \"last week\" ], \"0 week ago\": [ \"this", "1 week\": [ \"next week\" ], \"1 day ago\": [", "], \"am\": [ \"ki\" ], \"pm\": [ \"ut\" ], \"year\":", "], \"march\": [ \"mweri wa kathatũ\", \"kat\" ], \"april\": [", "\"ut\" ], \"year\": [ \"mwaka\" ], \"month\": [ \"mweri\" ],", "\"skip\": [ \" \", \".\", \",\", \";\", \"-\", \"/\", \"'\",", "], \"monday\": [ \"njumatatu\", \"tat\" ], \"tuesday\": [ \"njumaine\", \"ine\"", "[ \"mweri wa kaĩri\", \"kai\" ], \"march\": [ \"mweri wa", "], \"tuesday\": [ \"njumaine\", \"ine\" ], \"wednesday\": [ \"njumatano\", \"tan\"", "wa ikũmi\", \"iku\" ], \"november\": [ \"mweri wa ikũmi na", "\"february\": [ \"mweri wa kaĩri\", \"kai\" ], \"march\": [ \"mweri", "\"january\": [ \"mweri wa mbere\", \"mbe\" ], \"february\": [ \"mweri", "\"0 minute ago\": [ \"this minute\" ], \"0 second ago\":", "week ago\": [ \"this week\" ], \"in 1 week\": [", "\"tat\" ], \"tuesday\": [ \"njumaine\", \"ine\" ], \"wednesday\": [ \"njumatano\",", "wa gatantatũ\", \"gan\" ], \"july\": [ \"mweri wa mũgwanja\", \"mug\"", "], \"pm\": [ \"ut\" ], \"year\": [ \"mwaka\" ], \"month\":", "month\" ], \"0 month ago\": [ \"this month\" ], \"in", "], \"june\": [ \"mweri wa gatantatũ\", \"gan\" ], \"july\": [", "\"name\": \"ebu\", \"date_order\": \"DMY\", \"january\": [ \"mweri wa mbere\", \"mbe\"", "# -*- coding: utf-8 -*- info = { \"name\": \"ebu\",", "\"mweri wa mbere\", \"mbe\" ], \"february\": [ \"mweri wa kaĩri\",", "ikũmi na kaĩrĩ\", \"igi\" ], \"monday\": [ \"njumatatu\", \"tat\" ],", "\"kiumia\" ], \"day\": [ \"mũthenya\" ], \"hour\": [ \"ithaa\" ],", "], \"minute\": [ \"ndagĩka\" ], \"second\": [ \"sekondi\" ], \"relative-type\":", "], \"in 1 day\": [ \"rũciũ\" ], \"0 hour ago\":", "] }, \"locale_specific\": {}, \"skip\": [ \" \", \".\", \",\",", "[ \"this week\" ], \"in 1 week\": [ \"next week\"", "\"ũmũnthĩ\" ], \"in 1 day\": [ \"rũciũ\" ], \"0 hour", "], \"day\": [ \"mũthenya\" ], \"hour\": [ \"ithaa\" ], \"minute\":", "wa kana\", \"kan\" ], \"may\": [ \"mweri wa gatano\", \"gat\"", "\"this year\" ], \"in 1 year\": [ \"next year\" ],", "ago\": [ \"now\" ] }, \"locale_specific\": {}, \"skip\": [ \"", "month ago\": [ \"last month\" ], \"0 month ago\": [", "year ago\": [ \"last year\" ], \"0 year ago\": [", "], \"0 year ago\": [ \"this year\" ], \"in 1", "\"mbe\" ], \"february\": [ \"mweri wa kaĩri\", \"kai\" ], \"march\":", "\"mweri wa mũgwanja\", \"mug\" ], \"august\": [ \"mweri wa kanana\",", "\"1 month ago\": [ \"last month\" ], \"0 month ago\":", "\"1 day ago\": [ \"ĩgoro\" ], \"0 day ago\": [", "[ \"mweri wa ikũmi\", \"iku\" ], \"november\": [ \"mweri wa", "[ \"kiumia\", \"kma\" ], \"am\": [ \"ki\" ], \"pm\": [", "], \"hour\": [ \"ithaa\" ], \"minute\": [ \"ndagĩka\" ], \"second\":", "hour\" ], \"0 minute ago\": [ \"this minute\" ], \"0", "\"monday\": [ \"njumatatu\", \"tat\" ], \"tuesday\": [ \"njumaine\", \"ine\" ],", "\"0 week ago\": [ \"this week\" ], \"in 1 week\":", "\"mweri\" ], \"week\": [ \"kiumia\" ], \"day\": [ \"mũthenya\" ],", "\"njumaine\", \"ine\" ], \"wednesday\": [ \"njumatano\", \"tan\" ], \"thursday\": [", "\"this hour\" ], \"0 minute ago\": [ \"this minute\" ],", "gatantatũ\", \"gan\" ], \"july\": [ \"mweri wa mũgwanja\", \"mug\" ],", "\"ithaa\" ], \"minute\": [ \"ndagĩka\" ], \"second\": [ \"sekondi\" ],", "wa gatano\", \"gat\" ], \"june\": [ \"mweri wa gatantatũ\", \"gan\"", "[ \"mweri wa mũgwanja\", \"mug\" ], \"august\": [ \"mweri wa", "week\" ], \"1 day ago\": [ \"ĩgoro\" ], \"0 day", "], \"in 1 year\": [ \"next year\" ], \"1 month", "utf-8 -*- info = { \"name\": \"ebu\", \"date_order\": \"DMY\", \"january\":", "[ \"mweri wa kenda\", \"ken\" ], \"october\": [ \"mweri wa", "<reponame>yuta-komura/vishnu # -*- coding: utf-8 -*- info = { \"name\":", "\"DMY\", \"january\": [ \"mweri wa mbere\", \"mbe\" ], \"february\": [", "\"month\": [ \"mweri\" ], \"week\": [ \"kiumia\" ], \"day\": [", "\"hour\": [ \"ithaa\" ], \"minute\": [ \"ndagĩka\" ], \"second\": [", "year\" ], \"1 month ago\": [ \"last month\" ], \"0", "kathatũ\", \"kat\" ], \"april\": [ \"mweri wa kana\", \"kan\" ],", "ago\": [ \"last month\" ], \"0 month ago\": [ \"this", "], \"sunday\": [ \"kiumia\", \"kma\" ], \"am\": [ \"ki\" ],", "\"september\": [ \"mweri wa kenda\", \"ken\" ], \"october\": [ \"mweri", "\"arm\" ], \"friday\": [ \"njumaa\", \"maa\" ], \"saturday\": [ \"njumamothii\",", "\"march\": [ \"mweri wa kathatũ\", \"kat\" ], \"april\": [ \"mweri", "\"second\": [ \"sekondi\" ], \"relative-type\": { \"1 year ago\": [", "\", \".\", \",\", \";\", \"-\", \"/\", \"'\", \"|\", \"@\", \"[\",", "\"next week\" ], \"1 day ago\": [ \"ĩgoro\" ], \"0", "wa ikũmi na kaĩrĩ\", \"igi\" ], \"monday\": [ \"njumatatu\", \"tat\"", "\"last year\" ], \"0 year ago\": [ \"this year\" ],", "month ago\": [ \"this month\" ], \"in 1 month\": [", "1 month\": [ \"next month\" ], \"1 week ago\": [", "\"mweri wa ikũmi na kaĩrĩ\", \"igi\" ], \"monday\": [ \"njumatatu\",", "ikũmi\", \"iku\" ], \"november\": [ \"mweri wa ikũmi na ũmwe\",", "\"october\": [ \"mweri wa ikũmi\", \"iku\" ], \"november\": [ \"mweri", "info = { \"name\": \"ebu\", \"date_order\": \"DMY\", \"january\": [ \"mweri", "\"njumamothii\", \"nmm\" ], \"sunday\": [ \"kiumia\", \"kma\" ], \"am\": [", "\"week\": [ \"kiumia\" ], \"day\": [ \"mũthenya\" ], \"hour\": [", "], \"1 day ago\": [ \"ĩgoro\" ], \"0 day ago\":", "\"maa\" ], \"saturday\": [ \"njumamothii\", \"nmm\" ], \"sunday\": [ \"kiumia\",", "\"wednesday\": [ \"njumatano\", \"tan\" ], \"thursday\": [ \"aramithi\", \"arm\" ],", "], \"december\": [ \"mweri wa ikũmi na kaĩrĩ\", \"igi\" ],", "], \"month\": [ \"mweri\" ], \"week\": [ \"kiumia\" ], \"day\":", "], \"in 1 month\": [ \"next month\" ], \"1 week", "week\" ], \"0 week ago\": [ \"this week\" ], \"in", "\"0 day ago\": [ \"ũmũnthĩ\" ], \"in 1 day\": [", "[ \"this hour\" ], \"0 minute ago\": [ \"this minute\"", "}, \"locale_specific\": {}, \"skip\": [ \" \", \".\", \",\", \";\",", "\"november\": [ \"mweri wa ikũmi na ũmwe\", \"imw\" ], \"december\":", "], \"may\": [ \"mweri wa gatano\", \"gat\" ], \"june\": [", "\"last month\" ], \"0 month ago\": [ \"this month\" ],", "\"mweri wa kana\", \"kan\" ], \"may\": [ \"mweri wa gatano\",", "\"1 week ago\": [ \"last week\" ], \"0 week ago\":", "], \"february\": [ \"mweri wa kaĩri\", \"kai\" ], \"march\": [", "\"mweri wa kaĩri\", \"kai\" ], \"march\": [ \"mweri wa kathatũ\",", "na kaĩrĩ\", \"igi\" ], \"monday\": [ \"njumatatu\", \"tat\" ], \"tuesday\":", "\"aramithi\", \"arm\" ], \"friday\": [ \"njumaa\", \"maa\" ], \"saturday\": [" ]
[ "datasets for LM training\"\"\" # flake8: noqa from deepa2.preptrain.t2tpreprocessor import", "DeepA2 datasets for LM training\"\"\" # flake8: noqa from deepa2.preptrain.t2tpreprocessor", "\"\"\"Preprocessing DeepA2 datasets for LM training\"\"\" # flake8: noqa from", "for LM training\"\"\" # flake8: noqa from deepa2.preptrain.t2tpreprocessor import T2TPreprocessor" ]
[ "python3 from setuptools import setup, find_packages setup(name='awspk', version='0.1', description='A aws", "setuptools import setup, find_packages setup(name='awspk', version='0.1', description='A aws cli pen", "version='0.1', description='A aws cli pen knife with loads of interested", "knife with loads of interested stuff', author='<NAME>', author_email='<EMAIL>', py_modules=['awspk'], license='LICENSE',", "setup(name='awspk', version='0.1', description='A aws cli pen knife with loads of", "find_packages setup(name='awspk', version='0.1', description='A aws cli pen knife with loads", "from setuptools import setup, find_packages setup(name='awspk', version='0.1', description='A aws cli", "cli pen knife with loads of interested stuff', author='<NAME>', author_email='<EMAIL>',", "pen knife with loads of interested stuff', author='<NAME>', author_email='<EMAIL>', py_modules=['awspk'],", "setup, find_packages setup(name='awspk', version='0.1', description='A aws cli pen knife with", "description='A aws cli pen knife with loads of interested stuff',", "with loads of interested stuff', author='<NAME>', author_email='<EMAIL>', py_modules=['awspk'], license='LICENSE', )", "import setup, find_packages setup(name='awspk', version='0.1', description='A aws cli pen knife", "aws cli pen knife with loads of interested stuff', author='<NAME>',", "#!/usr/bin/env python3 from setuptools import setup, find_packages setup(name='awspk', version='0.1', description='A" ]
[ "return Xlib.XK.keysym_to_string(keysym) def rebind_string(self, keysym, newstring): \"\"\"Change the translation of", "starting at first_keycount and no more than count.\"\"\" r =", "return self._atom_cache[atomname] r = request.InternAtom(display = self, name = atomname,", "index + 1 code = code + 1 ### ###", "r = request.GetSelectionOwner(display = self.display, selection = selection) return r.owner", "until the server is ungrabbed. Server grabbing should be avoided", "return r else: return None def list_extensions(self): \"\"\"Return a list", "Finalize extensions by creating new classes for class_name, dictionary in", "codes in self._keymap_syms.items(): i = 0 while i < len(codes):", "the extensions provided by the server.\"\"\" r = request.ListExtensions(display =", "the mapping is changed and X.MappingSuccess is returned.\"\"\" r =", "src_width = src_width, src_height = src_height, dst_x = x, dst_y", "logical number. If one of the buttons to be altered", "\"\"\"Modify the keyboard mapping, starting with first_keycode. keysyms is a", "of fonts matching pattern. No more than max_names will be", "pending_events(self): \"\"\"Return the number of events queued, i.e. the number", "\"\"\"Change the parameters provided as keyword arguments: key_click_percent The volume", "if it supports the extension name. If it is supported", "import ext from . import X # Xlib.protocol modules from", "X.RevertToParent, RevertToPointerRoot, or RevertToNone. See XSetInputFocus(3X11) for details. There is", "it was previously grabbed by this client.\"\"\" request.UngrabServer(display = self.display,", "next event is fetched from the server.\"\"\" return self.display.next_event() def", "self._atom_cache = {} def get_atom(self, atomname, only_if_exists=0): if atomname in", "used to insert an entry in the DictWrapper extension_event. \"\"\"", "server and the client library support the X extension named", "bytes of an IPv4 address.\"\"\" request.ChangeHosts(display = self.display, onerror =", "use of access control lists at connection setup if mode", "you address it as # extension_event.EXTENSION_EVENT_NAME rather than # extension_event[\"EXTENSION_EVENT_NAME\"]", "a timestamp or X.CurrentTime.\"\"\" request.AllowEvents(display = self.display, onerror = onerror,", "than max_names will be returned. Each list item represents one", "= self.list_extensions() # Go through all extension modules for extname,", "\"\"\"Return the next event. If there are no events queued,", "drawable from .xobject import fontable from .xobject import colormap from", "server.\"\"\" r = request.ListExtensions(display = self.display) return r.names def change_keyboard_mapping(self,", "= self.display.resource_classes[class_name] self.display.resource_classes[class_name] = type(origcls.__name__, (origcls,), dictionary) # Problem: we", "self.display, onerror = onerror) def ungrab_server(self, onerror = None): \"\"\"Release", "first_keycode+n at index i.\"\"\" request.ChangeKeyboardMapping(display = self.display, onerror = onerror,", "from the display name.\"\"\" return self.display.get_default_screen() ### ### Extension module", "by this client.\"\"\" request.UngrabServer(display = self.display, onerror = onerror) def", "as a list of 32 integers. List item N contains", "This method is provided to allow Display objects to be", "returned. Otherwise the mapping is changed and X.MappingSuccess is returned.\"\"\"", "# extension dict maintained in the display object setattr(self.extension_event, name,", "codes[i][1] if code >= first_keycode and code < lastcode: del", "than max_names will be returned.\"\"\" r = request.ListFonts(display = self.display,", "atom does not exist.\"\"\" r = request.GetAtomName(display = self.display, atom", "grid, and 3 is shift+alt grid. If that key entry", "activated. If it is X.ScreenSaverReset, the screen saver is deactivated", "def get_input_focus(self): \"\"\"Return an object with the following attributes: focus", "a copy of the GNU Lesser General Public # License", "newevt._code = code self.display.add_extension_event(code, newevt, subcode) if name is None:", "sym->code map code = first_keycode for syms in keysyms: index", "02111-1307 USA # Python modules import types # Python 2/3", "MappingNotify event is received, to update the keymap cache. evt", "= self.display, onerror = onerror, percent = percent) def change_pointer_control(self,", "that is bound to keysym. A list of tuples (keycode,", "mode = mode, time = time) def grab_server(self, onerror =", "A list of properties. Each entry has two attributes: name", "# of the License, or (at your option) any later", "window which currently holds the input focus, X.NONE or X.PointerRoot.", "tuples, starting at first_keycount and no more than count.\"\"\" r", "def set_modifier_mapping(self, keycodes): \"\"\"Set the keycodes for the eight modifiers", "= index + 1 code = code + 1 ###", "not changed. Otherwise the mapping is changed and X.MappingSuccess is", "def change_hosts(self, mode, host_family, host, onerror = None): \"\"\"mode is", "should be avoided as much as possible.\"\"\" request.GrabServer(display = self.display,", "on the lowest keycode.\"\"\" try: # Copy the map list,", "provided, that key will be modified, otherwise the global state", "high level display object # # Copyright (C) 2000 <NAME>", "a keysym, looking in entry index. Normally index 0 is", "1 # Get the new keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode,", "No more than max_names will be returned.\"\"\" r = request.ListFonts(display", "to if the focused window becomes not visible, and should", "keycode first_keycode+n at index i.\"\"\" request.ChangeKeyboardMapping(display = self.display, onerror =", "restores the default. led led_mode led_mode should be X.LedModeOff or", "event = event) def ungrab_pointer(self, time, onerror = None): \"\"\"elease", "with other sub-events and EVT is the event class. EVT", "self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected a MappingNotify event') def _update_keymap(self,", "first_keycount and no more than count.\"\"\" r = request.GetKeyboardMapping(display =", "responses in case someone creates this later if r.atom !=", "the following attributes: family X.FamilyInternet, X.FamilyDECnet, or X.FamilyChaos. name A", "be one of the following strings: resource drawable window pixmap", "0. If the extension is not supported, None is returned.\"\"\"", "= 0, onerror = None): \"\"\"Send a synthetic event to", "for class_name, dictionary in self.class_extension_dicts.items(): origcls = self.display.resource_classes[class_name] self.display.resource_classes[class_name] =", "the lowest index and lowest code is returned. If keysym", "the pointer is only moved if the specified rectangle in", "self.display) return r.names def change_keyboard_mapping(self, first_keycode, keysyms, onerror = None):", "If it is X.ScreenSaverReset, the screen saver is deactivated as", "onerror = onerror) def ungrab_server(self, onerror = None): \"\"\"Release the", "the extension is not supported, None is returned.\"\"\" r =", "grabbing should be avoided as much as possible.\"\"\" request.GrabServer(display =", "request.WarpPointer(display = self.display, onerror = onerror, src_window = src_window, dst_window", "self.display, onerror = onerror) def warp_pointer(self, x, y, src_window =", "supported, None is returned.\"\"\" r = request.QueryExtension(display = self.display, name", "cannot be mapped to the same logical number. If one", "r.fonts def list_fonts_with_info(self, pattern, max_names): \"\"\"Return a list of fonts", "percent = percent) def change_pointer_control(self, accel = None, threshold =", "called for all unhandled errors. handler should take two arguments", "set_input_focus(self, focus, revert_to, time, onerror = None): \"\"\"Set input focus", "the bell in Hz, -1 restores the default. bell_duration The", "self.class_extension_dicts[class_name][name] = method except KeyError: self.class_extension_dicts[class_name] = { name: method", "function can be used when a resource ID has been", "0, src_y = 0, src_width = 0, src_height = 0,", "is None: name = evt.__name__ setattr(self.extension_event, name, code) def extension_add_subevent(self,", "all_chars_exist font_ascent font_descent replies_hint See the descripton of XFontStruct in", "to the number of pixels. -1 restores the default.\"\"\" if", "unsigned value. \"\"\" return request.ListFontsWithInfo(display = self.display, max_names = max_names,", "change_pointer_control(self, accel = None, threshold = None, onerror = None):", "method = create_unbound_method(function, cls) # Maybe should check extension overrides", "create_unbound_method(function, cls) # Maybe should check extension overrides too try:", "def extension_add_subevent(self, code, subcode, evt, name = None): \"\"\"extension_add_subevent(code, evt,", "object, name, function): \"\"\"extension_add_method(object, name, function) Add an X extension", "min_bounds max_bounds min_char_or_byte2 max_char_or_byte2 default_char draw_direction min_byte1 max_byte1 all_chars_exist font_ascent", "onerror, do_accel = do_accel, do_thres = do_threshold, accel_num = accel_num,", "NEWSTRING is None, remove old translation if any. \"\"\" if", "[()] * 256 self._keymap_syms = {} self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode - self.display.info.min_keycode", "= self.display, max_names = max_names, pattern = pattern) def set_font_path(self,", "primary keycode that is bound to keysym. If several keycodes", "bit in the byte representing key 8N. If a bit", "the threshold number of pixels at once. To change the", "src_window = src_window, dst_window = X.NONE, src_x = src_x, src_y", "X.RetainPermanent and X.RetainTemporary.\"\"\" request.SetCloseDownMode(display = self.display, onerror = onerror, mode", "of the bell in milliseconds, -1 restores the default. led", "also a Window.send_event() method.\"\"\" request.SendEvent(display = self.display, onerror = onerror,", "The hosts on the access list. Each entry has the", "mode is X.ScreenSaverActive the screen saver is activated. If it", "'gc') } class _BaseDisplay(protocol_display.Display): resource_classes = _resource_baseclasses.copy() # Implement a", "requests on all other client connections until the server is", "list of the pointer button mappings. Entry N in the", "isinstance(evt, event.MappingNotify): if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise", "with the following attributes: focus The window which currently holds", "in self.class_extension_dicts.items(): origcls = self.display.resource_classes[class_name] self.display.resource_classes[class_name] = type(origcls.__name__, (origcls,), dictionary)", "None): \"\"\"Release some queued events. mode should be one of", "buttons to be altered are logically in the down state,", "self.display, onerror = onerror, propagate = propagate, destination = destination,", "as numerator/denumerator. threshold The number of pixels the pointer must", "0 for sym in syms: if sym != X.NoSymbol: if", "can be a window object, or X.PointerWindow or X.InputFocus. event", "byte representing key 8N.\"\"\" r = request.QueryKeymap(display = self.display) return", "the bits for keys 8N to 8N + 7 with", "0 else: do_threshold = 1 request.ChangePointerControl(display = self.display, onerror =", "\"\"\"Look up the primary keycode that is bound to keysym.", "it should be a 32-bit mask listing the LEDs that", "evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt) if name is None:", "returned. Each list item represents one font and has the", "event with a subcode, to a tuple of (event,subcode) #", "r = request.ListFonts(display = self.display, max_names = max_names, pattern =", "the keysyms bound to the key. # The keysym->keycode map", "onerror = None): \"\"\"Set input focus to focus, which should", "However, if src_window is a window the pointer is only", "and X.MappingSuccess is returned.\"\"\" r = request.SetPointerMapping(display = self.display, map", "X.NONE, src_x = 0, src_y = 0, src_width = 0,", "def get_font_path(self): \"\"\"Return the current font path as a list", "()) for class_name in class_list: cls = _resource_baseclasses[class_name] if hasattr(cls,", "an extension error. CODE is the numeric code, and ERR", "def get_keyboard_mapping(self, first_keycode, count): \"\"\"Return the current keyboard mapping as", "down. The vector is represented as a list of 32", "onerror = onerror, attrs = keys) def get_keyboard_control(self): \"\"\"Return an", "\"\"\"Do nothing but send a request to the server.\"\"\" request.NoOperation(display", "extension error. CODE is the numeric code, and ERR is", "0, propagate = 0, onerror = None): \"\"\"Send a synthetic", "Entry N in the list sets the logical button number", "def set_close_down_mode(self, mode, onerror = None): \"\"\"Control what will happen", "colormap cursor This function can be used when a resource", "X.DisableAccess.\"\"\" request.SetAccessControl(display = self.display, onerror = onerror, mode = mode)", "methods def __getattr__(self, attr): try: function = self.display_extension_methods[attr] return types.MethodType(function,", "the selection. Can raise BadAtom.\"\"\" r = request.GetSelectionOwner(display = self.display,", "than # extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event = rq.DictWrapper({}) exts = self.list_extensions() #", "request.GetKeyboardControl(display = self.display) def bell(self, percent = 0, onerror =", "be altered are logically in the down state, X.MappingBusy is", "should be a 32-bit mask listing the LEDs that should", "be replaced with the width of src_window - src_x. src_height", "r = request.SetPointerMapping(display = self.display, map = map) return r.status", "the bell. \"\"\" return request.GetKeyboardControl(display = self.display) def bell(self, percent", "{} def get_atom(self, atomname, only_if_exists=0): if atomname in self._atom_cache: return", "= onerror, percent = percent) def change_pointer_control(self, accel = None,", "Xlib.XK.keysym_to_string(keysym) def rebind_string(self, keysym, newstring): \"\"\"Change the translation of KEYSYM", "accel_denum = accel if threshold is None: do_threshold = 0", "evt should be the event object.\"\"\" if isinstance(evt, event.MappingNotify): if", "of pixels. -1 restores the default.\"\"\" if accel is None:", "NAME is omitted, it will be set to the name", "by Display.get_pointer_mapping(). map[n] sets the logical number for the physical", "-- high level display object # # Copyright (C) 2000", "name, only_if_exists = 0): \"\"\"Intern the string name, returning its", "a request to the server.\"\"\" request.NoOperation(display = self.display, onerror =", "the screen saver is deactivated as if device input had", "the eight modifiers X.Shift, X.Lock, X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4", "volume of key click, from 0 to 100. bell_percent bell_pitch", "atom number. If only_if_exists is true and the atom does", "should change. If led is not provided, all LEDs are", "# Xlib modules from . import error from . import", "### def intern_atom(self, name, only_if_exists = 0): \"\"\"Intern the string", "= { name: method } def extension_add_event(self, code, evt, name", "move the pointer to absolute coordinates, use Window.warp_pointer().\"\"\" request.WarpPointer(display =", "= percent) def change_pointer_control(self, accel = None, threshold = None,", "do_thres = do_threshold, accel_num = accel_num, accel_denum = accel_denum, threshold", "if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected a", "= src_height, dst_x = x, dst_y = y) def set_input_focus(self,", "used to connect to the server, either provided when creating", "initialiasation function mod.init(self, info) self.extensions.append(extname) # Finalize extensions by creating", "these values. properties A list of properties. Each entry has", "eight-element list where each entry is a list of the", "to CODE. If NAME is omitted, it will be set", "= first_keycode + count for keysym, codes in self._keymap_syms.items(): i", "by the offsets (x, y). However, if src_window is a", "the number of the default screen, extracted from the display", "onerror = None, **keys): \"\"\"Change the parameters provided as keyword", "\"\"\"If mode is X.ScreenSaverActive the screen saver is activated. If", "'cursor': cursor.Cursor, } _resource_hierarchy = { 'resource': ('drawable', 'window', 'pixmap',", "is returned.\"\"\" fid = self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display =", "keys) def get_keyboard_control(self): \"\"\"Return an object with the following attributes:", "is a list of logical button numbers. map must be", "as protocol_display from .protocol import request, event, rq # Xlib.xobjects", "returned.\"\"\" r = request.SetModifierMapping(display = self.display, keycodes = keycodes) return", "button mappings. Entry N in the list sets the logical", "extension_event.EXTENSION_EVENT_NAME rather than # extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event = rq.DictWrapper({}) exts =", "### Extension module interface ### def extension_add_method(self, object, name, function):", "access control list is used, X.DisableAccess otherwise. hosts The hosts", "request.ListFontsWithInfo(display = self.display, max_names = max_names, pattern = pattern) def", "get_keyboard_control(self): \"\"\"Return an object with the following attributes: global_auto_repeat X.AutoRepeatModeOn", "event, event_mask = 0, propagate = 0, onerror = None):", "to 8N + 7 with the least significant bit in", "= None): \"\"\"See XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display = self.display, onerror = onerror,", "= only_if_exists) return r.atom def get_atom(self, atom, only_if_exists = 0):", "return r.atom class Display(object): def __init__(self, display = None): self.display", "Problem: we have already created some objects without the #", "= src_width, src_height = src_height, dst_x = x, dst_y =", "the four bytes of an IPv4 address.\"\"\" request.ChangeHosts(display = self.display,", "= accel_denum, threshold = threshold) def get_pointer_control(self): \"\"\"Return an object", "of this event that shares the code ID with other", "request.SetInputFocus(display = self.display, onerror = onerror, revert_to = revert_to, focus", "# 59 Temple Place, # Suite 330, # Boston, MA", "'pixmap': drawable.Pixmap, 'fontable': fontable.Fontable, 'font': fontable.Font, 'gc': fontable.GC, 'colormap': colormap.Colormap,", "subcode, to a tuple of (event,subcode) # note this wraps", "If there are no events queued, it will block until", "resource_classes = _resource_baseclasses.copy() # Implement a cache of atom names,", "del codes[i] else: i = i + 1 # Get", "mode is X.EnableAccess, disable if it is X.DisableAccess.\"\"\" request.SetAccessControl(display =", "to 100. bell_percent bell_pitch bell_duration The volume, pitch and duration", "is logically in the down state, X.MappingBusy is returned and", "when a MappingNotify event is received, to update the keymap", "0 accel_num = 0 accel_denum = 0 else: do_accel =", "changed and X.MappingSuccess is returned.\"\"\" r = request.SetModifierMapping(display = self.display,", "self.keysym_translations[keysym] = newstring ### ### X requests ### def intern_atom(self,", "specified rectangle in src_window contains it. If src_width is 0", "list with 256 elements. # Each element represents a keycode,", "PARTICULAR PURPOSE. # See the GNU Lesser General Public License", "the server has processed all the queued requests. Use this", "8N. If a bit is on, autorepeat is enabled for", "event, rq # Xlib.xobjects modules from .xobject import resource from", "pass else: self.keysym_translations[keysym] = newstring ### ### X requests ###", "handler which will be called for all unhandled errors. handler", "self.display.add_extension_event(code, newevt) if name is None: name = evt.__name__ setattr(self.extension_event,", "the next event. If there are no events queued, it", "object, or fetched from the environmental variable $DISPLAY.\"\"\" return self.display.get_display_name()", "reversing the arguments return map(lambda x: (x[1], x[0]), self._keymap_syms[keysym]) except", "Window.warp_pointer().\"\"\" request.WarpPointer(display = self.display, onerror = onerror, src_window = src_window,", "i.\"\"\" request.ChangeKeyboardMapping(display = self.display, onerror = onerror, first_keycode = first_keycode,", "coded as above. bell_pitch The pitch of the bell in", "string corresponding to KEYSYM, or None if no reasonable translation", "self.display, keycodes = keycodes) return r.status def get_modifier_mapping(self): \"\"\"Return a", "evt, name = None): \"\"\"extension_add_subevent(code, evt, [name]) Add an extension", "return cls(self.display, fid, owner = 1) def list_fonts(self, pattern, max_names):", "name = name) if r.present: return r else: return None", "r.paths def query_extension(self, name): \"\"\"Ask the server if it supports", "pointer grab. See XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display = self.display, onerror = onerror,", "IndexError: return X.NoSymbol def keysym_to_keycode(self, keysym): \"\"\"Look up the primary", "= self.display, name = name) if r.present: return r else:", "None): self.display = _BaseDisplay(display) # Create the keymap cache self._keymap_codes", "onerror = onerror, mode = mode) def set_close_down_mode(self, mode, onerror", "\"\"\"Disable processing of requests on all other client connections until", "accel is None: do_accel = 0 accel_num = 0 accel_denum", "the X extension named extension.\"\"\" return extension in self.extensions def", "class _BaseDisplay(protocol_display.Display): resource_classes = _resource_baseclasses.copy() # Implement a cache of", "('window', 'pixmap'), 'fontable': ('font', 'gc') } class _BaseDisplay(protocol_display.Display): resource_classes =", "EVT is the event class. EVT will be cloned, and", "a dict that maps the event name to the code", "of key clicks between 0 (off) and 100 (load). -1", "the one with the lowest index and lowest code is", "warp_pointer(self, x, y, src_window = X.NONE, src_x = 0, src_y", "max_names = max_names, pattern = pattern) return r.fonts def list_fonts_with_info(self,", "self.display, onerror = onerror, src_window = src_window, dst_window = X.NONE,", "i + 1 # Get the new keyboard mapping keysyms", "X.NONE or X.PointerRoot. revert_to Where the focus will revert, one", "keysyms[n][i] will be assigned to keycode first_keycode+n at index i.\"\"\"", "never wait for events, and in threaded applications.\"\"\" self.display.flush() def", "list of byte values, the coding depends on family. For", "some objects without the # extensions: the screen roots and", "self._keymap_syms[keysym]) except KeyError: return [] def refresh_keyboard_mapping(self, evt): \"\"\"This method", "onerror = onerror, first_keycode = first_keycode, keysyms = keysyms) def", "of access control lists at connection setup if mode is", "X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes should be a", "### keymap cache implementation ### # The keycode->keysym map is", "add_extension_error(self, code, err): \"\"\"add_extension_error(code, err) Add an extension error. CODE", "def rebind_string(self, keysym, newstring): \"\"\"Change the translation of KEYSYM to", "= { 'resource': ('drawable', 'window', 'pixmap', 'fontable', 'font', 'gc', 'colormap',", "the default.\"\"\" if accel is None: do_accel = 0 accel_num", "keys 8N to 8N + 7 with the least significant", "\"\"\"Control what will happen with the client's resources at connection", "two arguments as a normal request error handler, but the", "the mapping is not changed. Otherwise the mapping is changed", "move before the acceleration kicks in.\"\"\" return request.GetPointerControl(display = self.display)", "focus The window which currently holds the input focus, X.NONE", "This library is distributed in the hope that it will", "name: method } def extension_add_event(self, code, evt, name = None):", "default. bell_duration The duration of the bell in milliseconds, -1", "request.UngrabServer(display = self.display, onerror = onerror) def warp_pointer(self, x, y,", "the same length as the list returned by Display.get_pointer_mapping(). map[n]", "# are keysyms. The values are a sorted list of", "should be the event object.\"\"\" if isinstance(evt, event.MappingNotify): if evt.request", "method should be called once when a MappingNotify event is", "and fetch it __import__('Xlib.ext.' + modname) mod = getattr(ext, modname)", "requests of this extension uses. first_event The base event code", "X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time", "count.\"\"\" r = request.GetKeyboardMapping(display = self.display, first_keycode = first_keycode, count", "restores the default.\"\"\" if accel is None: do_accel = 0", "X extension named extension.\"\"\" return extension in self.extensions def create_resource_object(self,", "\"\"\"Return a bit vector for the logical state of the", "is provided, that key will be modified, otherwise the global", "[name]) Add an extension subevent. CODE is the numeric code,", "raise AssertionError('attempting to replace display method: %s' % name) self.display_extension_methods[name]", "code, err): \"\"\"add_extension_error(code, err) Add an extension error. CODE is", "See XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display = self.display, onerror = onerror, cursor =", "either version 2.1 # of the License, or (at your", "is only moved if the specified rectangle in src_window contains", "representing key 8N. If a bit is on, autorepeat is", "saver is activated. If it is X.ScreenSaverReset, the screen saver", "display as protocol_display from .protocol import request, event, rq #", "when it is important that errors caused by a certain", "bell_percent bell_pitch bell_duration The volume, pitch and duration of the", "name A list of byte values, the coding depends on", "keysym): \"\"\"Look up the primary keycode that is bound to", "(event,subcode) # note this wraps the dict so you address", "return self.display.pending_events() def has_extension(self, extension): \"\"\"Check if both the server", "attribute _code of the new event class will be set", "CODE is the numeric code, and EVT is the event", "return [] def refresh_keyboard_mapping(self, evt): \"\"\"This method should be called", "same logical number. If one of the buttons to be", "should have received a copy of the GNU Lesser General", "first_keycode = first_keycode, count = count) return r.keysyms def change_keyboard_control(self,", "def query_extension(self, name): \"\"\"Ask the server if it supports the", "object setattr(self.extension_event, name, (code,subcode)) def add_extension_error(self, code, err): \"\"\"add_extension_error(code, err)", "the input focus, X.NONE or X.PointerRoot. revert_to Where the focus", "only_if_exists = only_if_exists) return r.atom def get_atom(self, atom, only_if_exists =", "the keycodes that is bound to keysym. A list of", "a string corresponding to KEYSYM, or None if no reasonable", "name) self.display_extension_methods[name] = function else: class_list = (object, ) +", "request.SetModifierMapping(display = self.display, keycodes = keycodes) return r.status def get_modifier_mapping(self):", "percent which is relative the base volume. See XBell(3X11).\"\"\" request.Bell(display", "a window, X.PointerRoot or X.NONE. revert_to specifies where the focus", "The default is X.DestroyAll, the other values are X.RetainPermanent and", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the", "If path is empty, the default font path of the", "Foundation; either version 2.1 # of the License, or (at", "strings. If path is empty, the default font path of", "bound to any key, 0 is returned.\"\"\" try: return self._keymap_syms[keysym][0][1]", "resource ID has been fetched e.g. from an resource or", "onerror, propagate = propagate, destination = destination, event_mask = event_mask,", "attributes is returned: major_opcode The major opcode that the requests", "the keyboard mapping, starting with first_keycode. keysyms is a list", "= request.GetFontPath(display = self.display) return r.paths def query_extension(self, name): \"\"\"Ask", "\"\"\"Return the number of events queued, i.e. the number of", "in a mapping, where the keys # are keysyms. The", "X.FamilyDECnet, or X.FamilyChaos. name A list of byte values, the", "client's resources at connection close. The default is X.DestroyAll, the", "= None, threshold = None, onerror = None): \"\"\"To change", "cursor _resource_baseclasses = { 'resource': resource.Resource, 'drawable': drawable.Drawable, 'window': drawable.Window,", "name is used to insert an entry in the DictWrapper", "def query_keymap(self): \"\"\"Return a bit vector for the logical state", "is a list of bytes. For the Internet family, it", "except (KeyError, IndexError): return 0 def keysym_to_keycodes(self, keysym): \"\"\"Look up", "or (at your option) any later version. # # This", "must move before the acceleration kicks in.\"\"\" return request.GetPointerControl(display =", "modules for extname, modname in ext.__extensions__: if extname in exts:", "'fontable': ('font', 'gc') } class _BaseDisplay(protocol_display.Display): resource_classes = _resource_baseclasses.copy() #", "name = None): \"\"\"extension_add_event(code, evt, [name]) Add an extension event.", "extension subevent. CODE is the numeric code, subcode is the", "src_y = src_y, src_width = src_width, src_height = src_height, dst_x", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "mapping is not changed. If the mapping violates some server", "all unhandled errors. handler should take two arguments as a", "as # extension_event.EXTENSION_EVENT_NAME rather than # extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event = rq.DictWrapper({})", "are no events queued, it will block until the next", "and secondarily on the lowest keycode.\"\"\" try: # Copy the", "is returned.\"\"\" r = request.InternAtom(display = self.display, name = name,", "the server is ungrabbed. Server grabbing should be avoided as", "= keycodes) return r.status def get_modifier_mapping(self): \"\"\"Return a list of", "r = request.SetModifierMapping(display = self.display, keycodes = keycodes) return r.status", "code ID with other sub-events and EVT is the event", "that modifier. If any changed key is logically in the", "def get_screen_saver(self): \"\"\"Return an object with the attributes timeout, interval,", "self.keysym_translations = {} # Find all supported extensions self.extensions =", "# a dict that maps the event name to the", "% (class_name, name)) method = create_unbound_method(function, cls) # Maybe should", "onerror) def ungrab_server(self, onerror = None): \"\"\"Release the server if", "argument. Resource objects should never be created by instantiating the", "is not bound to any key, 0 is returned.\"\"\" try:", "major_opcode The major opcode that the requests of this extension", "number 0 disables the button. Two physical buttons cannot be", "processing of requests on all other client connections until the", "\"\"\"Flush the request queue, building and sending the queued requests.", "the method, a string. FUNCTION is a normal function whose", "= request.GetSelectionOwner(display = self.display, selection = selection) return r.owner def", "the default error handler which will be called for all", "= { 'resource': resource.Resource, 'drawable': drawable.Drawable, 'window': drawable.Window, 'pixmap': drawable.Pixmap,", "under the terms of the GNU Lesser General Public License", "if atom does not exist.\"\"\" r = request.GetAtomName(display = self.display,", "cache self._keymap_codes = [()] * 256 self._keymap_syms = {} self._update_keymap(self.display.info.min_keycode,", "get_atom(self, atomname, only_if_exists=0): if atomname in self._atom_cache: return self._atom_cache[atomname] r", "type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt, subcode) if", "request.GetPointerControl(display = self.display) def set_screen_saver(self, timeout, interval, prefer_blank, allow_exposures, onerror", "the classes in protocol.events. See XSendEvent(3X11) for details. There is", "If led is provided, it should be a 32-bit mask", "def open_font(self, name): \"\"\"Open the font identifed by the pattern", "X.MappingSuccess is returned.\"\"\" r = request.SetModifierMapping(display = self.display, keycodes =", "bell at the volume percent which is relative the base", "# We need this to handle display extension methods def", "default error handler which will be called for all unhandled", "of all the extensions provided by the server.\"\"\" r =", "getattr(ext, modname) info = self.query_extension(extname) self.display.set_extension_major(extname, info.major_opcode) # Call initialiasation", "the second argument (the request) will be None. See section", "of EVT. This name is used to insert an entry", "each entry is a list of the keycodes that should", "is true and the atom does not already exist, it", "rq # Xlib.xobjects modules from .xobject import resource from .xobject", "event. CODE is the numeric code, and EVT is the", "y). However, if src_window is a window the pointer is", "the pointer relative its current position by the offsets (x,", "X.LedModeOff or X.LedModeOn. If led is provided, it should be", "\"\"\" s = self.keysym_translations.get(keysym) if s is not None: return", "the physical button N+1.\"\"\" r = request.GetPointerMapping(display = self.display) return", "return self.display.get_atom(atom, only_if_exists) def get_atom_name(self, atom): \"\"\"Look up the name", "normal function whose first argument is a 'self'. \"\"\" if", "_resource_hierarchy.get(object, ()) for class_name in class_list: cls = _resource_baseclasses[class_name] if", "0): \"\"\"Intern the string name, returning its atom number. If", "keysyms. keysyms[n][i] will be assigned to keycode first_keycode+n at index", "onerror, first_keycode = first_keycode, keysyms = keysyms) def get_keyboard_mapping(self, first_keycode,", "name and return its font object. If name does not", "the button. Two physical buttons cannot be mapped to the", "Server grabbing should be avoided as much as possible.\"\"\" request.GrabServer(display", "Python 2/3 compatibility. from six import create_unbound_method # Xlib modules", "are keysyms. The values are a sorted list of tuples", "display, freeing the resources that it holds.\"\"\" self.display.close() def set_error_handler(self,", "cursor.Cursor, } _resource_hierarchy = { 'resource': ('drawable', 'window', 'pixmap', 'fontable',", "first_keycode, keysyms = keysyms) def get_keyboard_mapping(self, first_keycode, count): \"\"\"Return the", "close(self): \"\"\"Close the display, freeing the resources that it holds.\"\"\"", "global_auto_repeat X.AutoRepeatModeOn or X.AutoRepeatModeOff. auto_repeats A list of 32 integers.", "is not changed. If the mapping violates some server restriction,", "Translations for keysyms to strings. self.keysym_translations = {} # Find", "== 'display': if hasattr(self, name): raise AssertionError('attempting to replace display", "also a Window.set_input_focus().\"\"\" request.SetInputFocus(display = self.display, onerror = onerror, revert_to", "return len(self.display.info.roots) def get_default_screen(self): \"\"\"Return the number of the default", "name, only_if_exists = only_if_exists) return r.atom def get_atom(self, atom, only_if_exists", "= 0 else: do_accel = 1 accel_num, accel_denum = accel", "that by reinstantiating them. for screen in self.display.info.roots: screen.root =", "i.e. the number of times that Display.next_event() can be called", "= mode) def set_close_down_mode(self, mode, onerror = None): \"\"\"Control what", "where each entry is a list of the keycodes that", "if the focused window becomes not visible, and should be", "= onerror, mode = mode) def set_close_down_mode(self, mode, onerror =", "without the # extensions: the screen roots and default colormaps.", "modified.\"\"\" request.ChangeKeyboardControl(display = self.display, onerror = onerror, attrs = keys)", "self.sync() if ec.get_error(): self.display.free_resource_id(fid) return None else: cls = self.display.get_resource_class('font',", "be created by instantiating the appropriate class directly, since any", "until the next event is fetched from the server.\"\"\" return", "err): \"\"\"add_extension_error(code, err) Add an extension error. CODE is the", "key is currently pressed down. The vector is represented as", "sync(self): \"\"\"Flush the queue and wait until the server has", "to refresh the keymap cache. \"\"\" # Delete all sym->code", "remove old translation if any. \"\"\" if newstring is None:", "def create_resource_object(self, type, id): \"\"\"Create a resource object of type", "a MappingNotify event is received, to update the keymap cache.", "code, and ERR is the error class. \"\"\" self.display.add_extension_error(code, err)", "a grabbed keyboard and any queued events. See XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display", "the other values are X.RetainPermanent and X.RetainTemporary.\"\"\" request.SetCloseDownMode(display = self.display,", "the descripton of XFontStruct in XGetFontProperty(3X11) for details on these", "a list of the keycodes that should be bound to", "bound to that modifier.\"\"\" r = request.GetModifierMapping(display = self.display) return", "256 self._keymap_syms = {} self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode - self.display.info.min_keycode + 1))", "name = None): \"\"\"extension_add_subevent(code, evt, [name]) Add an extension subevent.", "don't cache NONE responses in case someone creates this later", "{ 'resource': resource.Resource, 'drawable': drawable.Drawable, 'window': drawable.Window, 'pixmap': drawable.Pixmap, 'fontable':", "will be useful, # but WITHOUT ANY WARRANTY; without even", "a MappingNotify event') def _update_keymap(self, first_keycode, count): \"\"\"Internal function, called", "request.QueryKeymap(display = self.display) return r.map def open_font(self, name): \"\"\"Open the", "item represents one font and has the following properties: name", "font path as a list of strings.\"\"\" r = request.GetFontPath(display", "on all other client connections until the server is ungrabbed.", "in Hz, -1 restores the default. bell_duration The duration of", "volume, pitch and duration of the bell. \"\"\" return request.GetKeyboardControl(display", "mapping is changed and X.MappingSuccess is returned.\"\"\" r = request.SetPointerMapping(display", "self.display, onerror = onerror, mode = mode) def set_pointer_mapping(self, map):", "return self.display.fileno() def close(self): \"\"\"Close the display, freeing the resources", "up the primary keycode that is bound to keysym. If", "None): \"\"\"If mode is X.ScreenSaverActive the screen saver is activated.", "method. OBJECT is the type of object to add the", "\"\"\"Check if both the server and the client library support", "= None): \"\"\"Set the font path to path, which should", "in the byte representing key 8N. If a bit is", "newevt = type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt,", "def ungrab_keyboard(self, time, onerror = None): \"\"\"Ungrab a grabbed keyboard", "to which this keysym is bound, and # index is", "the global state for the entire keyboard will be modified.\"\"\"", "for the physical button N+1.\"\"\" r = request.GetPointerMapping(display = self.display)", "queue, building and sending the queued requests. This can be", "return request.ListFontsWithInfo(display = self.display, max_names = max_names, pattern = pattern)", "in the display object setattr(self.extension_event, name, (code,subcode)) def add_extension_error(self, code,", "of screens on the display.\"\"\" return len(self.display.info.roots) def get_default_screen(self): \"\"\"Return", "no more than count.\"\"\" r = request.GetKeyboardMapping(display = self.display, first_keycode", "auto_repeat_mode should be one of X.AutoRepeatModeOff, X.AutoRepeatModeOn, or X.AutoRepeatModeDefault. If", "received.\"\"\" request.ForceScreenSaver(display = self.display, onerror = onerror, mode = mode)", "screen_count(self): \"\"\"Return the total number of screens on the display.\"\"\"", "map is stored in a list with 256 elements. #", "becomes not visible, and should be X.RevertToParent, RevertToPointerRoot, or RevertToNone.", "provided to allow Display objects to be passed select.select().\"\"\" return", "will then move num/denum times the normal speed if it", "max_names, pattern = pattern) return r.fonts def list_fonts_with_info(self, pattern, max_names):", "See section Error Handling.\"\"\" self.display.set_error_handler(handler) def flush(self): \"\"\"Flush the request", "count): \"\"\"Return the current keyboard mapping as a list of", "= code self.display.add_extension_event(code, newevt, subcode) if name is None: name", "the pattern name and return its font object. If name", "only_if_exists = 0): \"\"\"Alias for intern_atom, using internal cache\"\"\" return", "This library is free software; you can redistribute it and/or", "from . import error from . import ext from .", "the changed codes lastcode = first_keycode + count for keysym,", "of eight lists, one for each modifier. The list can", "the following attributes is returned: major_opcode The major opcode that", "corresponding to KEYSYM, or None if no reasonable translation is", "a tuple of (event,subcode) # note this wraps the dict", "classes for class_name, dictionary in self.class_extension_dicts.items(): origcls = self.display.resource_classes[class_name] self.display.resource_classes[class_name]", "\"\"\"extension_add_method(object, name, function) Add an X extension module method. OBJECT", "= atomname, only_if_exists = only_if_exists) # don't cache NONE responses", "entry is a list of the keycodes that should be", "X.AsyncBoth, or X.SyncBoth. time should be a timestamp or X.CurrentTime.\"\"\"", "for details on these values. properties A list of properties.", "object.\"\"\" if isinstance(evt, event.MappingNotify): if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count)", "name = evt.__name__ # store subcodes as a tuple of", "the keycodes bound to that modifier.\"\"\" r = request.GetModifierMapping(display =", "_BaseDisplay(display) # Create the keymap cache self._keymap_codes = [()] *", "number of times that Display.next_event() can be called without blocking.\"\"\"", "path = path) def get_font_path(self): \"\"\"Return the current font path", "= request.QueryExtension(display = self.display, name = name) if r.present: return", "free software; you can redistribute it and/or # modify it", "focus, X.NONE or X.PointerRoot. revert_to Where the focus will revert,", "a Window.set_input_focus().\"\"\" request.SetInputFocus(display = self.display, onerror = onerror, revert_to =", "is treated in a similar way. To move the pointer", "def __getattr__(self, attr): try: function = self.display_extension_methods[attr] return types.MethodType(function, self)", "self.display.add_extension_event(code, newevt, subcode) if name is None: name = evt.__name__", "request.SendEvent(display = self.display, onerror = onerror, propagate = propagate, destination", "and 100 (load). -1 will restore default setting. bell_percent The", "onerror = onerror, percent = percent) def change_pointer_control(self, accel =", "focus = focus, time = time) def get_input_focus(self): \"\"\"Return an", "cursor This function can be used when a resource ID", "# Delete all sym->code maps for the changed codes lastcode", "# store subcodes as a tuple of (event code, subcode)", "self.display, onerror = onerror, revert_to = revert_to, focus = focus,", "r else: return None def list_extensions(self): \"\"\"Return a list of", "self.display) return r.map def open_font(self, name): \"\"\"Open the font identifed", "try: return self._keymap_syms[keysym][0][1] except (KeyError, IndexError): return 0 def keysym_to_keycodes(self,", "= self.keysym_translations.get(keysym) if s is not None: return s import", "self._atom_cache[atomname] = r.atom return r.atom class Display(object): def __init__(self, display", "AssertionError('attempting to replace display method: %s' % name) self.display_extension_methods[name] =", "= self.display) return r.map def set_modifier_mapping(self, keycodes): \"\"\"Set the keycodes", "key will be modified, otherwise the global state for the", "send a request to the server.\"\"\" request.NoOperation(display = self.display, onerror", "src_height, dst_x = x, dst_y = y) def set_input_focus(self, focus,", "See the GNU Lesser General Public License for more details.", "that owns selection (an atom), or X.NONE if there is", "modifier.\"\"\" r = request.GetModifierMapping(display = self.display) return r.keycodes def no_operation(self,", "is important that errors caused by a certain request is", "shift+alt grid. If that key entry is not bound, X.NoSymbol", "are # the keysyms bound to the key. # The", "\"\"\"Return an object with the following attributes: accel_num accel_denom The", "will be returned. Each list item represents one font and", "src_window, dst_window = X.NONE, src_x = src_x, src_y = src_y,", "button N+1.\"\"\" r = request.GetPointerMapping(display = self.display) return r.map def", "mode = mode) def set_close_down_mode(self, mode, onerror = None): \"\"\"Control", "self.display, name = name) if r.present: return r else: return", "'font': fontable.Font, 'gc': fontable.GC, 'colormap': colormap.Colormap, 'cursor': cursor.Cursor, } _resource_hierarchy", "def get_modifier_mapping(self): \"\"\"Return a list of eight lists, one for", "pattern, max_names): \"\"\"Return a list of font names matching pattern.", "for class_name in class_list: cls = _resource_baseclasses[class_name] if hasattr(cls, name):", "Free Software Foundation, Inc., # 59 Temple Place, # Suite", "creates this later if r.atom != X.NONE: self._atom_cache[atomname] = r.atom", "the new event class will be set to CODE. If", "can be called without blocking.\"\"\" return self.display.pending_events() def has_extension(self, extension):", "from an resource or a command line argument. Resource objects", "to NEWSTRING. If NEWSTRING is None, remove old translation if", "pattern, max_names): \"\"\"Return a list of fonts matching pattern. No", "# Python 2/3 compatibility. from six import create_unbound_method # Xlib", "{ 'resource': ('drawable', 'window', 'pixmap', 'fontable', 'font', 'gc', 'colormap', 'cursor'),", "else: cls = self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid, owner =", "type, id): \"\"\"Create a resource object of type for the", "return r.atom def get_atom(self, atom, only_if_exists = 0): \"\"\"Alias for", "it __import__('Xlib.ext.' + modname) mod = getattr(ext, modname) info =", "= self.display, onerror = onerror) def warp_pointer(self, x, y, src_window", "a string. FUNCTION is a normal function whose first argument", "was previously grabbed by this client.\"\"\" request.UngrabServer(display = self.display, onerror", "object. If name does not match any font, None is", "TypeError('expected a MappingNotify event') def _update_keymap(self, first_keycode, count): \"\"\"Internal function,", "_resource_baseclasses[class_name] if hasattr(cls, name): raise AssertionError('attempting to replace %s method:", "onerror) def warp_pointer(self, x, y, src_window = X.NONE, src_x =", "the byte representing key 8N. If a bit is on,", "You should have received a copy of the GNU Lesser", "[] self.class_extension_dicts = {} self.display_extension_methods = {} # a dict", "A list of tuples (keycode, index) is returned, sorted primarily", "\"\"\"Ask the server if it supports the extension name. If", "to send, instantiated from one of the classes in protocol.events.", "the 4 bytes of an IPv4 address. \"\"\" return request.ListHosts(display", "sym->code maps for the changed codes lastcode = first_keycode +", "else: self._keymap_syms[sym] = [(index, code)] index = index + 1", "allow_exposures, onerror = None): \"\"\"See XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display = self.display, onerror", "in the # extension dict maintained in the display object", ".xobject import drawable from .xobject import fontable from .xobject import", "screen(self, sno = None): if sno is None: return self.display.info.roots[self.display.default_screen]", "def _update_keymap(self, first_keycode, count): \"\"\"Internal function, called to refresh the", "i < len(codes): code = codes[i][1] if code >= first_keycode", "numbers. map must be of the same length as the", "deactivated as if device input had been received.\"\"\" request.ForceScreenSaver(display =", "focus, revert_to, time, onerror = None): \"\"\"Set input focus to", "is None: return self.display.info.roots[self.display.default_screen] else: return self.display.info.roots[sno] def screen_count(self): \"\"\"Return", "X.PointerRoot or X.NONE. revert_to specifies where the focus reverts to", "onerror = onerror, timeout = timeout, interval = interval, prefer_blank", "an entry in the DictWrapper extension_event. \"\"\" newevt = type(evt.__name__,", "is not changed. Otherwise the mapping is changed and X.MappingSuccess", "def get_atom_name(self, atom): \"\"\"Look up the name of atom, returning", "X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be a", "Will raise BadAtom if atom does not exist.\"\"\" r =", "has the following properties: name The name of the font.", "return r.names def change_keyboard_mapping(self, first_keycode, keysyms, onerror = None): \"\"\"Modify", "of the pointer button mappings. Entry N in the list", "of the License, or (at your option) any later version.", "= name) self.sync() if ec.get_error(): self.display.free_resource_id(fid) return None else: cls", "byte representing key 8N. If a bit is on, autorepeat", "return r.paths def query_extension(self, name): \"\"\"Ask the server if it", "display = None): self.display = _BaseDisplay(display) # Create the keymap", "type(origcls.__name__, (origcls,), dictionary) # Problem: we have already created some", "r = request.GetFontPath(display = self.display) return r.paths def query_extension(self, name):", "do_accel = do_accel, do_thres = do_threshold, accel_num = accel_num, accel_denum", "X.MappingSuccess is returned.\"\"\" r = request.SetPointerMapping(display = self.display, map =", "self.display, onerror = onerror, mode = mode, time = time)", "= code self.display.add_extension_event(code, newevt) if name is None: name =", "led_mode should be X.LedModeOff or X.LedModeOn. If led is provided,", "set to the name of EVT. This name is used", "update the keymap cache. evt should be the event object.\"\"\"", "onerror = None): \"\"\"Modify the keyboard mapping, starting with first_keycode.", "the event name to the code # or, when it's", "several keycodes are found, the one with the lowest index", "lowest index and secondarily on the lowest keycode.\"\"\" try: #", "keys # are keysyms. The values are a sorted list", "be a timestamp or X.CurrentTime.\"\"\" request.AllowEvents(display = self.display, onerror =", "\"\"\"Return the window that owns selection (an atom), or X.NONE", "if no reasonable translation is found. \"\"\" s = self.keysym_translations.get(keysym)", "a list of font names matching pattern. No more than", "request.ListHosts(display = self.display) def set_access_control(self, mode, onerror = None): \"\"\"Enable", "# Suite 330, # Boston, MA 02111-1307 USA # Python", "the environmental variable $DISPLAY.\"\"\" return self.display.get_display_name() def fileno(self): \"\"\"Returns the", "method is provided to allow Display objects to be passed", "the server if it supports the extension name. If it", "a command line argument. Resource objects should never be created", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "extension_add_method(self, object, name, function): \"\"\"extension_add_method(object, name, function) Add an X", "provided by the server.\"\"\" r = request.ListExtensions(display = self.display) return", "available. \"\"\" return self.display.resource_classes[type](self.display, id) # We need this to", "Boston, MA 02111-1307 USA # Python modules import types #", "the display name.\"\"\" return self.display.get_default_screen() ### ### Extension module interface", "1 indicates that the corresponding key is currently pressed down.", "RevertToPointerRoot, or RevertToNone. \"\"\" return request.GetInputFocus(display = self.display) def query_keymap(self):", "bound to that modifier. If any changed key is logically", "= None): \"\"\"Do nothing but send a request to the", "1 is shifted, 2 is alt grid, and 3 is", "will be assigned to keycode first_keycode+n at index i.\"\"\" request.ChangeKeyboardMapping(display", "= self.display, onerror = onerror, do_accel = do_accel, do_thres =", "{ name: method } def extension_add_event(self, code, evt, name =", "map must be of the same length as the list", "count) # Replace code->sym map with the new map self._keymap_codes[first_keycode:lastcode]", "return r.status def get_modifier_mapping(self): \"\"\"Return a list of eight lists,", "= 0, src_height = 0, onerror = None): \"\"\"Move the", "# You should have received a copy of the GNU", "of X.RevertToParent, RevertToPointerRoot, or RevertToNone. \"\"\" return request.GetInputFocus(display = self.display)", "from .xobject import drawable from .xobject import fontable from .xobject", "keycode->keysym map is stored in a list with 256 elements.", "entry index. Normally index 0 is unshifted, 1 is shifted,", "max_names): \"\"\"Return a list of font names matching pattern. No", "pointer and any queued events. See XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display = self.display,", "eight lists, one for each modifier. The list can be", "name of EVT. This name is used to insert an", "is returned: major_opcode The major opcode that the requests of", "info.major_opcode) # Call initialiasation function mod.init(self, info) self.extensions.append(extname) # Finalize", "'resource': resource.Resource, 'drawable': drawable.Drawable, 'window': drawable.Window, 'pixmap': drawable.Pixmap, 'fontable': fontable.Fontable,", "self.display.get_atom(atom, only_if_exists) def get_atom_name(self, atom): \"\"\"Look up the name of", "of atom names, used by Window objects when # dealing", "with first_keycode. keysyms is a list of tuples of keysyms.", "the same logical number. If one of the buttons to", "class will be set to CODE. If NAME is omitted,", "is unshifted, 1 is shifted, 2 is alt grid, and", "the name used to connect to the server, either provided", "return self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol def keysym_to_keycode(self, keysym): \"\"\"Look", "self.display, max_names = max_names, pattern = pattern) def set_font_path(self, path,", "the bell at the volume percent which is relative the", "list returned by Display.get_pointer_mapping(). map[n] sets the logical number for", "fontable from .xobject import colormap from .xobject import cursor _resource_baseclasses", "src_x, src_y = src_y, src_width = src_width, src_height = src_height,", "None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym) def rebind_string(self, keysym,", "prefer_blank, allow_exposures = allow_exposures) def get_screen_saver(self): \"\"\"Return an object with", "bytes. For the Internet family, it should be the four", "owner = 1) def list_fonts(self, pattern, max_names): \"\"\"Return a list", "XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display = self.display, onerror = onerror, timeout = timeout,", "translation of KEYSYM to NEWSTRING. If NEWSTRING is None, remove", "so on. The sublists list the keycodes bound to that", "or None if no reasonable translation is found. \"\"\" s", "strings.\"\"\" r = request.GetFontPath(display = self.display) return r.paths def query_extension(self,", "them. for screen in self.display.info.roots: screen.root = self.display.resource_classes['window'](self.display, screen.root.id) screen.default_colormap", "\"\"\"Move the pointer relative its current position by the offsets", "elements. # Each element represents a keycode, and the tuple", "a key to which this keysym is bound, and #", "keycodes are found, the one with the lowest index and", "of the method, a string. FUNCTION is a normal function", "mask listing the LEDs that should change. If led is", "the current font path as a list of strings.\"\"\" r", "first_keycode + count for keysym, codes in self._keymap_syms.items(): i =", "'font', 'gc', 'colormap', 'cursor'), 'drawable': ('window', 'pixmap'), 'fontable': ('font', 'gc')", "fontable font gc colormap cursor NAME is the name of", "focus to focus, which should be a window, X.PointerRoot or", "32 integers. List item N contains the bits for keys", "'colormap': colormap.Colormap, 'cursor': cursor.Cursor, } _resource_hierarchy = { 'resource': ('drawable',", "# Each element represents a keycode, and the tuple elements", "if s is not None: return s import Xlib.XK return", "IPv4 address. \"\"\" return request.ListHosts(display = self.display) def set_access_control(self, mode,", "corresponding key. led_mask A 32-bit mask indicating which LEDs are", "= None): \"\"\"Modify the keyboard mapping, starting with first_keycode. keysyms", "command line argument. Resource objects should never be created by", "will be replaced with the width of src_window - src_x.", "self.display, first_keycode = first_keycode, count = count) return r.keysyms def", "onerror = onerror, path = path) def get_font_path(self): \"\"\"Return the", "onerror = None): \"\"\"To change the pointer acceleration, set accel", "r.keysyms def change_keyboard_control(self, onerror = None, **keys): \"\"\"Change the parameters", "# # This library is distributed in the hope that", "be of the same length as the list returned by", "This function can be used when a resource ID has", "and ERR is the error class. \"\"\" self.display.add_extension_error(code, err) ###", "X.NONE: self._atom_cache[atomname] = r.atom return r.atom class Display(object): def __init__(self,", "mode should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer,", "the parameters provided as keyword arguments: key_click_percent The volume of", "= src_window, dst_window = X.NONE, src_x = src_x, src_y =", "it under the terms of the GNU Lesser General Public", "and X.RetainTemporary.\"\"\" request.SetCloseDownMode(display = self.display, onerror = onerror, mode =", "is changed and X.MappingSuccess is returned.\"\"\" r = request.SetModifierMapping(display =", "or X.NONE. revert_to specifies where the focus reverts to if", "from .xobject import fontable from .xobject import colormap from .xobject", "replace %s method: %s' % (class_name, name)) method = create_unbound_method(function,", "tuples (keycode, index) is returned, sorted primarily on the lowest", "the primary keycode that is bound to keysym. If several", "code >= first_keycode and code < lastcode: del codes[i] else:", "version. # # This library is distributed in the hope", "IPv4 address.\"\"\" request.ChangeHosts(display = self.display, onerror = onerror, mode =", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "as a list of strings.\"\"\" r = request.GetFontPath(display = self.display)", "# Xlib.protocol modules from .protocol import display as protocol_display from", "appropriate class directly, since any X extensions dynamically added by", "is the numeric code, and EVT is the event class.", "building and sending the queued requests. This can be necessary", "= self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid, owner = 1) def", "100 (load). -1 will restore default setting. bell_percent The base", "dict so you address it as # extension_event.EXTENSION_EVENT_NAME rather than", "to allow Display objects to be passed select.select().\"\"\" return self.display.fileno()", "('font', 'gc') } class _BaseDisplay(protocol_display.Display): resource_classes = _resource_baseclasses.copy() # Implement", "### def screen(self, sno = None): if sno is None:", "\"\"\"Convert a keycode to a keysym, looking in entry index.", "intern_atom(self, name, only_if_exists = 0): \"\"\"Intern the string name, returning", "if newstring is None: try: del self.keysym_translations[keysym] except KeyError: pass", "onerror, mode = mode, time = time) def grab_server(self, onerror", "the requests of this extension uses. first_event The base event", "primarily on the lowest index and secondarily on the lowest", "of strings.\"\"\" r = request.GetFontPath(display = self.display) return r.paths def", "changed. If the mapping violates some server restriction, X.MappingFailed is", "= self.display, onerror = onerror, attrs = keys) def get_keyboard_control(self):", "are on. key_click_percent The volume of key click, from 0", "FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser", "selection. Can raise BadAtom.\"\"\" r = request.GetSelectionOwner(display = self.display, selection", "path of the server will be restored.\"\"\" request.SetFontPath(display = self.display,", "\"\"\"Ring the bell at the volume percent which is relative", "number for the physical button n+1. Logical number 0 disables", "parameters of a pointer grab. See XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display = self.display,", "def get_pointer_mapping(self): \"\"\"Return a list of the pointer button mappings.", "{} # Find all supported extensions self.extensions = [] self.class_extension_dicts", "If led is not provided, all LEDs are changed. key", "onerror, cursor = cursor, time = time, event_mask = event_mask)", "mode = mode, host_family = host_family, host = host) def", "def no_operation(self, onerror = None): \"\"\"Do nothing but send a", "onerror = ec, fid = fid, name = name) self.sync()", "code, subcode) in the # extension dict maintained in the", "pattern name and return its font object. If name does", "host, onerror = None): \"\"\"mode is either X.HostInsert or X.HostDelete.", "Fix that by reinstantiating them. for screen in self.display.info.roots: screen.root", "\"\"\"Alias for intern_atom, using internal cache\"\"\" return self.display.get_atom(atom, only_if_exists) def", "a list of 32 integers. List item N contains the", "= pattern) return r.fonts def list_fonts_with_info(self, pattern, max_names): \"\"\"Return a", "modified, otherwise the global state for the entire keyboard will", "raise AttributeError(attr) ### ### display information retrieval ### def screen(self,", "an object with the following attributes: accel_num accel_denom The acceleration", "unshifted, 1 is shifted, 2 is alt grid, and 3", "object with the attributes timeout, interval, prefer_blanking, allow_exposures. See XGetScreenSaver(3X11)", "an resource or a command line argument. Resource objects should", "the screen saver is activated. If it is X.ScreenSaverReset, the", "this library; if not, write to the # Free Software", "= None): \"\"\"Send a synthetic event to the window destination", "for the integer id. type should be one of the", "cursor, time = time, event_mask = event_mask) def ungrab_keyboard(self, time,", "i = i + 1 # Get the new keyboard", "atom, returning it as a string. Will raise BadAtom if", "above. bell_pitch The pitch of the bell in Hz, -1", "font names matching pattern. No more than max_names will be", "= self.display) return r.map def open_font(self, name): \"\"\"Open the font", "= onerror, time = time) def allow_events(self, mode, time, onerror", "list can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on.", "be a 32-bit mask listing the LEDs that should change.", "the font path to path, which should be a list", "X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be", "be a eight-element list where each entry is a list", "mode, time, onerror = None): \"\"\"Release some queued events. mode", "host_family, host = host) def list_hosts(self): \"\"\"Return an object with", "The atom identifying this property. value A 32-bit unsigned value.", "name is None: name = evt.__name__ setattr(self.extension_event, name, code) def", "propagate = propagate, destination = destination, event_mask = event_mask, event", "def set_access_control(self, mode, onerror = None): \"\"\"Enable use of access", "self.display, onerror = onerror, time = time) def allow_events(self, mode,", "atom), or X.NONE if there is no owner for the", "is not supported, None is returned.\"\"\" r = request.QueryExtension(display =", "onerror, mode = mode) def set_close_down_mode(self, mode, onerror = None):", "library support the X extension named extension.\"\"\" return extension in", "subevent. CODE is the numeric code, subcode is the sub-ID", "Error Handling.\"\"\" self.display.set_error_handler(handler) def flush(self): \"\"\"Flush the request queue, building", "err) ### ### keymap cache implementation ### # The keycode->keysym", "be bound to that modifier. If any changed key is", "fid, owner = 1) def list_fonts(self, pattern, max_names): \"\"\"Return a", "that shares the code ID with other sub-events and EVT", "wait until the server has processed all the queued requests.", "= type(origcls.__name__, (origcls,), dictionary) # Problem: we have already created", "entry has two attributes: name The atom identifying this property.", "first_error The base error code if the extension have additional", "The base error code if the extension have additional errors,", "types # Python 2/3 compatibility. from six import create_unbound_method #", "LEDs that should change. If led is not provided, all", "access control lists at connection setup if mode is X.EnableAccess,", "and X.Mod5. keycodes should be a eight-element list where each", "restores the default. bell_duration The duration of the bell in", "= self.display, onerror = onerror, mode = mode) def force_screen_saver(self,", "path to path, which should be a list of strings.", "### ### client-internal keysym to string translations ### def lookup_string(self,", "X.RevertToParent, RevertToPointerRoot, or RevertToNone. \"\"\" return request.GetInputFocus(display = self.display) def", "return r.status def get_pointer_mapping(self): \"\"\"Return a list of the pointer", "= getattr(ext, modname) info = self.query_extension(extname) self.display.set_extension_major(extname, info.major_opcode) # Call", "atom does not already exist, it will not be created", "\"\"\" return request.ListFontsWithInfo(display = self.display, max_names = max_names, pattern =", "def get_atom(self, atomname, only_if_exists=0): if atomname in self._atom_cache: return self._atom_cache[atomname]", "= cursor, time = time, event_mask = event_mask) def ungrab_keyboard(self,", "next_event(self): \"\"\"Return the next event. If there are no events", "in the byte representing key 8N.\"\"\" r = request.QueryKeymap(display =", "bell_pitch bell_duration The volume, pitch and duration of the bell.", "extension_add_subevent(self, code, subcode, evt, name = None): \"\"\"extension_add_subevent(code, evt, [name])", "+ count for keysym, codes in self._keymap_syms.items(): i = 0", "**keys): \"\"\"Change the parameters provided as keyword arguments: key_click_percent The", "self.display.resource_classes[class_name] self.display.resource_classes[class_name] = type(origcls.__name__, (origcls,), dictionary) # Problem: we have", "attributes timeout, interval, prefer_blanking, allow_exposures. See XGetScreenSaver(3X11) for details.\"\"\" return", "keycodes) return r.status def get_modifier_mapping(self): \"\"\"Return a list of eight", "is a normal function whose first argument is a 'self'.", "is empty, the default font path of the server will", "at first_keycount and no more than count.\"\"\" r = request.GetKeyboardMapping(display", "of the same length as the list returned by Display.get_pointer_mapping().", "CODE. If NAME is omitted, it will be set to", "= keys) def get_keyboard_control(self): \"\"\"Return an object with the following", "self._keymap_syms.items(): i = 0 while i < len(codes): code =", ".xobject import resource from .xobject import drawable from .xobject import", "threshold The number of pixels the pointer must move before", "Maybe should check extension overrides too try: self.class_extension_dicts[class_name][name] = method", "do_accel = 0 accel_num = 0 accel_denum = 0 else:", "keysyms. The values are a sorted list of tuples with", "name = evt.__name__ setattr(self.extension_event, name, code) def extension_add_subevent(self, code, subcode,", "provided, it should be a 32-bit mask listing the LEDs", "a normal request error handler, but the second argument (the", "The keysym->keycode map is stored in a mapping, where the", "dealing with some ICCCM properties not defined in Xlib.Xatom def", "For the Internet family, it is the 4 bytes of", "normal speed if it moves beyond the threshold number of", "strings. self.keysym_translations = {} # Find all supported extensions self.extensions", "ERR is the error class. \"\"\" self.display.add_extension_error(code, err) ### ###", "one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or", "overrides too try: self.class_extension_dicts[class_name][name] = method except KeyError: self.class_extension_dicts[class_name] =", "two # elements each: (index, keycode) # keycode is the", "There is also a Window.send_event() method.\"\"\" request.SendEvent(display = self.display, onerror", "drawable.Window, 'pixmap': drawable.Pixmap, 'fontable': fontable.Fontable, 'font': fontable.Font, 'gc': fontable.GC, 'colormap':", "pointer is only moved if the specified rectangle in src_window", "of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is a list of", "this property. value A 32-bit unsigned value. \"\"\" return request.ListFontsWithInfo(display", "If any changed key is logically in the down state,", "the numeric code, subcode is the sub-ID of this event", "where the keys # are keysyms. The values are a", "this e.g. when it is important that errors caused by", "keysym): \"\"\"Return a string corresponding to KEYSYM, or None if", "matching pattern. No more than max_names will be returned.\"\"\" r", "the map list, reversing the arguments return map(lambda x: (x[1],", "map): \"\"\"Set the mapping of the pointer buttons. map is", "of key click, from 0 to 100. bell_percent bell_pitch bell_duration", "times that Display.next_event() can be called without blocking.\"\"\" return self.display.pending_events()", "not match any font, None is returned.\"\"\" fid = self.display.allocate_resource_id()", "the queue and wait until the server has processed all", "else: return self.display.info.roots[sno] def screen_count(self): \"\"\"Return the total number of", "the # extensions: the screen roots and default colormaps. #", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "changed key is logically in the down state, X.MappingBusy is", "assigned to keycode first_keycode+n at index i.\"\"\" request.ChangeKeyboardMapping(display = self.display,", "-1 restores the default. led led_mode led_mode should be X.LedModeOff", "it to the number of pixels. -1 restores the default.\"\"\"", "which will be called for all unhandled errors. handler should", "not supported, None is returned.\"\"\" r = request.QueryExtension(display = self.display,", "s = self.keysym_translations.get(keysym) if s is not None: return s", "None: try: del self.keysym_translations[keysym] except KeyError: pass else: self.keysym_translations[keysym] =", "is None: try: del self.keysym_translations[keysym] except KeyError: pass else: self.keysym_translations[keysym]", "default.\"\"\" if accel is None: do_accel = 0 accel_num =", "by the pattern name and return its font object. If", "through all extension modules for extname, modname in ext.__extensions__: if", "is distributed in the hope that it will be useful,", "src_window contains it. If src_width is 0 it will be", "if r.present: return r else: return None def list_extensions(self): \"\"\"Return", "If one of the buttons to be altered are logically", "value. \"\"\" return request.ListFontsWithInfo(display = self.display, max_names = max_names, pattern", "is returned. Otherwise the mapping is changed and X.MappingSuccess is", "error handler which will be called for all unhandled errors.", "add the function to, a string from this list: display", "to the key. # The keysym->keycode map is stored in", "is the type of object to add the function to,", "to that modifier.\"\"\" r = request.GetModifierMapping(display = self.display) return r.keycodes", "newstring ### ### X requests ### def intern_atom(self, name, only_if_exists", "physical buttons cannot be mapped to the same logical number.", "return r.keycodes def no_operation(self, onerror = None): \"\"\"Do nothing but", "= [] self.class_extension_dicts = {} self.display_extension_methods = {} # a", "Add an X extension module method. OBJECT is the type", "%s' % name) self.display_extension_methods[name] = function else: class_list = (object,", "is the sub-ID of this event that shares the code", "processed all the queued requests. Use this e.g. when it", "is returned, sorted primarily on the lowest index and secondarily", "= time, event_mask = event_mask) def ungrab_keyboard(self, time, onerror =", "of the following strings: resource drawable window pixmap fontable font", "in XGetFontProperty(3X11) for details on these values. properties A list", "attributes: name The atom identifying this property. value A 32-bit", "the list returned by Display.get_pointer_mapping(). map[n] sets the logical number", "refresh_keyboard_mapping(self, evt): \"\"\"This method should be called once when a", "a resource ID has been fetched e.g. from an resource", "get_keyboard_mapping(self, first_keycode, count): \"\"\"Return the current keyboard mapping as a", "2 is alt grid, and 3 is shift+alt grid. If", "properties not defined in Xlib.Xatom def __init__(self, *args, **keys): protocol_display.Display.__init__(self,", "the pointer to absolute coordinates, use Window.warp_pointer().\"\"\" request.WarpPointer(display = self.display,", "= error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror = ec, fid =", "evt): \"\"\"This method should be called once when a MappingNotify", "WITHOUT ANY WARRANTY; without even the implied warranty of #", "revert_to, time, onerror = None): \"\"\"Set input focus to focus,", "x[0]), self._keymap_syms[keysym]) except KeyError: return [] def refresh_keyboard_mapping(self, evt): \"\"\"This", "self.display, onerror = onerror, timeout = timeout, interval = interval,", "return types.MethodType(function, self) except KeyError: raise AttributeError(attr) ### ### display", "= self.display, onerror = onerror, revert_to = revert_to, focus =", "at connection setup if mode is X.EnableAccess, disable if it", "= method except KeyError: self.class_extension_dicts[class_name] = { name: method }", "Free Software Foundation; either version 2.1 # of the License,", "events. See XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display = self.display, onerror = onerror, time", "be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on. The sublists", "descriptor number of the underlying socket. This method is provided", "= None): \"\"\"Disable processing of requests on all other client", "represents one font and has the following properties: name The", "saver is deactivated as if device input had been received.\"\"\"", "from .xobject import resource from .xobject import drawable from .xobject", "def set_screen_saver(self, timeout, interval, prefer_blank, allow_exposures, onerror = None): \"\"\"See", "Window objects when # dealing with some ICCCM properties not", "the server.\"\"\" r = request.ListExtensions(display = self.display) return r.names def", "atomname in self._atom_cache: return self._atom_cache[atomname] r = request.InternAtom(display = self,", "type should be one of the following strings: resource drawable", "code for a key to which this keysym is bound,", "client connections until the server is ungrabbed. Server grabbing should", "e.g. when it is important that errors caused by a", "first_keycode, keysyms, onerror = None): \"\"\"Modify the keyboard mapping, starting", "AttributeError(attr) ### ### display information retrieval ### def screen(self, sno", "following attributes: focus The window which currently holds the input", "should be one of the following strings: resource drawable window", "mapping is changed and X.MappingSuccess is returned.\"\"\" r = request.SetModifierMapping(display", "self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror = ec,", "\"\"\"Return the current font path as a list of strings.\"\"\"", "onerror = onerror) def warp_pointer(self, x, y, src_window = X.NONE,", "sending the queued requests. This can be necessary in applications", "the Display object, or fetched from the environmental variable $DISPLAY.\"\"\"", "when creating the Display object, or fetched from the environmental", "cache implementation ### # The keycode->keysym map is stored in", "currently holds the input focus, X.NONE or X.PointerRoot. revert_to Where", "{} self.display_extension_methods = {} # a dict that maps the", "following attributes: accel_num accel_denom The acceleration as numerator/denumerator. threshold The", "Implement a cache of atom names, used by Window objects", "event_mask = event_mask, event = event) def ungrab_pointer(self, time, onerror", "sorted list of tuples with two # elements each: (index,", "\"\"\"Enable use of access control lists at connection setup if", "def extension_add_event(self, code, evt, name = None): \"\"\"extension_add_event(code, evt, [name])", "default_char draw_direction min_byte1 max_byte1 all_chars_exist font_ascent font_descent replies_hint See the", "where the focus reverts to if the focused window becomes", "sub-ID of this event that shares the code ID with", "The vector is represented as a list of 32 integers.", "and the attribute _code of the new event class will", "the pointer buttons. map is a list of logical button", "EVT will be cloned, and the attribute _code of the", "_resource_hierarchy = { 'resource': ('drawable', 'window', 'pixmap', 'fontable', 'font', 'gc',", "with the width of src_window - src_x. src_height is treated", "X.PointerRoot. revert_to Where the focus will revert, one of X.RevertToParent,", "for keysym, codes in self._keymap_syms.items(): i = 0 while i", "r = request.GetPointerMapping(display = self.display) return r.map def set_modifier_mapping(self, keycodes):", "the GNU Lesser General Public License for more details. #", "X # Xlib.protocol modules from .protocol import display as protocol_display", "time = time) def change_active_pointer_grab(self, event_mask, cursor, time, onerror =", "None): \"\"\"extension_add_event(code, evt, [name]) Add an extension event. CODE is", "query_keymap(self): \"\"\"Return a bit vector for the logical state of", "= (object, ) + _resource_hierarchy.get(object, ()) for class_name in class_list:", "= do_accel, do_thres = do_threshold, accel_num = accel_num, accel_denum =", "= rq.DictWrapper({}) exts = self.list_extensions() # Go through all extension", "way. To move the pointer to absolute coordinates, use Window.warp_pointer().\"\"\"", "and 3 is shift+alt grid. If that key entry is", "class_list = (object, ) + _resource_hierarchy.get(object, ()) for class_name in", "the keys # are keysyms. The values are a sorted", "self.extension_event = rq.DictWrapper({}) exts = self.list_extensions() # Go through all", "values are a sorted list of tuples with two #", "None): \"\"\"To change the pointer acceleration, set accel to a", "should be called once when a MappingNotify event is received,", "in milliseconds, -1 restores the default. led led_mode led_mode should", "count) return r.keysyms def change_keyboard_control(self, onerror = None, **keys): \"\"\"Change", "self.extensions def create_resource_object(self, type, id): \"\"\"Create a resource object of", "self.display, onerror = onerror, time = time) def change_active_pointer_grab(self, event_mask,", "Use this e.g. when it is important that errors caused", "on these values. properties A list of properties. Each entry", "get_display_name(self): \"\"\"Returns the name used to connect to the server,", "returned. If keysym is not bound to any key, 0", "the current keyboard mapping as a list of tuples, starting", "is omitted, it will be set to the name of", "gc colormap cursor This function can be used when a", "= self.display) return r.keycodes def no_operation(self, onerror = None): \"\"\"Do", "added by the library will not be available. \"\"\" return", "a list of eight lists, one for each modifier. The", "= ec, fid = fid, name = name) self.sync() if", "roots and default colormaps. # Fix that by reinstantiating them.", "code->sym map with the new map self._keymap_codes[first_keycode:lastcode] = keysyms #", "previously grabbed by this client.\"\"\" request.UngrabServer(display = self.display, onerror =", "or RevertToNone. \"\"\" return request.GetInputFocus(display = self.display) def query_keymap(self): \"\"\"Return", "def add_extension_error(self, code, err): \"\"\"add_extension_error(code, err) Add an extension error.", "pattern = pattern) return r.fonts def list_fonts_with_info(self, pattern, max_names): \"\"\"Return", "X.Mod5. keycodes should be a eight-element list where each entry", "} def extension_add_event(self, code, evt, name = None): \"\"\"extension_add_event(code, evt,", "string. Will raise BadAtom if atom does not exist.\"\"\" r", "= onerror, propagate = propagate, destination = destination, event_mask =", "self._keymap_codes = [()] * 256 self._keymap_syms = {} self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode", "set it to the number of pixels. -1 restores the", "= mode) def force_screen_saver(self, mode, onerror = None): \"\"\"If mode", "if sym != X.NoSymbol: if sym in self._keymap_syms: symcodes =", "list_extensions(self): \"\"\"Return a list of all the extensions provided by", "returning it as a string. Will raise BadAtom if atom", "will be restored.\"\"\" request.SetFontPath(display = self.display, onerror = onerror, path", "be set to CODE. If NAME is omitted, it will", "= onerror, cursor = cursor, time = time, event_mask =", "from 0 to 100. bell_percent bell_pitch bell_duration The volume, pitch", "first_keycode, count): \"\"\"Internal function, called to refresh the keymap cache.", "This can be necessary in applications that never wait for", "only_if_exists = 0): \"\"\"Intern the string name, returning its atom", "stored in a list with 256 elements. # Each element", "the corresponding key is currently pressed down. The vector is", "omitted, it will be set to the name of EVT.", "None): \"\"\"See XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display = self.display, onerror = onerror, timeout", "newevt) if name is None: name = evt.__name__ setattr(self.extension_event, name,", "# Xlib.xobjects modules from .xobject import resource from .xobject import", "the coding depends on family. For the Internet family, it", "destination which can be a window object, or X.PointerWindow or", "'pixmap'), 'fontable': ('font', 'gc') } class _BaseDisplay(protocol_display.Display): resource_classes = _resource_baseclasses.copy()", "event that shares the code ID with other sub-events and", "Copy the map list, reversing the arguments return map(lambda x:", "in src_window contains it. If src_width is 0 it will", "None): \"\"\"Release the server if it was previously grabbed by", "def screen(self, sno = None): if sno is None: return", "interface ### def extension_add_method(self, object, name, function): \"\"\"extension_add_method(object, name, function)", "Each entry has two attributes: name The atom identifying this", "lookup_string(self, keysym): \"\"\"Return a string corresponding to KEYSYM, or None", "index i.\"\"\" request.ChangeKeyboardMapping(display = self.display, onerror = onerror, first_keycode =", "on family. For the Internet family, it is the 4", "return r.map def set_modifier_mapping(self, keycodes): \"\"\"Set the keycodes for the", "specifies where the focus reverts to if the focused window", "object, or X.PointerWindow or X.InputFocus. event is the event object", "self.display.free_resource_id(fid) return None else: cls = self.display.get_resource_class('font', fontable.Font) return cls(self.display,", "or X.HostDelete. host_family is one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos.", "too try: self.class_extension_dicts[class_name][name] = method except KeyError: self.class_extension_dicts[class_name] = {", "ungrab_server(self, onerror = None): \"\"\"Release the server if it was", "= self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror =", "the # Free Software Foundation, Inc., # 59 Temple Place,", "class Display(object): def __init__(self, display = None): self.display = _BaseDisplay(display)", "= self.display) return r.names def change_keyboard_mapping(self, first_keycode, keysyms, onerror =", "then move num/denum times the normal speed if it moves", "is on, autorepeat is enabled for the corresponding key. led_mask", "return map(lambda x: (x[1], x[0]), self._keymap_syms[keysym]) except KeyError: return []", "0 accel_denum = 0 else: do_accel = 1 accel_num, accel_denum", "pointer must move before the acceleration kicks in.\"\"\" return request.GetPointerControl(display", "map = map) return r.status def get_pointer_mapping(self): \"\"\"Return a list", "-1 restores the default. bell_duration The duration of the bell", "<NAME> <<EMAIL>> # # This library is free software; you", "= [(index, code)] index = index + 1 code =", "If a bit is on, autorepeat is enabled for the", "self._atom_cache[atomname] r = request.InternAtom(display = self, name = atomname, only_if_exists", "The sublists list the keycodes bound to that modifier.\"\"\" r", "stored in a mapping, where the keys # are keysyms.", "Normally index 0 is unshifted, 1 is shifted, 2 is", "License for more details. # # You should have received", "base error code if the extension have additional errors, or", "font path of the server will be restored.\"\"\" request.SetFontPath(display =", "and in threaded applications.\"\"\" self.display.flush() def sync(self): \"\"\"Flush the queue", "NONE responses in case someone creates this later if r.atom", "onerror, mode = mode, host_family = host_family, host = host)", "onerror = onerror, mode = mode, host_family = host_family, host", "be modified, otherwise the global state for the entire keyboard", "bell_percent The base volume of the bell, coded as above.", "if sym in self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort()", "list of tuples (keycode, index) is returned, sorted primarily on", "} class _BaseDisplay(protocol_display.Display): resource_classes = _resource_baseclasses.copy() # Implement a cache", "tuple (num, denum). The pointer will then move num/denum times", "of object to add the function to, a string from", "= 1 request.ChangePointerControl(display = self.display, onerror = onerror, do_accel =", "to be passed select.select().\"\"\" return self.display.fileno() def close(self): \"\"\"Close the", "of an IPv4 address. \"\"\" return request.ListHosts(display = self.display) def", "connection close. The default is X.DestroyAll, the other values are", "of 32 integers. List item N contains the bits for", "is returned and the mapping is not changed. Otherwise the", "are changed. key auto_repeat_mode auto_repeat_mode should be one of X.AutoRepeatModeOff,", "should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard,", "up all the keycodes that is bound to keysym. A", "= None): \"\"\"Release the server if it was previously grabbed", "r.map def open_font(self, name): \"\"\"Open the font identifed by the", "None def list_extensions(self): \"\"\"Return a list of all the extensions", "# as published by the Free Software Foundation; either version", "return self.display.resource_classes[type](self.display, id) # We need this to handle display", "info = self.query_extension(extname) self.display.set_extension_major(extname, info.major_opcode) # Call initialiasation function mod.init(self,", "# the keysyms bound to the key. # The keysym->keycode", "8N to 8N + 7 with the least significant bit", "= {} # Find all supported extensions self.extensions = []", "request.ForceScreenSaver(display = self.display, onerror = onerror, mode = mode) def", "in self._keymap_syms.items(): i = 0 while i < len(codes): code", "key is provided, that key will be modified, otherwise the", "onerror = None): \"\"\"Release some queued events. mode should be", "rebind_string(self, keysym, newstring): \"\"\"Change the translation of KEYSYM to NEWSTRING.", "the pointer button mappings. Entry N in the list sets", "uses. first_event The base event code if the extension have", "<<EMAIL>> # # This library is free software; you can", "details. # # You should have received a copy of", "focused window becomes not visible, and should be X.RevertToParent, RevertToPointerRoot,", "\"\"\" self.display.add_extension_error(code, err) ### ### keymap cache implementation ### #", "and the mapping is not changed. Otherwise the mapping is", "section Error Handling.\"\"\" self.display.set_error_handler(handler) def flush(self): \"\"\"Flush the request queue,", "'resource': ('drawable', 'window', 'pixmap', 'fontable', 'font', 'gc', 'colormap', 'cursor'), 'drawable':", "def has_extension(self, extension): \"\"\"Check if both the server and the", "If keysym is not bound to any key, 0 is", "of strings. If path is empty, the default font path", "the sub-ID of this event that shares the code ID", "from .protocol import display as protocol_display from .protocol import request,", "max_names, pattern = pattern) def set_font_path(self, path, onerror = None):", "name is None: name = evt.__name__ # store subcodes as", "index = 0 for sym in syms: if sym !=", "onerror = onerror, cursor = cursor, time = time, event_mask", "for screen in self.display.info.roots: screen.root = self.display.resource_classes['window'](self.display, screen.root.id) screen.default_colormap =", "= self.display, onerror = onerror, propagate = propagate, destination =", "list of tuples of keysyms. keysyms[n][i] will be assigned to", "# Problem: we have already created some objects without the", "0 is unshifted, 1 is shifted, 2 is alt grid,", "focus, which should be a window, X.PointerRoot or X.NONE. revert_to", "than count.\"\"\" r = request.GetKeyboardMapping(display = self.display, first_keycode = first_keycode,", "dict maintained in the display object setattr(self.extension_event, name, (code,subcode)) def", "pattern. No more than max_names will be returned.\"\"\" r =", "fid, name = name) self.sync() if ec.get_error(): self.display.free_resource_id(fid) return None", "Internet family, it should be the four bytes of an", "keycode to a keysym, looking in entry index. Normally index", "or X.CurrentTime.\"\"\" request.AllowEvents(display = self.display, onerror = onerror, mode =", "1 accel_num, accel_denum = accel if threshold is None: do_threshold", "= count) return r.keysyms def change_keyboard_control(self, onerror = None, **keys):", "a grabbed pointer and any queued events. See XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display", "# Copyright (C) 2000 <NAME> <<EMAIL>> # # This library", "= {} def get_atom(self, atomname, only_if_exists=0): if atomname in self._atom_cache:", "min_char_or_byte2 max_char_or_byte2 default_char draw_direction min_byte1 max_byte1 all_chars_exist font_ascent font_descent replies_hint", "= self.query_extension(extname) self.display.set_extension_major(extname, info.major_opcode) # Call initialiasation function mod.init(self, info)", "restriction, X.MappingFailed is returned. Otherwise the mapping is changed and", "of the bell, coded as above. bell_pitch The pitch of", "in the DictWrapper extension_event. \"\"\" newevt = type(evt.__name__, evt.__bases__, evt.__dict__.copy())", "self.display, onerror = onerror, mode = mode) def set_close_down_mode(self, mode,", "object # # Copyright (C) 2000 <NAME> <<EMAIL>> # #", "General Public License # as published by the Free Software", "cache of atom names, used by Window objects when #", "time, onerror = None): \"\"\"Change the dynamic parameters of a", "r.atom def get_atom(self, atom, only_if_exists = 0): \"\"\"Alias for intern_atom,", "if the extension have additional events, or 0. first_error The", "'drawable': ('window', 'pixmap'), 'fontable': ('font', 'gc') } class _BaseDisplay(protocol_display.Display): resource_classes", "replace display method: %s' % name) self.display_extension_methods[name] = function else:", "not be created and X.NONE is returned.\"\"\" r = request.InternAtom(display", "should be bound to that modifier. If any changed key", "the byte representing key 8N.\"\"\" r = request.QueryKeymap(display = self.display)", "be the four bytes of an IPv4 address.\"\"\" request.ChangeHosts(display =", "# Python modules import types # Python 2/3 compatibility. from", "it will not be created and X.NONE is returned.\"\"\" r", "function else: class_list = (object, ) + _resource_hierarchy.get(object, ()) for", "a resource object of type for the integer id. type", "and default colormaps. # Fix that by reinstantiating them. for", "If NEWSTRING is None, remove old translation if any. \"\"\"", "NAME is the name of the method, a string. FUNCTION", "request.ListFonts(display = self.display, max_names = max_names, pattern = pattern) return", "MA 02111-1307 USA # Python modules import types # Python", "= self.display, onerror = onerror, time = time) def allow_events(self,", "None is returned.\"\"\" fid = self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display", "for all unhandled errors. handler should take two arguments as", "hasattr(self, name): raise AssertionError('attempting to replace display method: %s' %", "= onerror, mode = mode, host_family = host_family, host =", "mode, onerror = None): \"\"\"Enable use of access control lists", "256 elements. # Each element represents a keycode, and the", "starting with first_keycode. keysyms is a list of tuples of", "self._keymap_codes[first_keycode:lastcode] = keysyms # Update sym->code map code = first_keycode", "that it will be useful, # but WITHOUT ANY WARRANTY;", "modifier. The list can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and", "first_keycode = first_keycode, keysyms = keysyms) def get_keyboard_mapping(self, first_keycode, count):", "numerator/denumerator. threshold The number of pixels the pointer must move", "'window', 'pixmap', 'fontable', 'font', 'gc', 'colormap', 'cursor'), 'drawable': ('window', 'pixmap'),", "r.status def get_pointer_mapping(self): \"\"\"Return a list of the pointer button", "will happen with the client's resources at connection close. The", "\"\"\" return request.GetKeyboardControl(display = self.display) def bell(self, percent = 0,", "and sending the queued requests. This can be necessary in", "event_mask, event = event) def ungrab_pointer(self, time, onerror = None):", "bell. \"\"\" return request.GetKeyboardControl(display = self.display) def bell(self, percent =", "and code < lastcode: del codes[i] else: i = i", "by the server.\"\"\" r = request.ListExtensions(display = self.display) return r.names", "method.\"\"\" request.SendEvent(display = self.display, onerror = onerror, propagate = propagate,", "request.GrabServer(display = self.display, onerror = onerror) def ungrab_server(self, onerror =", "the least significant bit in the byte representing key 8N.\"\"\"", "import error from . import ext from . import X", "event_mask, cursor, time, onerror = None): \"\"\"Change the dynamic parameters", "= self.display, onerror = onerror, timeout = timeout, interval =", "properties A list of properties. Each entry has two attributes:", "returned.\"\"\" r = request.InternAtom(display = self.display, name = name, only_if_exists", "is returned. If keysym is not bound to any key,", "key 8N. If a bit is on, autorepeat is enabled", "all the extensions provided by the server.\"\"\" r = request.ListExtensions(display", "be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth,", "an object with the following attributes: mode X.EnableAccess if the", "event class. EVT will be cloned, and the attribute _code", "with this library; if not, write to the # Free", "absolute coordinates, use Window.warp_pointer().\"\"\" request.WarpPointer(display = self.display, onerror = onerror,", "and duration of the bell. \"\"\" return request.GetKeyboardControl(display = self.display)", "XSendEvent(3X11) for details. There is also a Window.send_event() method.\"\"\" request.SendEvent(display", "access list. Each entry has the following attributes: family X.FamilyInternet,", "= fid, name = name) self.sync() if ec.get_error(): self.display.free_resource_id(fid) return", "is the name of the method, a string. FUNCTION is", "if ec.get_error(): self.display.free_resource_id(fid) return None else: cls = self.display.get_resource_class('font', fontable.Font)", "be passed select.select().\"\"\" return self.display.fileno() def close(self): \"\"\"Close the display,", "'fontable': fontable.Fontable, 'font': fontable.Font, 'gc': fontable.GC, 'colormap': colormap.Colormap, 'cursor': cursor.Cursor,", "used, X.DisableAccess otherwise. hosts The hosts on the access list.", "2000 <NAME> <<EMAIL>> # # This library is free software;", "shifted, 2 is alt grid, and 3 is shift+alt grid.", "the focus will revert, one of X.RevertToParent, RevertToPointerRoot, or RevertToNone.", "prefer_blanking, allow_exposures. See XGetScreenSaver(3X11) for details.\"\"\" return request.GetScreenSaver(display = self.display)", "classes in protocol.events. See XSendEvent(3X11) for details. There is also", "found, the one with the lowest index and lowest code", "Display.get_pointer_mapping(). map[n] sets the logical number for the physical button", "insert an entry in the DictWrapper extension_event. \"\"\" newevt =", "the event object to send, instantiated from one of the", "physical button n+1. Logical number 0 disables the button. Two", "self.display.info.roots: screen.root = self.display.resource_classes['window'](self.display, screen.root.id) screen.default_colormap = self.display.resource_classes['colormap'](self.display, screen.default_colormap.id) def", "and should be X.RevertToParent, RevertToPointerRoot, or RevertToNone. See XSetInputFocus(3X11) for", "software; you can redistribute it and/or # modify it under", "string translations ### def lookup_string(self, keysym): \"\"\"Return a string corresponding", "protocol.events. See XSendEvent(3X11) for details. There is also a Window.send_event()", "request.UngrabPointer(display = self.display, onerror = onerror, time = time) def", "\"\"\" return self.display.resource_classes[type](self.display, id) # We need this to handle", "0 else: do_accel = 1 accel_num, accel_denum = accel if", "bound to the key. # The keysym->keycode map is stored", "owner for the selection. Can raise BadAtom.\"\"\" r = request.GetSelectionOwner(display", "X.NONE is returned.\"\"\" r = request.InternAtom(display = self.display, name =", "volume of key clicks between 0 (off) and 100 (load).", "matching pattern. No more than max_names will be returned. Each", "supports the extension name. If it is supported an object", "file descriptor number of the underlying socket. This method is", "# # This library is free software; you can redistribute", "request.GetKeyboardMapping(display = self.display, first_keycode = first_keycode, count = count) return", "(off) and 100 (load). -1 will restore default setting. bell_percent", "330, # Boston, MA 02111-1307 USA # Python modules import", "the underlying socket. This method is provided to allow Display", "the access list. Each entry has the following attributes: family", "= self.get_keyboard_mapping(first_keycode, count) # Replace code->sym map with the new", "= self.display) def set_screen_saver(self, timeout, interval, prefer_blank, allow_exposures, onerror =", "the appropriate class directly, since any X extensions dynamically added", "list where each entry is a list of the keycodes", "strings: resource drawable window pixmap fontable font gc colormap cursor", "= allow_exposures) def get_screen_saver(self): \"\"\"Return an object with the attributes", "name, code) def extension_add_subevent(self, code, subcode, evt, name = None):", "The major opcode that the requests of this extension uses.", "\"\"\"Look up all the keycodes that is bound to keysym.", "to the # Free Software Foundation, Inc., # 59 Temple", "to keysym. If several keycodes are found, the one with", "of tuples (keycode, index) is returned, sorted primarily on the", "to a keysym, looking in entry index. Normally index 0", "A 32-bit unsigned value. \"\"\" return request.ListFontsWithInfo(display = self.display, max_names", "any changed key is logically in the down state, X.MappingBusy", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "setattr(self.extension_event, name, code) def extension_add_subevent(self, code, subcode, evt, name =", "accel to a tuple (num, denum). The pointer will then", "and the mapping is not changed. If the mapping violates", "keyboard and any queued events. See XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display = self.display,", "input focus to focus, which should be a window, X.PointerRoot", "is None: do_threshold = 0 else: do_threshold = 1 request.ChangePointerControl(display", "threaded applications.\"\"\" self.display.flush() def sync(self): \"\"\"Flush the queue and wait", "+ modname) mod = getattr(ext, modname) info = self.query_extension(extname) self.display.set_extension_major(extname,", "keysyms = self.get_keyboard_mapping(first_keycode, count) # Replace code->sym map with the", "request.ChangeActivePointerGrab(display = self.display, onerror = onerror, cursor = cursor, time", "= X.NONE, src_x = src_x, src_y = src_y, src_width =", "more than max_names will be returned.\"\"\" r = request.ListFonts(display =", "extension dict maintained in the display object setattr(self.extension_event, name, (code,subcode))", "timeout, interval = interval, prefer_blank = prefer_blank, allow_exposures = allow_exposures)", "### def extension_add_method(self, object, name, function): \"\"\"extension_add_method(object, name, function) Add", "it will block until the next event is fetched from", "from . import ext from . import X # Xlib.protocol", "If src_width is 0 it will be replaced with the", "grabbed keyboard and any queued events. See XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display =", "following attributes: global_auto_repeat X.AutoRepeatModeOn or X.AutoRepeatModeOff. auto_repeats A list of", "X.NoSymbol is returned.\"\"\" try: return self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol", "relative its current position by the offsets (x, y). However,", "A list of byte values, the coding depends on family.", "Hz, -1 restores the default. bell_duration The duration of the", "code = first_keycode for syms in keysyms: index = 0", "\"\"\"To change the pointer acceleration, set accel to a tuple", "See XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display = self.display, onerror = onerror, time =", "redistribute it and/or # modify it under the terms of", "named extension.\"\"\" return extension in self.extensions def create_resource_object(self, type, id):", "or 0. If the extension is not supported, None is", "family. For the Internet family, it is the 4 bytes", "that should be bound to that modifier. If any changed", "event is received, to update the keymap cache. evt should", "is None: name = evt.__name__ # store subcodes as a", "self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym] = [(index, code)] index", "fontable.Font, 'gc': fontable.GC, 'colormap': colormap.Colormap, 'cursor': cursor.Cursor, } _resource_hierarchy =", "self._keymap_syms = {} self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode - self.display.info.min_keycode + 1)) #", "as above. bell_pitch The pitch of the bell in Hz,", "ext from . import X # Xlib.protocol modules from .protocol", "function mod.init(self, info) self.extensions.append(extname) # Finalize extensions by creating new", "'drawable': drawable.Drawable, 'window': drawable.Window, 'pixmap': drawable.Pixmap, 'fontable': fontable.Fontable, 'font': fontable.Font,", "wait for events, and in threaded applications.\"\"\" self.display.flush() def sync(self):", "code) def extension_add_subevent(self, code, subcode, evt, name = None): \"\"\"extension_add_subevent(code,", "allow_events(self, mode, time, onerror = None): \"\"\"Release some queued events.", "if src_window is a window the pointer is only moved", "event_mask) def ungrab_keyboard(self, time, onerror = None): \"\"\"Ungrab a grabbed", "to a tuple (num, denum). The pointer will then move", "mode, host_family = host_family, host = host) def list_hosts(self): \"\"\"Return", "each bit set to 1 indicates that the corresponding key", "sym in self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else:", "0 it will be replaced with the width of src_window", "depends on family. For the Internet family, it is the", "self.display, onerror = onerror, first_keycode = first_keycode, keysyms = keysyms)", "lowest keycode.\"\"\" try: # Copy the map list, reversing the", "or X.FamilyChaos. name A list of byte values, the coding", "time, onerror = None): \"\"\"Set input focus to focus, which", "have additional errors, or 0. If the extension is not", "modname) info = self.query_extension(extname) self.display.set_extension_major(extname, info.major_opcode) # Call initialiasation function", "AssertionError('attempting to replace %s method: %s' % (class_name, name)) method", "ext.__extensions__: if extname in exts: # Import the module and", "pitch and duration of the bell. \"\"\" return request.GetKeyboardControl(display =", "error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror = ec, fid = fid,", "(object, ) + _resource_hierarchy.get(object, ()) for class_name in class_list: cls", "this keysym is bound, and # index is the keysyms", "get_screen_saver(self): \"\"\"Return an object with the attributes timeout, interval, prefer_blanking,", "time = time) def grab_server(self, onerror = None): \"\"\"Disable processing", "an X extension module method. OBJECT is the type of", "errors caused by a certain request is trapped.\"\"\" # Do", "self, name = atomname, only_if_exists = only_if_exists) # don't cache", ".xobject import cursor _resource_baseclasses = { 'resource': resource.Resource, 'drawable': drawable.Drawable,", "number of screens on the display.\"\"\" return len(self.display.info.roots) def get_default_screen(self):", "time, event_mask = event_mask) def ungrab_keyboard(self, time, onerror = None):", "None: name = evt.__name__ # store subcodes as a tuple", "X.ShiftMapIndex, X.Mod1MapIndex, and so on. The sublists list the keycodes", "set to 1 indicates that the corresponding key is currently", "that it holds.\"\"\" self.display.close() def set_error_handler(self, handler): \"\"\"Set the default", "colormaps. # Fix that by reinstantiating them. for screen in", "to connect to the server, either provided when creating the", "evt.__name__ setattr(self.extension_event, name, code) def extension_add_subevent(self, code, subcode, evt, name", "it is X.DisableAccess.\"\"\" request.SetAccessControl(display = self.display, onerror = onerror, mode", "def extension_add_method(self, object, name, function): \"\"\"extension_add_method(object, name, function) Add an", "restore default setting. bell_percent The base volume of the bell,", "found. \"\"\" s = self.keysym_translations.get(keysym) if s is not None:", "vector for the logical state of the keyboard, where each", "of the bell in Hz, -1 restores the default. bell_duration", "and X.NONE is returned.\"\"\" r = request.InternAtom(display = self.display, name", "do it... self.get_pointer_control() def next_event(self): \"\"\"Return the next event. If", "and the tuple elements are # the keysyms bound to", "None, **keys): \"\"\"Change the parameters provided as keyword arguments: key_click_percent", "None): \"\"\"extension_add_subevent(code, evt, [name]) Add an extension subevent. CODE is", "or RevertToNone. See XSetInputFocus(3X11) for details. There is also a", "pointer button mappings. Entry N in the list sets the", "of keysyms. keysyms[n][i] will be assigned to keycode first_keycode+n at", "src_window - src_x. src_height is treated in a similar way.", "significant bit in the byte representing key 8N. If a", "evt, [name]) Add an extension event. CODE is the numeric", "X.AutoRepeatModeDefault. If key is provided, that key will be modified,", "object with the following attributes is returned: major_opcode The major", "= 0 while i < len(codes): code = codes[i][1] if", "is no owner for the selection. Can raise BadAtom.\"\"\" r", "the atom does not already exist, it will not be", "atomname, only_if_exists = only_if_exists) # don't cache NONE responses in", "error. CODE is the numeric code, and ERR is the", "fetched from the environmental variable $DISPLAY.\"\"\" return self.display.get_display_name() def fileno(self):", "return r.map def open_font(self, name): \"\"\"Open the font identifed by", "r = request.QueryExtension(display = self.display, name = name) if r.present:", "= atom) return r.name def get_selection_owner(self, selection): \"\"\"Return the window", "which can be a window object, or X.PointerWindow or X.InputFocus.", "self.extensions.append(extname) # Finalize extensions by creating new classes for class_name,", "handler, but the second argument (the request) will be None.", "= onerror, time = time) def change_active_pointer_grab(self, event_mask, cursor, time,", "speed if it moves beyond the threshold number of pixels", "= self.display) def change_hosts(self, mode, host_family, host, onerror = None):", ".protocol import display as protocol_display from .protocol import request, event,", "for more details. # # You should have received a", "get_atom_name(self, atom): \"\"\"Look up the name of atom, returning it", "grid. If that key entry is not bound, X.NoSymbol is", "map with the new map self._keymap_codes[first_keycode:lastcode] = keysyms # Update", "no events queued, it will block until the next event", "state, X.MappingBusy is returned and the mapping is not changed.", "address it as # extension_event.EXTENSION_EVENT_NAME rather than # extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event", "= onerror, attrs = keys) def get_keyboard_control(self): \"\"\"Return an object", "should take two arguments as a normal request error handler,", "led is not provided, all LEDs are changed. key auto_repeat_mode", "family, it should be the four bytes of an IPv4", "must be of the same length as the list returned", "< len(codes): code = codes[i][1] if code >= first_keycode and", "0 is returned.\"\"\" try: return self._keymap_syms[keysym][0][1] except (KeyError, IndexError): return", "max_byte1 all_chars_exist font_ascent font_descent replies_hint See the descripton of XFontStruct", "time, onerror = None): \"\"\"Release some queued events. mode should", "### ### keymap cache implementation ### # The keycode->keysym map", "cursor = cursor, time = time, event_mask = event_mask) def", "change_keyboard_mapping(self, first_keycode, keysyms, onerror = None): \"\"\"Modify the keyboard mapping,", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "should be a window, X.PointerRoot or X.NONE. revert_to specifies where", "extension have additional events, or 0. first_error The base error", "ec, fid = fid, name = name) self.sync() if ec.get_error():", "if mode is X.EnableAccess, disable if it is X.DisableAccess.\"\"\" request.SetAccessControl(display", "beyond the threshold number of pixels at once. To change", "None is returned.\"\"\" r = request.QueryExtension(display = self.display, name =", "$DISPLAY.\"\"\" return self.display.get_display_name() def fileno(self): \"\"\"Returns the file descriptor number", "with the attributes timeout, interval, prefer_blanking, allow_exposures. See XGetScreenSaver(3X11) for", "received a copy of the GNU Lesser General Public #", "mode = mode) def set_pointer_mapping(self, map): \"\"\"Set the mapping of", "name to the code # or, when it's an event", "server has processed all the queued requests. Use this e.g.", "list: display resource drawable window pixmap fontable font gc colormap", "if name is None: name = evt.__name__ # store subcodes", "name): raise AssertionError('attempting to replace display method: %s' % name)", "is currently pressed down. The vector is represented as a", "to the name of EVT. This name is used to", "been received.\"\"\" request.ForceScreenSaver(display = self.display, onerror = onerror, mode =", "address. \"\"\" return request.ListHosts(display = self.display) def set_access_control(self, mode, onerror", "environmental variable $DISPLAY.\"\"\" return self.display.get_display_name() def fileno(self): \"\"\"Returns the file", "identifying this property. value A 32-bit unsigned value. \"\"\" return", "the following properties: name The name of the font. min_bounds", "r.names def change_keyboard_mapping(self, first_keycode, keysyms, onerror = None): \"\"\"Modify the", "= self.display, onerror = onerror, mode = mode) def set_pointer_mapping(self,", "ID with other sub-events and EVT is the event class.", "least significant bit in the byte representing key 8N.\"\"\" r", "the arguments return map(lambda x: (x[1], x[0]), self._keymap_syms[keysym]) except KeyError:", "= 0): \"\"\"Intern the string name, returning its atom number.", "is shifted, 2 is alt grid, and 3 is shift+alt", "focus will revert, one of X.RevertToParent, RevertToPointerRoot, or RevertToNone. \"\"\"", "self.display.set_error_handler(handler) def flush(self): \"\"\"Flush the request queue, building and sending", "newevt._code = code self.display.add_extension_event(code, newevt) if name is None: name", "returned.\"\"\" try: return self._keymap_syms[keysym][0][1] except (KeyError, IndexError): return 0 def", "and the client library support the X extension named extension.\"\"\"", "def set_error_handler(self, handler): \"\"\"Set the default error handler which will", "drawable.Pixmap, 'fontable': fontable.Fontable, 'font': fontable.Font, 'gc': fontable.GC, 'colormap': colormap.Colormap, 'cursor':", "screen roots and default colormaps. # Fix that by reinstantiating", "onerror = onerror, time = time) def allow_events(self, mode, time,", "None, onerror = None): \"\"\"To change the pointer acceleration, set", "gc colormap cursor NAME is the name of the method,", "X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should", "denum). The pointer will then move num/denum times the normal", "accel_denum = 0 else: do_accel = 1 accel_num, accel_denum =", "= request.SetModifierMapping(display = self.display, keycodes = keycodes) return r.status def", "sno = None): if sno is None: return self.display.info.roots[self.display.default_screen] else:", "The window which currently holds the input focus, X.NONE or", "= request.SetPointerMapping(display = self.display, map = map) return r.status def", "= x, dst_y = y) def set_input_focus(self, focus, revert_to, time,", "atom identifying this property. value A 32-bit unsigned value. \"\"\"", "the default. led led_mode led_mode should be X.LedModeOff or X.LedModeOn.", "on the display.\"\"\" return len(self.display.info.roots) def get_default_screen(self): \"\"\"Return the number", "replaced with the width of src_window - src_x. src_height is", "it will be set to the name of EVT. This", "details.\"\"\" return request.GetScreenSaver(display = self.display) def change_hosts(self, mode, host_family, host,", "type of object to add the function to, a string", "\"\"\"Intern the string name, returning its atom number. If only_if_exists", "self.display, onerror = ec, fid = fid, name = name)", "r.atom return r.atom class Display(object): def __init__(self, display = None):", "base event code if the extension have additional events, or", "X.FamilyInternet, X.FamilyDECnet, or X.FamilyChaos. name A list of byte values,", "address.\"\"\" request.ChangeHosts(display = self.display, onerror = onerror, mode = mode,", "= revert_to, focus = focus, time = time) def get_input_focus(self):", "should be X.RevertToParent, RevertToPointerRoot, or RevertToNone. See XSetInputFocus(3X11) for details.", "= event_mask, event = event) def ungrab_pointer(self, time, onerror =", "a list of bytes. For the Internet family, it should", "from this list: display resource drawable window pixmap fontable font", "bound to keysym. If several keycodes are found, the one", "reasonable translation is found. \"\"\" s = self.keysym_translations.get(keysym) if s", "BadAtom if atom does not exist.\"\"\" r = request.GetAtomName(display =", "the pointer acceleration, set accel to a tuple (num, denum).", "None if no reasonable translation is found. \"\"\" s =", "'display': if hasattr(self, name): raise AssertionError('attempting to replace display method:", "maps the event name to the code # or, when", "request.GetFontPath(display = self.display) return r.paths def query_extension(self, name): \"\"\"Ask the", "device input had been received.\"\"\" request.ForceScreenSaver(display = self.display, onerror =", "raise BadAtom.\"\"\" r = request.GetSelectionOwner(display = self.display, selection = selection)", "\"\"\"Returns the file descriptor number of the underlying socket. This", "request.InternAtom(display = self.display, name = name, only_if_exists = only_if_exists) return", "unhandled errors. handler should take two arguments as a normal", "def keysym_to_keycode(self, keysym): \"\"\"Look up the primary keycode that is", "the number of events queued, i.e. the number of times", "def list_extensions(self): \"\"\"Return a list of all the extensions provided", "onerror = None): \"\"\"Enable use of access control lists at", "focus reverts to if the focused window becomes not visible,", "KeyError: pass else: self.keysym_translations[keysym] = newstring ### ### X requests", "= selection) return r.owner def send_event(self, destination, event, event_mask =", "import X # Xlib.protocol modules from .protocol import display as", "maintained in the display object setattr(self.extension_event, name, (code,subcode)) def add_extension_error(self,", "that keycode. def keycode_to_keysym(self, keycode, index): \"\"\"Convert a keycode to", "= max_names, pattern = pattern) return r.fonts def list_fonts_with_info(self, pattern,", "by instantiating the appropriate class directly, since any X extensions", "# Copy the map list, reversing the arguments return map(lambda", "but the second argument (the request) will be None. See", "ec.get_error(): self.display.free_resource_id(fid) return None else: cls = self.display.get_resource_class('font', fontable.Font) return", "of the font. min_bounds max_bounds min_char_or_byte2 max_char_or_byte2 default_char draw_direction min_byte1", "should be one of X.AutoRepeatModeOff, X.AutoRepeatModeOn, or X.AutoRepeatModeDefault. If key", "global state for the entire keyboard will be modified.\"\"\" request.ChangeKeyboardControl(display", "to any key, 0 is returned.\"\"\" try: return self._keymap_syms[keysym][0][1] except", "underlying socket. This method is provided to allow Display objects", "= 0 accel_num = 0 accel_denum = 0 else: do_accel", "mapped to the same logical number. If one of the", "an extension subevent. CODE is the numeric code, subcode is", "compatibility. from six import create_unbound_method # Xlib modules from .", "= request.InternAtom(display = self, name = atomname, only_if_exists = only_if_exists)", "events, or 0. first_error The base error code if the", "fontable.Font) return cls(self.display, fid, owner = 1) def list_fonts(self, pattern,", "will be returned.\"\"\" r = request.ListFonts(display = self.display, max_names =", "for keysyms to strings. self.keysym_translations = {} # Find all", "is enabled for the corresponding key. led_mask A 32-bit mask", "be one of X.AutoRepeatModeOff, X.AutoRepeatModeOn, or X.AutoRepeatModeDefault. If key is", "= host_family, host = host) def list_hosts(self): \"\"\"Return an object", "until the server has processed all the queued requests. Use", "in self.display.info.roots: screen.root = self.display.resource_classes['window'](self.display, screen.root.id) screen.default_colormap = self.display.resource_classes['colormap'](self.display, screen.default_colormap.id)", "if atomname in self._atom_cache: return self._atom_cache[atomname] r = request.InternAtom(display =", "click, from 0 to 100. bell_percent bell_pitch bell_duration The volume,", "if the specified rectangle in src_window contains it. If src_width", "first_keycode. keysyms is a list of tuples of keysyms. keysyms[n][i]", "number of pixels the pointer must move before the acceleration", "in a list with 256 elements. # Each element represents", "a list of tuples, starting at first_keycount and no more", "index. Normally index 0 is unshifted, 1 is shifted, 2", "the client's resources at connection close. The default is X.DestroyAll,", "is the event object to send, instantiated from one of", "one of the following strings: resource drawable window pixmap fontable", "be cloned, and the attribute _code of the new event", "window destination which can be a window object, or X.PointerWindow", "all supported extensions self.extensions = [] self.class_extension_dicts = {} self.display_extension_methods", "X.SyncBoth. time should be a timestamp or X.CurrentTime.\"\"\" request.AllowEvents(display =", "0 disables the button. Two physical buttons cannot be mapped", "way to do it... self.get_pointer_control() def next_event(self): \"\"\"Return the next", "accel if threshold is None: do_threshold = 0 else: do_threshold", "all extension modules for extname, modname in ext.__extensions__: if extname", "\"\"\"Set the mapping of the pointer buttons. map is a", "keycodes): \"\"\"Set the keycodes for the eight modifiers X.Shift, X.Lock,", "the type of object to add the function to, a", "XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display = self.display, onerror = onerror, cursor = cursor,", "id. type should be one of the following strings: resource", "on. The sublists list the keycodes bound to that modifier.\"\"\"", "window pixmap fontable font gc colormap cursor This function can", "function) Add an X extension module method. OBJECT is the", "for sym in syms: if sym != X.NoSymbol: if sym", "name does not match any font, None is returned.\"\"\" fid", "events, and in threaded applications.\"\"\" self.display.flush() def sync(self): \"\"\"Flush the", "[name]) Add an extension event. CODE is the numeric code,", "for the logical state of the keyboard, where each bit", "self.display) def set_screen_saver(self, timeout, interval, prefer_blank, allow_exposures, onerror = None):", "owns selection (an atom), or X.NONE if there is no", "n+1. Logical number 0 disables the button. Two physical buttons", "the down state, X.MappingBusy is returned and the mapping is", "that never wait for events, and in threaded applications.\"\"\" self.display.flush()", "of pixels the pointer must move before the acceleration kicks", "the logical state of the keyboard, where each bit set", "requests. This can be necessary in applications that never wait", "def set_font_path(self, path, onerror = None): \"\"\"Set the font path", "host = host) def list_hosts(self): \"\"\"Return an object with the", "for details. There is also a Window.set_input_focus().\"\"\" request.SetInputFocus(display = self.display,", "arguments: key_click_percent The volume of key clicks between 0 (off)", "use Window.warp_pointer().\"\"\" request.WarpPointer(display = self.display, onerror = onerror, src_window =", "a Window.send_event() method.\"\"\" request.SendEvent(display = self.display, onerror = onerror, propagate", "The base event code if the extension have additional events,", "select.select().\"\"\" return self.display.fileno() def close(self): \"\"\"Close the display, freeing the", "visible, and should be X.RevertToParent, RevertToPointerRoot, or RevertToNone. See XSetInputFocus(3X11)", "request.OpenFont(display = self.display, onerror = ec, fid = fid, name", "light-weight replyrequest to sync. There must # be a better", "module interface ### def extension_add_method(self, object, name, function): \"\"\"extension_add_method(object, name,", "so you address it as # extension_event.EXTENSION_EVENT_NAME rather than #", "= request.GetModifierMapping(display = self.display) return r.keycodes def no_operation(self, onerror =", "src_height = src_height, dst_x = x, dst_y = y) def", "mod.init(self, info) self.extensions.append(extname) # Finalize extensions by creating new classes", "by reinstantiating them. for screen in self.display.info.roots: screen.root = self.display.resource_classes['window'](self.display,", "N+1.\"\"\" r = request.GetPointerMapping(display = self.display) return r.map def set_modifier_mapping(self,", "= _BaseDisplay(display) # Create the keymap cache self._keymap_codes = [()]", "returned, sorted primarily on the lowest index and secondarily on", "name = name) self.sync() if ec.get_error(): self.display.free_resource_id(fid) return None else:", "= self.display, onerror = onerror, path = path) def get_font_path(self):", "keycode is the code for a key to which this", "def flush(self): \"\"\"Flush the request queue, building and sending the", "the function to, a string from this list: display resource", "number of pixels. -1 restores the default.\"\"\" if accel is", "import create_unbound_method # Xlib modules from . import error from", "key clicks between 0 (off) and 100 (load). -1 will", "is changed and X.MappingSuccess is returned.\"\"\" r = request.SetPointerMapping(display =", "get_modifier_mapping(self): \"\"\"Return a list of eight lists, one for each", "argument (the request) will be None. See section Error Handling.\"\"\"", "as a tuple of (event code, subcode) in the #", "get_selection_owner(self, selection): \"\"\"Return the window that owns selection (an atom),", "def change_keyboard_control(self, onerror = None, **keys): \"\"\"Change the parameters provided", "\"\"\"Open the font identifed by the pattern name and return", "key click, from 0 to 100. bell_percent bell_pitch bell_duration The", "of the GNU Lesser General Public License # as published", "request.ChangePointerControl(display = self.display, onerror = onerror, do_accel = do_accel, do_thres", "onerror, percent = percent) def change_pointer_control(self, accel = None, threshold", "from .xobject import cursor _resource_baseclasses = { 'resource': resource.Resource, 'drawable':", "self.display_extension_methods[name] = function else: class_list = (object, ) + _resource_hierarchy.get(object,", "base volume. See XBell(3X11).\"\"\" request.Bell(display = self.display, onerror = onerror,", "must # be a better way to do it... self.get_pointer_control()", "list of logical button numbers. map must be of the", "propagate, destination = destination, event_mask = event_mask, event = event)", "reinstantiating them. for screen in self.display.info.roots: screen.root = self.display.resource_classes['window'](self.display, screen.root.id)", "in exts: # Import the module and fetch it __import__('Xlib.ext.'", "# Finalize extensions by creating new classes for class_name, dictionary", "do_threshold = 0 else: do_threshold = 1 request.ChangePointerControl(display = self.display,", "= None, **keys): \"\"\"Change the parameters provided as keyword arguments:", "font identifed by the pattern name and return its font", "+ _resource_hierarchy.get(object, ()) for class_name in class_list: cls = _resource_baseclasses[class_name]", "if name is None: name = evt.__name__ setattr(self.extension_event, name, code)", "Logical number 0 disables the button. Two physical buttons cannot", "Add an extension subevent. CODE is the numeric code, subcode", "ICCCM properties not defined in Xlib.Xatom def __init__(self, *args, **keys):", "total number of screens on the display.\"\"\" return len(self.display.info.roots) def", "= mode) def set_pointer_mapping(self, map): \"\"\"Set the mapping of the", "requests. Use this e.g. when it is important that errors", "= None): \"\"\"Set input focus to focus, which should be", "self.display) def change_hosts(self, mode, host_family, host, onerror = None): \"\"\"mode", "0, src_width = 0, src_height = 0, onerror = None):", "*args, **keys): protocol_display.Display.__init__(self, *args, **keys) self._atom_cache = {} def get_atom(self,", "self.display.resource_classes['colormap'](self.display, screen.default_colormap.id) def get_display_name(self): \"\"\"Returns the name used to connect", "request.QueryExtension(display = self.display, name = name) if r.present: return r", "= onerror, mode = mode) def set_pointer_mapping(self, map): \"\"\"Set the", "with the following attributes is returned: major_opcode The major opcode", "name of the method, a string. FUNCTION is a normal", "X.NONE, src_x = src_x, src_y = src_y, src_width = src_width,", "N in the list sets the logical button number for", "extension event. CODE is the numeric code, and EVT is", "method, a string. FUNCTION is a normal function whose first", "extension): \"\"\"Check if both the server and the client library", "max_names = max_names, pattern = pattern) def set_font_path(self, path, onerror", "first_event The base event code if the extension have additional", "as the list returned by Display.get_pointer_mapping(). map[n] sets the logical", "copy of the GNU Lesser General Public # License along", "self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode - self.display.info.min_keycode + 1)) # Translations for keysyms", "except KeyError: pass else: self.keysym_translations[keysym] = newstring ### ### X", "Public License for more details. # # You should have", "error code if the extension have additional errors, or 0.", "are a sorted list of tuples with two # elements", "self.display, selection = selection) return r.owner def send_event(self, destination, event,", "without blocking.\"\"\" return self.display.pending_events() def has_extension(self, extension): \"\"\"Check if both", "To move the pointer to absolute coordinates, use Window.warp_pointer().\"\"\" request.WarpPointer(display", "elements are # the keysyms bound to the key. #", "* 256 self._keymap_syms = {} self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode - self.display.info.min_keycode +", "mode) def set_pointer_mapping(self, map): \"\"\"Set the mapping of the pointer", "# extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event = rq.DictWrapper({}) exts = self.list_extensions() # Go", "the server will be restored.\"\"\" request.SetFontPath(display = self.display, onerror =", "display extension methods def __getattr__(self, attr): try: function = self.display_extension_methods[attr]", "The pitch of the bell in Hz, -1 restores the", "is returned and the mapping is not changed. If the", "self.display, onerror = onerror, path = path) def get_font_path(self): \"\"\"Return", "# Create the keymap cache self._keymap_codes = [()] * 256", "### ### Extension module interface ### def extension_add_method(self, object, name,", "in applications that never wait for events, and in threaded", "\"\"\"Look up the name of atom, returning it as a", "should never be created by instantiating the appropriate class directly,", "Public # License along with this library; if not, write", "path, onerror = None): \"\"\"Set the font path to path,", "def bell(self, percent = 0, onerror = None): \"\"\"Ring the", "to the window destination which can be a window object,", "for each modifier. The list can be indexed using X.ShiftMapIndex,", "PURPOSE. # See the GNU Lesser General Public License for", "be called for all unhandled errors. handler should take two", "mode, onerror = None): \"\"\"If mode is X.ScreenSaverActive the screen", "newevt = type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt)", "pattern) def set_font_path(self, path, onerror = None): \"\"\"Set the font", "timeout, interval, prefer_blanking, allow_exposures. See XGetScreenSaver(3X11) for details.\"\"\" return request.GetScreenSaver(display", "License # as published by the Free Software Foundation; either", "in ext.__extensions__: if extname in exts: # Import the module", "position by the offsets (x, y). However, if src_window is", "font. min_bounds max_bounds min_char_or_byte2 max_char_or_byte2 default_char draw_direction min_byte1 max_byte1 all_chars_exist", "r.atom class Display(object): def __init__(self, display = None): self.display =", "the display object setattr(self.extension_event, name, (code,subcode)) def add_extension_error(self, code, err):", "x: (x[1], x[0]), self._keymap_syms[keysym]) except KeyError: return [] def refresh_keyboard_mapping(self,", "a bit vector for the logical state of the keyboard,", "one with the lowest index and lowest code is returned.", "= time) def allow_events(self, mode, time, onerror = None): \"\"\"Release", "connections until the server is ungrabbed. Server grabbing should be", "The volume of key click, from 0 to 100. bell_percent", "list sets the logical button number for the physical button", "is stored in a mapping, where the keys # are", "in entry index. Normally index 0 is unshifted, 1 is", "There is also a Window.set_input_focus().\"\"\" request.SetInputFocus(display = self.display, onerror =", "creating the Display object, or fetched from the environmental variable", "None): \"\"\"Control what will happen with the client's resources at", "logically in the down state, X.MappingBusy is returned and the", "X.Lock, X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes should", "there are no events queued, it will block until the", "request.SetFontPath(display = self.display, onerror = onerror, path = path) def", "wraps the dict so you address it as # extension_event.EXTENSION_EVENT_NAME", "that errors caused by a certain request is trapped.\"\"\" #", "a synthetic event to the window destination which can be", "self.display.pending_events() def has_extension(self, extension): \"\"\"Check if both the server and", "keyboard mapping as a list of tuples, starting at first_keycount", "X.DisableAccess otherwise. hosts The hosts on the access list. Each", "= propagate, destination = destination, event_mask = event_mask, event =", "the focus reverts to if the focused window becomes not", "family, it is the 4 bytes of an IPv4 address.", "= None): \"\"\"Release some queued events. mode should be one", "percent = 0, onerror = None): \"\"\"Ring the bell at", "can redistribute it and/or # modify it under the terms", "None. See section Error Handling.\"\"\" self.display.set_error_handler(handler) def flush(self): \"\"\"Flush the", "X.MappingBusy is returned and the mapping is not changed. Otherwise", "X.NONE. revert_to specifies where the focus reverts to if the", "7 with the least significant bit in the byte representing", "resource from .xobject import drawable from .xobject import fontable from", "Xlib.display -- high level display object # # Copyright (C)", "will be called for all unhandled errors. handler should take", "Display.next_event() can be called without blocking.\"\"\" return self.display.pending_events() def has_extension(self,", "def next_event(self): \"\"\"Return the next event. If there are no", "r = request.GetAtomName(display = self.display, atom = atom) return r.name", "time = time) def allow_events(self, mode, time, onerror = None):", "called to refresh the keymap cache. \"\"\" # Delete all", "grab_server(self, onerror = None): \"\"\"Disable processing of requests on all", "be None. See section Error Handling.\"\"\" self.display.set_error_handler(handler) def flush(self): \"\"\"Flush", "**keys) self._atom_cache = {} def get_atom(self, atomname, only_if_exists=0): if atomname", "server, either provided when creating the Display object, or fetched", "def change_pointer_control(self, accel = None, threshold = None, onerror =", "code, subcode, evt, name = None): \"\"\"extension_add_subevent(code, evt, [name]) Add", "code # or, when it's an event with a subcode,", "retrieval ### def screen(self, sno = None): if sno is", "object of type for the integer id. type should be", "is the error class. \"\"\" self.display.add_extension_error(code, err) ### ### keymap", "is shift+alt grid. If that key entry is not bound,", "None): \"\"\"Move the pointer relative its current position by the", "= None): if sno is None: return self.display.info.roots[self.display.default_screen] else: return", "except KeyError: raise AttributeError(attr) ### ### display information retrieval ###", "additional events, or 0. first_error The base error code if", "following properties: name The name of the font. min_bounds max_bounds", "is None: do_accel = 0 accel_num = 0 accel_denum =", "for the physical button n+1. Logical number 0 disables the", "count = count) return r.keysyms def change_keyboard_control(self, onerror = None,", "onerror = None): \"\"\"Ring the bell at the volume percent", "parameters provided as keyword arguments: key_click_percent The volume of key", "it is the 4 bytes of an IPv4 address. \"\"\"", "self.display, name = name, only_if_exists = only_if_exists) return r.atom def", "None): \"\"\"Set input focus to focus, which should be a", "your option) any later version. # # This library is", "volume. See XBell(3X11).\"\"\" request.Bell(display = self.display, onerror = onerror, percent", "of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth.", "= self.display, onerror = onerror, time = time) def change_active_pointer_grab(self,", "def get_default_screen(self): \"\"\"Return the number of the default screen, extracted", "3 is shift+alt grid. If that key entry is not", "See XSendEvent(3X11) for details. There is also a Window.send_event() method.\"\"\"", "subcode) if name is None: name = evt.__name__ # store", "self.display) return r.paths def query_extension(self, name): \"\"\"Ask the server if", "else: class_list = (object, ) + _resource_hierarchy.get(object, ()) for class_name", "code self.display.add_extension_event(code, newevt, subcode) if name is None: name =", "can be necessary in applications that never wait for events,", "destination, event, event_mask = 0, propagate = 0, onerror =", "Temple Place, # Suite 330, # Boston, MA 02111-1307 USA", "keyboard, where each bit set to 1 indicates that the", "screen.default_colormap.id) def get_display_name(self): \"\"\"Returns the name used to connect to", "return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym) def rebind_string(self, keysym, newstring):", "following attributes: mode X.EnableAccess if the access control list is", "X requests ### def intern_atom(self, name, only_if_exists = 0): \"\"\"Intern", "the dict so you address it as # extension_event.EXTENSION_EVENT_NAME rather", "request.GetModifierMapping(display = self.display) return r.keycodes def no_operation(self, onerror = None):", "For the Internet family, it should be the four bytes", "with a subcode, to a tuple of (event,subcode) # note", "self.display.get_default_screen() ### ### Extension module interface ### def extension_add_method(self, object,", "disables the button. Two physical buttons cannot be mapped to", "\"\"\"Set the keycodes for the eight modifiers X.Shift, X.Lock, X.Control,", "list of font names matching pattern. No more than max_names", "of properties. Each entry has two attributes: name The atom", "keysyms is a list of tuples of keysyms. keysyms[n][i] will", "event is fetched from the server.\"\"\" return self.display.next_event() def pending_events(self):", "\"\"\"Return a list of eight lists, one for each modifier.", "requests ### def intern_atom(self, name, only_if_exists = 0): \"\"\"Intern the", "errors. handler should take two arguments as a normal request", "event object to send, instantiated from one of the classes", "can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on. The", "other client connections until the server is ungrabbed. Server grabbing", "= None): self.display = _BaseDisplay(display) # Create the keymap cache", "count for keysym, codes in self._keymap_syms.items(): i = 0 while", "Two physical buttons cannot be mapped to the same logical", "server restriction, X.MappingFailed is returned. Otherwise the mapping is changed", "information retrieval ### def screen(self, sno = None): if sno", "= request.QueryKeymap(display = self.display) return r.map def open_font(self, name): \"\"\"Open", "changed. Otherwise the mapping is changed and X.MappingSuccess is returned.\"\"\"", "will be set to the name of EVT. This name", "all the queued requests. Use this e.g. when it is", "len(codes): code = codes[i][1] if code >= first_keycode and code", "for keys 8N to 8N + 7 with the least", "map[n] sets the logical number for the physical button n+1.", "and X.MappingSuccess is returned.\"\"\" r = request.SetModifierMapping(display = self.display, keycodes", "the mapping is not changed. If the mapping violates some", "if not, write to the # Free Software Foundation, Inc.,", "for the corresponding key. led_mask A 32-bit mask indicating which", "codes lastcode = first_keycode + count for keysym, codes in", "keysyms bound to the key. # The keysym->keycode map is", "cache\"\"\" return self.display.get_atom(atom, only_if_exists) def get_atom_name(self, atom): \"\"\"Look up the", "\"\"\"Ungrab a grabbed keyboard and any queued events. See XUngrabKeyboard(3X11).\"\"\"", "fontable.Fontable, 'font': fontable.Font, 'gc': fontable.GC, 'colormap': colormap.Colormap, 'cursor': cursor.Cursor, }", "32-bit mask listing the LEDs that should change. If led", "X.MappingBusy is returned and the mapping is not changed. If", "if hasattr(self, name): raise AssertionError('attempting to replace display method: %s'", "def keysym_to_keycodes(self, keysym): \"\"\"Look up all the keycodes that is", "def get_keyboard_control(self): \"\"\"Return an object with the following attributes: global_auto_repeat", "object to send, instantiated from one of the classes in", "with two # elements each: (index, keycode) # keycode is", "= prefer_blank, allow_exposures = allow_exposures) def get_screen_saver(self): \"\"\"Return an object", "connect to the server, either provided when creating the Display", "is returned.\"\"\" r = request.QueryExtension(display = self.display, name = name)", "auto_repeats A list of 32 integers. List item N contains", "mode = mode) def force_screen_saver(self, mode, onerror = None): \"\"\"If", "current font path as a list of strings.\"\"\" r =", "syms in keysyms: index = 0 for sym in syms:", "def set_input_focus(self, focus, revert_to, time, onerror = None): \"\"\"Set input", "return self.display.info.roots[self.display.default_screen] else: return self.display.info.roots[sno] def screen_count(self): \"\"\"Return the total", "# don't cache NONE responses in case someone creates this", "the keysyms index in the map for that keycode. def", "events queued, i.e. the number of times that Display.next_event() can", "a keycode, and the tuple elements are # the keysyms", "atom, only_if_exists = 0): \"\"\"Alias for intern_atom, using internal cache\"\"\"", "(C) 2000 <NAME> <<EMAIL>> # # This library is free", "object with the following attributes: mode X.EnableAccess if the access", "normal request error handler, but the second argument (the request)", "and EVT is the event class. EVT will be cloned,", "a list of tuples of keysyms. keysyms[n][i] will be assigned", "X.FamilyDECnet or X.FamilyChaos. host is a list of bytes. For", "control list is used, X.DisableAccess otherwise. hosts The hosts on", "self.display_extension_methods[attr] return types.MethodType(function, self) except KeyError: raise AttributeError(attr) ### ###", "= {} # a dict that maps the event name", "that maps the event name to the code # or,", "return r.keysyms def change_keyboard_control(self, onerror = None, **keys): \"\"\"Change the", "does not match any font, None is returned.\"\"\" fid =", "= codes[i][1] if code >= first_keycode and code < lastcode:", "(class_name, name)) method = create_unbound_method(function, cls) # Maybe should check", "the following attributes: global_auto_repeat X.AutoRepeatModeOn or X.AutoRepeatModeOff. auto_repeats A list", "has processed all the queued requests. Use this e.g. when", "KeyError: return [] def refresh_keyboard_mapping(self, evt): \"\"\"This method should be", "def fileno(self): \"\"\"Returns the file descriptor number of the underlying", "XGetFontProperty(3X11) for details on these values. properties A list of", "keysym_to_keycode(self, keysym): \"\"\"Look up the primary keycode that is bound", "some queued events. mode should be one of X.AsyncPointer, X.SyncPointer,", "line argument. Resource objects should never be created by instantiating", "properties. Each entry has two attributes: name The atom identifying", "rectangle in src_window contains it. If src_width is 0 it", "an extension event. CODE is the numeric code, and EVT", "X.InputFocus. event is the event object to send, instantiated from", "display name.\"\"\" return self.display.get_default_screen() ### ### Extension module interface ###", "error handler, but the second argument (the request) will be", "extensions dynamically added by the library will not be available.", "changed and X.MappingSuccess is returned.\"\"\" r = request.SetPointerMapping(display = self.display,", "state for the entire keyboard will be modified.\"\"\" request.ChangeKeyboardControl(display =", "be set to the name of EVT. This name is", "extracted from the display name.\"\"\" return self.display.get_default_screen() ### ### Extension", "pattern = pattern) def set_font_path(self, path, onerror = None): \"\"\"Set", "is 0 it will be replaced with the width of", "events. mode should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard,", "mappings. Entry N in the list sets the logical button", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See", "for extname, modname in ext.__extensions__: if extname in exts: #", "= 0): \"\"\"Alias for intern_atom, using internal cache\"\"\" return self.display.get_atom(atom,", "self) except KeyError: raise AttributeError(attr) ### ### display information retrieval", "to 1 indicates that the corresponding key is currently pressed", "onerror, revert_to = revert_to, focus = focus, time = time)", "cloned, and the attribute _code of the new event class", "We need this to handle display extension methods def __getattr__(self,", "you can redistribute it and/or # modify it under the", "to the server, either provided when creating the Display object,", "numeric code, and EVT is the event class. EVT will", "= newstring ### ### X requests ### def intern_atom(self, name,", "### ### X requests ### def intern_atom(self, name, only_if_exists =", "= {} self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode - self.display.info.min_keycode + 1)) # Translations", "two attributes: name The atom identifying this property. value A", "bound, X.NoSymbol is returned.\"\"\" try: return self._keymap_codes[keycode][index] except IndexError: return", "newevt, subcode) if name is None: name = evt.__name__ #", "min_byte1 max_byte1 all_chars_exist font_ascent font_descent replies_hint See the descripton of", "name. If it is supported an object with the following", "\"\"\"Returns the name used to connect to the server, either", "provided as keyword arguments: key_click_percent The volume of key clicks", "a list of strings.\"\"\" r = request.GetFontPath(display = self.display) return", "along with this library; if not, write to the #", "is the numeric code, and ERR is the error class.", "2.1 # of the License, or (at your option) any", "entire keyboard will be modified.\"\"\" request.ChangeKeyboardControl(display = self.display, onerror =", "None else: cls = self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid, owner", "index 0 is unshifted, 1 is shifted, 2 is alt", "not exist.\"\"\" r = request.GetAtomName(display = self.display, atom = atom)", "have additional events, or 0. first_error The base error code", "screen.root = self.display.resource_classes['window'](self.display, screen.root.id) screen.default_colormap = self.display.resource_classes['colormap'](self.display, screen.default_colormap.id) def get_display_name(self):", "src_window = X.NONE, src_x = 0, src_y = 0, src_width", "onerror, time = time) def change_active_pointer_grab(self, event_mask, cursor, time, onerror", "of a pointer grab. See XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display = self.display, onerror", "already exist, it will not be created and X.NONE is", "None): \"\"\"Do nothing but send a request to the server.\"\"\"", "number of the underlying socket. This method is provided to", "of the default screen, extracted from the display name.\"\"\" return", "name.\"\"\" return self.display.get_default_screen() ### ### Extension module interface ### def", "A 32-bit mask indicating which LEDs are on. key_click_percent The", "self.display) def bell(self, percent = 0, onerror = None): \"\"\"Ring", "queue and wait until the server has processed all the", "r.status def get_modifier_mapping(self): \"\"\"Return a list of eight lists, one", "should be a timestamp or X.CurrentTime.\"\"\" request.AllowEvents(display = self.display, onerror", "else: do_threshold = 1 request.ChangePointerControl(display = self.display, onerror = onerror,", "evt, name = None): \"\"\"extension_add_event(code, evt, [name]) Add an extension", "defined in Xlib.Xatom def __init__(self, *args, **keys): protocol_display.Display.__init__(self, *args, **keys)", "\"\"\"Set input focus to focus, which should be a window,", "from six import create_unbound_method # Xlib modules from . import", "General Public License for more details. # # You should", "self.display, onerror = onerror, mode = mode) def force_screen_saver(self, mode,", "empty, the default font path of the server will be", "is the 4 bytes of an IPv4 address. \"\"\" return", "numeric code, and ERR is the error class. \"\"\" self.display.add_extension_error(code,", "lists at connection setup if mode is X.EnableAccess, disable if", "the client library support the X extension named extension.\"\"\" return", "not provided, all LEDs are changed. key auto_repeat_mode auto_repeat_mode should", "= accel_num, accel_denum = accel_denum, threshold = threshold) def get_pointer_control(self):", "+ 7 with the least significant bit in the byte", "X.Mod1MapIndex, and so on. The sublists list the keycodes bound", "screen.default_colormap = self.display.resource_classes['colormap'](self.display, screen.default_colormap.id) def get_display_name(self): \"\"\"Returns the name used", "cls = _resource_baseclasses[class_name] if hasattr(cls, name): raise AssertionError('attempting to replace", "in Xlib.Xatom def __init__(self, *args, **keys): protocol_display.Display.__init__(self, *args, **keys) self._atom_cache", "the event object.\"\"\" if isinstance(evt, event.MappingNotify): if evt.request == X.MappingKeyboard:", "None): \"\"\"elease a grabbed pointer and any queued events. See", "else: self.keysym_translations[keysym] = newstring ### ### X requests ### def", "query_extension(self, name): \"\"\"Ask the server if it supports the extension", "= first_keycode, count = count) return r.keysyms def change_keyboard_control(self, onerror", "values are X.RetainPermanent and X.RetainTemporary.\"\"\" request.SetCloseDownMode(display = self.display, onerror =", "only_if_exists is true and the atom does not already exist,", "GNU Lesser General Public License # as published by the", "8N.\"\"\" r = request.QueryKeymap(display = self.display) return r.map def open_font(self,", "is stored in a list with 256 elements. # Each", "the keycodes that should be bound to that modifier. If", "else: return None def list_extensions(self): \"\"\"Return a list of all", "bell, coded as above. bell_pitch The pitch of the bell", "src_y = 0, src_width = 0, src_height = 0, onerror", "self.display) return r.keycodes def no_operation(self, onerror = None): \"\"\"Do nothing", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "returned.\"\"\" r = request.QueryExtension(display = self.display, name = name) if", "XGetScreenSaver(3X11) for details.\"\"\" return request.GetScreenSaver(display = self.display) def change_hosts(self, mode,", "keysyms, onerror = None): \"\"\"Modify the keyboard mapping, starting with", "+ 1 code = code + 1 ### ### client-internal", "by a certain request is trapped.\"\"\" # Do a light-weight", "need this to handle display extension methods def __getattr__(self, attr):", "If NAME is omitted, it will be set to the", "similar way. To move the pointer to absolute coordinates, use", "bell_duration The duration of the bell in milliseconds, -1 restores", "extension.\"\"\" return extension in self.extensions def create_resource_object(self, type, id): \"\"\"Create", "default screen, extracted from the display name.\"\"\" return self.display.get_default_screen() ###", "extensions by creating new classes for class_name, dictionary in self.class_extension_dicts.items():", "if isinstance(evt, event.MappingNotify): if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else:", "allow_exposures. See XGetScreenSaver(3X11) for details.\"\"\" return request.GetScreenSaver(display = self.display) def", "be mapped to the same logical number. If one of", "32-bit unsigned value. \"\"\" return request.ListFontsWithInfo(display = self.display, max_names =", "# extension_event.EXTENSION_EVENT_NAME rather than # extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event = rq.DictWrapper({}) exts", "object with the following attributes: global_auto_repeat X.AutoRepeatModeOn or X.AutoRepeatModeOff. auto_repeats", "import fontable from .xobject import colormap from .xobject import cursor", "pixels at once. To change the threshold, set it to", "from .protocol import request, event, rq # Xlib.xobjects modules from", "directly, since any X extensions dynamically added by the library", "queued events. See XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display = self.display, onerror = onerror,", "freeing the resources that it holds.\"\"\" self.display.close() def set_error_handler(self, handler):", "name The name of the font. min_bounds max_bounds min_char_or_byte2 max_char_or_byte2", "used when a resource ID has been fetched e.g. from", "X.NoSymbol def keysym_to_keycode(self, keysym): \"\"\"Look up the primary keycode that", "in class_list: cls = _resource_baseclasses[class_name] if hasattr(cls, name): raise AssertionError('attempting", "on the lowest index and secondarily on the lowest keycode.\"\"\"", "keyboard mapping, starting with first_keycode. keysyms is a list of", "a string. Will raise BadAtom if atom does not exist.\"\"\"", "return request.GetInputFocus(display = self.display) def query_keymap(self): \"\"\"Return a bit vector", "key. led_mask A 32-bit mask indicating which LEDs are on.", "is one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is a", "return its font object. If name does not match any", "of byte values, the coding depends on family. For the", "display method: %s' % name) self.display_extension_methods[name] = function else: class_list", "this later if r.atom != X.NONE: self._atom_cache[atomname] = r.atom return", "objects to be passed select.select().\"\"\" return self.display.fileno() def close(self): \"\"\"Close", "# Replace code->sym map with the new map self._keymap_codes[first_keycode:lastcode] =", "is returned.\"\"\" try: return self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol def", "a list of all the extensions provided by the server.\"\"\"", "it is X.ScreenSaverReset, the screen saver is deactivated as if", "def get_pointer_control(self): \"\"\"Return an object with the following attributes: accel_num", "of the buttons to be altered are logically in the", "string from this list: display resource drawable window pixmap fontable", "y, src_window = X.NONE, src_x = 0, src_y = 0,", "threshold = threshold) def get_pointer_control(self): \"\"\"Return an object with the", "# Call initialiasation function mod.init(self, info) self.extensions.append(extname) # Finalize extensions", "None): \"\"\"Ring the bell at the volume percent which is", "variable $DISPLAY.\"\"\" return self.display.get_display_name() def fileno(self): \"\"\"Returns the file descriptor", "keysyms to strings. self.keysym_translations = {} # Find all supported", "using X.ShiftMapIndex, X.Mod1MapIndex, and so on. The sublists list the", "have received a copy of the GNU Lesser General Public", "pixels. -1 restores the default.\"\"\" if accel is None: do_accel", "the # extension dict maintained in the display object setattr(self.extension_event,", "buttons cannot be mapped to the same logical number. If", "modules from . import error from . import ext from", "BadAtom.\"\"\" r = request.GetSelectionOwner(display = self.display, selection = selection) return", "+ 1 # Get the new keyboard mapping keysyms =", "request.Bell(display = self.display, onerror = onerror, percent = percent) def", "('drawable', 'window', 'pixmap', 'fontable', 'font', 'gc', 'colormap', 'cursor'), 'drawable': ('window',", "logical number for the physical button n+1. Logical number 0", "resource.Resource, 'drawable': drawable.Drawable, 'window': drawable.Window, 'pixmap': drawable.Pixmap, 'fontable': fontable.Fontable, 'font':", "the file descriptor number of the underlying socket. This method", "if it is X.DisableAccess.\"\"\" request.SetAccessControl(display = self.display, onerror = onerror,", "= self.display, first_keycode = first_keycode, count = count) return r.keysyms", "Add an extension event. CODE is the numeric code, and", "'colormap', 'cursor'), 'drawable': ('window', 'pixmap'), 'fontable': ('font', 'gc') } class", "function to, a string from this list: display resource drawable", "only_if_exists) def get_atom_name(self, atom): \"\"\"Look up the name of atom,", "if sno is None: return self.display.info.roots[self.display.default_screen] else: return self.display.info.roots[sno] def", "None): if sno is None: return self.display.info.roots[self.display.default_screen] else: return self.display.info.roots[sno]", "offsets (x, y). However, if src_window is a window the", "the volume percent which is relative the base volume. See", "dictionary in self.class_extension_dicts.items(): origcls = self.display.resource_classes[class_name] self.display.resource_classes[class_name] = type(origcls.__name__, (origcls,),", "max_names will be returned. Each list item represents one font", "= request.GetAtomName(display = self.display, atom = atom) return r.name def", "which is relative the base volume. See XBell(3X11).\"\"\" request.Bell(display =", "if there is no owner for the selection. Can raise", "both the server and the client library support the X", "queued requests. Use this e.g. when it is important that", "from one of the classes in protocol.events. See XSendEvent(3X11) for", "request.UngrabKeyboard(display = self.display, onerror = onerror, time = time) def", "one font and has the following properties: name The name", "objects should never be created by instantiating the appropriate class", "selection): \"\"\"Return the window that owns selection (an atom), or", "kicks in.\"\"\" return request.GetPointerControl(display = self.display) def set_screen_saver(self, timeout, interval,", "does not already exist, it will not be created and", "# Fix that by reinstantiating them. for screen in self.display.info.roots:", "- src_x. src_height is treated in a similar way. To", "# Xlib.display -- high level display object # # Copyright", "max_char_or_byte2 default_char draw_direction min_byte1 max_byte1 all_chars_exist font_ascent font_descent replies_hint See", "any queued events. See XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display = self.display, onerror =", "either X.HostInsert or X.HostDelete. host_family is one of X.FamilyInternet, X.FamilyDECnet", "the extension have additional events, or 0. first_error The base", "default. led led_mode led_mode should be X.LedModeOff or X.LedModeOn. If", "modify it under the terms of the GNU Lesser General", "the name of EVT. This name is used to insert", "an object with the attributes timeout, interval, prefer_blanking, allow_exposures. See", "name used to connect to the server, either provided when", "the default. bell_duration The duration of the bell in milliseconds,", "def lookup_string(self, keysym): \"\"\"Return a string corresponding to KEYSYM, or", "coding depends on family. For the Internet family, it is", "event name to the code # or, when it's an", "extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event = rq.DictWrapper({}) exts = self.list_extensions() # Go through", "LEDs are changed. key auto_repeat_mode auto_repeat_mode should be one of", "is represented as a list of 32 integers. List item", "code if the extension have additional events, or 0. first_error", "key entry is not bound, X.NoSymbol is returned.\"\"\" try: return", "library is free software; you can redistribute it and/or #", "cursor NAME is the name of the method, a string.", "src_x = 0, src_y = 0, src_width = 0, src_height", "before the acceleration kicks in.\"\"\" return request.GetPointerControl(display = self.display) def", "this extension uses. first_event The base event code if the", "onerror = onerror, mode = mode) def force_screen_saver(self, mode, onerror", "of the underlying socket. This method is provided to allow", "the lowest index and secondarily on the lowest keycode.\"\"\" try:", "important that errors caused by a certain request is trapped.\"\"\"", "default font path of the server will be restored.\"\"\" request.SetFontPath(display", "If key is provided, that key will be modified, otherwise", "error class. \"\"\" self.display.add_extension_error(code, err) ### ### keymap cache implementation", "physical button N+1.\"\"\" r = request.GetPointerMapping(display = self.display) return r.map", "r.keycodes def no_operation(self, onerror = None): \"\"\"Do nothing but send", "pointer buttons. map is a list of logical button numbers.", "get_default_screen(self): \"\"\"Return the number of the default screen, extracted from", "any. \"\"\" if newstring is None: try: del self.keysym_translations[keysym] except", "!= X.NONE: self._atom_cache[atomname] = r.atom return r.atom class Display(object): def", "\"\"\"Close the display, freeing the resources that it holds.\"\"\" self.display.close()", "of the classes in protocol.events. See XSendEvent(3X11) for details. There", "of requests on all other client connections until the server", "keycodes that should be bound to that modifier. If any", "A list of 32 integers. List item N contains the", "return self.display.get_default_screen() ### ### Extension module interface ### def extension_add_method(self,", "in self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym]", "in the down state, X.MappingBusy is returned and the mapping", "in the list sets the logical button number for the", "the Free Software Foundation; either version 2.1 # of the", "= mode, host_family = host_family, host = host) def list_hosts(self):", "key 8N.\"\"\" r = request.QueryKeymap(display = self.display) return r.map def", "socket. This method is provided to allow Display objects to", "be X.LedModeOff or X.LedModeOn. If led is provided, it should", "X.DestroyAll, the other values are X.RetainPermanent and X.RetainTemporary.\"\"\" request.SetCloseDownMode(display =", "len(self.display.info.roots) def get_default_screen(self): \"\"\"Return the number of the default screen,", "or X.SyncBoth. time should be a timestamp or X.CurrentTime.\"\"\" request.AllowEvents(display", "\"\"\"add_extension_error(code, err) Add an extension error. CODE is the numeric", "led is provided, it should be a 32-bit mask listing", "= evt.__name__ # store subcodes as a tuple of (event", "host_family = host_family, host = host) def list_hosts(self): \"\"\"Return an", "# modify it under the terms of the GNU Lesser", "the server.\"\"\" return self.display.next_event() def pending_events(self): \"\"\"Return the number of", "def ungrab_server(self, onerror = None): \"\"\"Release the server if it", "mapping is not changed. Otherwise the mapping is changed and", "syms: if sym != X.NoSymbol: if sym in self._keymap_syms: symcodes", "See XSetInputFocus(3X11) for details. There is also a Window.set_input_focus().\"\"\" request.SetInputFocus(display", "XBell(3X11).\"\"\" request.Bell(display = self.display, onerror = onerror, percent = percent)", "def set_pointer_mapping(self, map): \"\"\"Set the mapping of the pointer buttons.", "types.MethodType(function, self) except KeyError: raise AttributeError(attr) ### ### display information", "= evt.__name__ setattr(self.extension_event, name, code) def extension_add_subevent(self, code, subcode, evt,", "None): \"\"\"mode is either X.HostInsert or X.HostDelete. host_family is one", "holds.\"\"\" self.display.close() def set_error_handler(self, handler): \"\"\"Set the default error handler", "name, returning its atom number. If only_if_exists is true and", "= onerror) def ungrab_server(self, onerror = None): \"\"\"Release the server", "identifed by the pattern name and return its font object.", "font_descent replies_hint See the descripton of XFontStruct in XGetFontProperty(3X11) for", "the buttons to be altered are logically in the down", "= request.GetPointerMapping(display = self.display) return r.map def set_modifier_mapping(self, keycodes): \"\"\"Set", "a pointer grab. See XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display = self.display, onerror =", "License along with this library; if not, write to the", "keycode that is bound to keysym. If several keycodes are", "ungrab_pointer(self, time, onerror = None): \"\"\"elease a grabbed pointer and", "to focus, which should be a window, X.PointerRoot or X.NONE.", "max_names): \"\"\"Return a list of fonts matching pattern. No more", "descripton of XFontStruct in XGetFontProperty(3X11) for details on these values.", "listing the LEDs that should change. If led is not", "state of the keyboard, where each bit set to 1", "= _resource_baseclasses.copy() # Implement a cache of atom names, used", "keymap cache self._keymap_codes = [()] * 256 self._keymap_syms = {}", "Display objects to be passed select.select().\"\"\" return self.display.fileno() def close(self):", "bits for keys 8N to 8N + 7 with the", "# Boston, MA 02111-1307 USA # Python modules import types", "def close(self): \"\"\"Close the display, freeing the resources that it", "Add an extension error. CODE is the numeric code, and", "else: i = i + 1 # Get the new", "-1 will restore default setting. bell_percent The base volume of", "at connection close. The default is X.DestroyAll, the other values", "better way to do it... self.get_pointer_control() def next_event(self): \"\"\"Return the", "display information retrieval ### def screen(self, sno = None): if", "name, (code,subcode)) def add_extension_error(self, code, err): \"\"\"add_extension_error(code, err) Add an", "X.Shift, X.Lock, X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes", "a list of strings. If path is empty, the default", "will restore default setting. bell_percent The base volume of the", "created by instantiating the appropriate class directly, since any X", "= only_if_exists) # don't cache NONE responses in case someone", "(x, y). However, if src_window is a window the pointer", "= event) def ungrab_pointer(self, time, onerror = None): \"\"\"elease a", "open_font(self, name): \"\"\"Open the font identifed by the pattern name", "There must # be a better way to do it...", "4 bytes of an IPv4 address. \"\"\" return request.ListHosts(display =", "None): \"\"\"Enable use of access control lists at connection setup", "= onerror, mode = mode) def force_screen_saver(self, mode, onerror =", "is found. \"\"\" s = self.keysym_translations.get(keysym) if s is not", "the following strings: resource drawable window pixmap fontable font gc", "path, which should be a list of strings. If path", "in keysyms: index = 0 for sym in syms: if", "rq.DictWrapper({}) exts = self.list_extensions() # Go through all extension modules", "\"\"\" newevt = type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code,", "a eight-element list where each entry is a list of", "If the mapping violates some server restriction, X.MappingFailed is returned.", "Create the keymap cache self._keymap_codes = [()] * 256 self._keymap_syms", "XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display = self.display, onerror = onerror, time = time)", "note this wraps the dict so you address it as", "if any. \"\"\" if newstring is None: try: del self.keysym_translations[keysym]", "resource object of type for the integer id. type should", "# Free Software Foundation, Inc., # 59 Temple Place, #", "= self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym] = [(index, code)]", "1 code = code + 1 ### ### client-internal keysym", "See XBell(3X11).\"\"\" request.Bell(display = self.display, onerror = onerror, percent =", "be a better way to do it... self.get_pointer_control() def next_event(self):", "value A 32-bit unsigned value. \"\"\" return request.ListFontsWithInfo(display = self.display,", "the physical button n+1. Logical number 0 disables the button.", "# note this wraps the dict so you address it", "function): \"\"\"extension_add_method(object, name, function) Add an X extension module method.", "more than count.\"\"\" r = request.GetKeyboardMapping(display = self.display, first_keycode =", "modname) mod = getattr(ext, modname) info = self.query_extension(extname) self.display.set_extension_major(extname, info.major_opcode)", "= y) def set_input_focus(self, focus, revert_to, time, onerror = None):", "X.HostDelete. host_family is one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host", "as a string. Will raise BadAtom if atom does not", "of src_window - src_x. src_height is treated in a similar", "allow_exposures = allow_exposures) def get_screen_saver(self): \"\"\"Return an object with the", "is None, remove old translation if any. \"\"\" if newstring", "return r.owner def send_event(self, destination, event, event_mask = 0, propagate", "fetched from the server.\"\"\" return self.display.next_event() def pending_events(self): \"\"\"Return the", "= _resource_baseclasses[class_name] if hasattr(cls, name): raise AssertionError('attempting to replace %s", "are found, the one with the lowest index and lowest", "\"\"\"Return the number of the default screen, extracted from the", "= interval, prefer_blank = prefer_blank, allow_exposures = allow_exposures) def get_screen_saver(self):", "\"\"\"Return a list of the pointer button mappings. Entry N", "one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is a list", "keysyms = keysyms) def get_keyboard_mapping(self, first_keycode, count): \"\"\"Return the current", "path as a list of strings.\"\"\" r = request.GetFontPath(display =", "the attribute _code of the new event class will be", "the code for a key to which this keysym is", "keycode. def keycode_to_keysym(self, keycode, index): \"\"\"Convert a keycode to a", "= pattern) def set_font_path(self, path, onerror = None): \"\"\"Set the", "created some objects without the # extensions: the screen roots", "the entire keyboard will be modified.\"\"\" request.ChangeKeyboardControl(display = self.display, onerror", "onerror = None): \"\"\"If mode is X.ScreenSaverActive the screen saver", "server is ungrabbed. Server grabbing should be avoided as much", "do_threshold, accel_num = accel_num, accel_denum = accel_denum, threshold = threshold)", "{} # a dict that maps the event name to", "this client.\"\"\" request.UngrabServer(display = self.display, onerror = onerror) def warp_pointer(self,", "self.display.fileno() def close(self): \"\"\"Close the display, freeing the resources that", "+ 1)) # Translations for keysyms to strings. self.keysym_translations =", "X.PointerWindow or X.InputFocus. event is the event object to send,", "self.display.flush() def sync(self): \"\"\"Flush the queue and wait until the", "0. first_error The base error code if the extension have", "self.display.set_extension_major(extname, info.major_opcode) # Call initialiasation function mod.init(self, info) self.extensions.append(extname) #", "with the lowest index and lowest code is returned. If", "extension have additional errors, or 0. If the extension is", "= onerror, timeout = timeout, interval = interval, prefer_blank =", "be restored.\"\"\" request.SetFontPath(display = self.display, onerror = onerror, path =", "code, evt, name = None): \"\"\"extension_add_event(code, evt, [name]) Add an", "bell_duration The volume, pitch and duration of the bell. \"\"\"", "accel_denom The acceleration as numerator/denumerator. threshold The number of pixels", "will be cloned, and the attribute _code of the new", "\"\"\"elease a grabbed pointer and any queued events. See XUngrabPointer(3X11).\"\"\"", "acceleration as numerator/denumerator. threshold The number of pixels the pointer", "auto_repeat_mode auto_repeat_mode should be one of X.AutoRepeatModeOff, X.AutoRepeatModeOn, or X.AutoRepeatModeDefault.", "accel_num accel_denom The acceleration as numerator/denumerator. threshold The number of", "fid = fid, name = name) self.sync() if ec.get_error(): self.display.free_resource_id(fid)", "= self.display) def bell(self, percent = 0, onerror = None):", "screen saver is activated. If it is X.ScreenSaverReset, the screen", "will not be created and X.NONE is returned.\"\"\" r =", "what will happen with the client's resources at connection close.", "violates some server restriction, X.MappingFailed is returned. Otherwise the mapping", "__init__(self, *args, **keys): protocol_display.Display.__init__(self, *args, **keys) self._atom_cache = {} def", "by Window objects when # dealing with some ICCCM properties", "ungrabbed. Server grabbing should be avoided as much as possible.\"\"\"", "eight modifiers X.Shift, X.Lock, X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and", "X.AutoRepeatModeOn or X.AutoRepeatModeOff. auto_repeats A list of 32 integers. List", "onerror = None): \"\"\"Set the font path to path, which", "change the pointer acceleration, set accel to a tuple (num,", "object to add the function to, a string from this", "Xlib.protocol modules from .protocol import display as protocol_display from .protocol", "be modified.\"\"\" request.ChangeKeyboardControl(display = self.display, onerror = onerror, attrs =", "same length as the list returned by Display.get_pointer_mapping(). map[n] sets", "of the GNU Lesser General Public # License along with", "fonts matching pattern. No more than max_names will be returned.", "at the volume percent which is relative the base volume.", "class. EVT will be cloned, and the attribute _code of", "trapped.\"\"\" # Do a light-weight replyrequest to sync. There must", "onerror = onerror, mode = mode) def set_pointer_mapping(self, map): \"\"\"Set", "new classes for class_name, dictionary in self.class_extension_dicts.items(): origcls = self.display.resource_classes[class_name]", "in syms: if sym != X.NoSymbol: if sym in self._keymap_syms:", "or fetched from the environmental variable $DISPLAY.\"\"\" return self.display.get_display_name() def", "Python modules import types # Python 2/3 compatibility. from six", "\"\"\"Return a list of all the extensions provided by the", "X.RetainTemporary.\"\"\" request.SetCloseDownMode(display = self.display, onerror = onerror, mode = mode)", "= r.atom return r.atom class Display(object): def __init__(self, display =", "default setting. bell_percent The base volume of the bell, coded", "X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is a list of bytes.", "pattern) return r.fonts def list_fonts_with_info(self, pattern, max_names): \"\"\"Return a list", "down state, X.MappingBusy is returned and the mapping is not", "import Xlib.XK return Xlib.XK.keysym_to_string(keysym) def rebind_string(self, keysym, newstring): \"\"\"Change the", "it will be useful, # but WITHOUT ANY WARRANTY; without", "num/denum times the normal speed if it moves beyond the", "to a tuple of (event,subcode) # note this wraps the", "self.display.info.roots[self.display.default_screen] else: return self.display.info.roots[sno] def screen_count(self): \"\"\"Return the total number", "sub-events and EVT is the event class. EVT will be", "is returned.\"\"\" try: return self._keymap_syms[keysym][0][1] except (KeyError, IndexError): return 0", "extension module method. OBJECT is the type of object to", "newstring is None: try: del self.keysym_translations[keysym] except KeyError: pass else:", "since any X extensions dynamically added by the library will", "mode, time = time) def grab_server(self, onerror = None): \"\"\"Disable", "extension named extension.\"\"\" return extension in self.extensions def create_resource_object(self, type,", "key is logically in the down state, X.MappingBusy is returned", "of an IPv4 address.\"\"\" request.ChangeHosts(display = self.display, onerror = onerror,", "the specified rectangle in src_window contains it. If src_width is", "the name of the method, a string. FUNCTION is a", "# Do a light-weight replyrequest to sync. There must #", "on, autorepeat is enabled for the corresponding key. led_mask A", "the attributes timeout, interval, prefer_blanking, allow_exposures. See XGetScreenSaver(3X11) for details.\"\"\"", "None: return self.display.info.roots[self.display.default_screen] else: return self.display.info.roots[sno] def screen_count(self): \"\"\"Return the", "= type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt) if", "hope that it will be useful, # but WITHOUT ANY", "Inc., # 59 Temple Place, # Suite 330, # Boston,", ") + _resource_hierarchy.get(object, ()) for class_name in class_list: cls =", "where each bit set to 1 indicates that the corresponding", "import display as protocol_display from .protocol import request, event, rq", "self.list_extensions() # Go through all extension modules for extname, modname", "is a 'self'. \"\"\" if object == 'display': if hasattr(self,", "None): \"\"\"Set the font path to path, which should be", "X.HostInsert or X.HostDelete. host_family is one of X.FamilyInternet, X.FamilyDECnet or", "not visible, and should be X.RevertToParent, RevertToPointerRoot, or RevertToNone. See", "interval, prefer_blank, allow_exposures, onerror = None): \"\"\"See XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display =", "from .xobject import colormap from .xobject import cursor _resource_baseclasses =", "is also a Window.set_input_focus().\"\"\" request.SetInputFocus(display = self.display, onerror = onerror,", "six import create_unbound_method # Xlib modules from . import error", "= request.InternAtom(display = self.display, name = name, only_if_exists = only_if_exists)", "second argument (the request) will be None. See section Error", "the display.\"\"\" return len(self.display.info.roots) def get_default_screen(self): \"\"\"Return the number of", "1) def list_fonts(self, pattern, max_names): \"\"\"Return a list of font", "setup if mode is X.EnableAccess, disable if it is X.DisableAccess.\"\"\"", "number of events queued, i.e. the number of times that", "queued requests. This can be necessary in applications that never", "property. value A 32-bit unsigned value. \"\"\" return request.ListFontsWithInfo(display =", "mode, onerror = None): \"\"\"Control what will happen with the", "X.NoSymbol: if sym in self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index, code))", "for a key to which this keysym is bound, and", "this event that shares the code ID with other sub-events", "fontable.GC, 'colormap': colormap.Colormap, 'cursor': cursor.Cursor, } _resource_hierarchy = { 'resource':", "queued events. See XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display = self.display, onerror = onerror,", "self.display.resource_classes['window'](self.display, screen.root.id) screen.default_colormap = self.display.resource_classes['colormap'](self.display, screen.default_colormap.id) def get_display_name(self): \"\"\"Returns the", "the font identifed by the pattern name and return its", "more than max_names will be returned. Each list item represents", "None: do_threshold = 0 else: do_threshold = 1 request.ChangePointerControl(display =", "the License, or (at your option) any later version. #", "= function else: class_list = (object, ) + _resource_hierarchy.get(object, ())", "autorepeat is enabled for the corresponding key. led_mask A 32-bit", "= time) def get_input_focus(self): \"\"\"Return an object with the following", "accel_denum, threshold = threshold) def get_pointer_control(self): \"\"\"Return an object with", "of the new event class will be set to CODE.", "coordinates, use Window.warp_pointer().\"\"\" request.WarpPointer(display = self.display, onerror = onerror, src_window", "is either X.HostInsert or X.HostDelete. host_family is one of X.FamilyInternet,", "replies_hint See the descripton of XFontStruct in XGetFontProperty(3X11) for details", "a tuple (num, denum). The pointer will then move num/denum", "= self.display) def query_keymap(self): \"\"\"Return a bit vector for the", "= type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt, subcode)", "change_hosts(self, mode, host_family, host, onerror = None): \"\"\"mode is either", "\"\"\"Change the dynamic parameters of a pointer grab. See XChangeActivePointerGrab(3X11).\"\"\"", "the logical button number for the physical button N+1.\"\"\" r", "Software Foundation; either version 2.1 # of the License, or", "src_x = src_x, src_y = src_y, src_width = src_width, src_height", "= self.display, onerror = onerror, cursor = cursor, time =", "of the keycodes that should be bound to that modifier.", "map for that keycode. def keycode_to_keysym(self, keycode, index): \"\"\"Convert a", "Handling.\"\"\" self.display.set_error_handler(handler) def flush(self): \"\"\"Flush the request queue, building and", "keysym->keycode map is stored in a mapping, where the keys", "to, a string from this list: display resource drawable window", "key_click_percent The volume of key click, from 0 to 100.", "only moved if the specified rectangle in src_window contains it.", "is supported an object with the following attributes is returned:", "logical button numbers. map must be of the same length", "request.SetCloseDownMode(display = self.display, onerror = onerror, mode = mode) def", "if it was previously grabbed by this client.\"\"\" request.UngrabServer(display =", "pattern. No more than max_names will be returned. Each list", "function, called to refresh the keymap cache. \"\"\" # Delete", "= request.GetKeyboardMapping(display = self.display, first_keycode = first_keycode, count = count)", "= self.display.resource_classes['window'](self.display, screen.root.id) screen.default_colormap = self.display.resource_classes['colormap'](self.display, screen.default_colormap.id) def get_display_name(self): \"\"\"Returns", "volume of the bell, coded as above. bell_pitch The pitch", "which should be a window, X.PointerRoot or X.NONE. revert_to specifies", "is returned.\"\"\" r = request.SetModifierMapping(display = self.display, keycodes = keycodes)", "block until the next event is fetched from the server.\"\"\"", "translations ### def lookup_string(self, keysym): \"\"\"Return a string corresponding to", "\"\"\"Flush the queue and wait until the server has processed", "set_screen_saver(self, timeout, interval, prefer_blank, allow_exposures, onerror = None): \"\"\"See XSetScreenSaver(3X11).\"\"\"", "cache. evt should be the event object.\"\"\" if isinstance(evt, event.MappingNotify):", "\"\"\"Return a string corresponding to KEYSYM, or None if no", "force_screen_saver(self, mode, onerror = None): \"\"\"If mode is X.ScreenSaverActive the", "mask indicating which LEDs are on. key_click_percent The volume of", "index is the keysyms index in the map for that", "objects without the # extensions: the screen roots and default", "symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym] = [(index, code)] index =", "newstring): \"\"\"Change the translation of KEYSYM to NEWSTRING. If NEWSTRING", "its font object. If name does not match any font,", "= request.ListFonts(display = self.display, max_names = max_names, pattern = pattern)", "USA # Python modules import types # Python 2/3 compatibility.", "# keycode is the code for a key to which", "replyrequest to sync. There must # be a better way", "(code,subcode)) def add_extension_error(self, code, err): \"\"\"add_extension_error(code, err) Add an extension", "onerror = onerror, propagate = propagate, destination = destination, event_mask", "(self.display.info.max_keycode - self.display.info.min_keycode + 1)) # Translations for keysyms to", "\"\"\" if object == 'display': if hasattr(self, name): raise AssertionError('attempting", "on the access list. Each entry has the following attributes:", "1 ### ### client-internal keysym to string translations ### def", "# extensions: the screen roots and default colormaps. # Fix", "None, remove old translation if any. \"\"\" if newstring is", "if accel is None: do_accel = 0 accel_num = 0", "index): \"\"\"Convert a keycode to a keysym, looking in entry", "is provided to allow Display objects to be passed select.select().\"\"\"", "have already created some objects without the # extensions: the", "# The keysym->keycode map is stored in a mapping, where", "with the following attributes: accel_num accel_denom The acceleration as numerator/denumerator.", "selection (an atom), or X.NONE if there is no owner", "drawable.Drawable, 'window': drawable.Window, 'pixmap': drawable.Pixmap, 'fontable': fontable.Fontable, 'font': fontable.Font, 'gc':", "name): \"\"\"Open the font identifed by the pattern name and", "server if it supports the extension name. If it is", "The base volume of the bell, coded as above. bell_pitch", "and the atom does not already exist, it will not", "_BaseDisplay(protocol_display.Display): resource_classes = _resource_baseclasses.copy() # Implement a cache of atom", "details. There is also a Window.send_event() method.\"\"\" request.SendEvent(display = self.display,", "request.AllowEvents(display = self.display, onerror = onerror, mode = mode, time", "list_fonts(self, pattern, max_names): \"\"\"Return a list of font names matching", "The volume of key clicks between 0 (off) and 100", "request) will be None. See section Error Handling.\"\"\" self.display.set_error_handler(handler) def", "__init__(self, display = None): self.display = _BaseDisplay(display) # Create the", "be called once when a MappingNotify event is received, to", "KEYSYM, or None if no reasonable translation is found. \"\"\"", "one of the classes in protocol.events. See XSendEvent(3X11) for details.", "threshold, set it to the number of pixels. -1 restores", "if the access control list is used, X.DisableAccess otherwise. hosts", "time) def allow_events(self, mode, time, onerror = None): \"\"\"Release some", "list_hosts(self): \"\"\"Return an object with the following attributes: mode X.EnableAccess", "accel_num, accel_denum = accel_denum, threshold = threshold) def get_pointer_control(self): \"\"\"Return", "is activated. If it is X.ScreenSaverReset, the screen saver is", "between 0 (off) and 100 (load). -1 will restore default", "display.\"\"\" return len(self.display.info.roots) def get_default_screen(self): \"\"\"Return the number of the", "modifier. If any changed key is logically in the down", "moves beyond the threshold number of pixels at once. To", "published by the Free Software Foundation; either version 2.1 #", "= self.display, max_names = max_names, pattern = pattern) return r.fonts", "string name, returning its atom number. If only_if_exists is true", "timestamp or X.CurrentTime.\"\"\" request.AllowEvents(display = self.display, onerror = onerror, mode", "with the client's resources at connection close. The default is", "Xlib.Xatom def __init__(self, *args, **keys): protocol_display.Display.__init__(self, *args, **keys) self._atom_cache =", "is free software; you can redistribute it and/or # modify", "maps for the changed codes lastcode = first_keycode + count", "of this extension uses. first_event The base event code if", "family X.FamilyInternet, X.FamilyDECnet, or X.FamilyChaos. name A list of byte", "def sync(self): \"\"\"Flush the queue and wait until the server", "attrs = keys) def get_keyboard_control(self): \"\"\"Return an object with the", "other values are X.RetainPermanent and X.RetainTemporary.\"\"\" request.SetCloseDownMode(display = self.display, onerror", "(x[1], x[0]), self._keymap_syms[keysym]) except KeyError: return [] def refresh_keyboard_mapping(self, evt):", "s import Xlib.XK return Xlib.XK.keysym_to_string(keysym) def rebind_string(self, keysym, newstring): \"\"\"Change", "indicating which LEDs are on. key_click_percent The volume of key", "be a list of strings. If path is empty, the", "The duration of the bell in milliseconds, -1 restores the", "for that keycode. def keycode_to_keysym(self, keycode, index): \"\"\"Convert a keycode", "type for the integer id. type should be one of", "def get_selection_owner(self, selection): \"\"\"Return the window that owns selection (an", "in a similar way. To move the pointer to absolute", "the integer id. type should be one of the following", "called once when a MappingNotify event is received, to update", "indicates that the corresponding key is currently pressed down. The", "first_keycode, count = count) return r.keysyms def change_keyboard_control(self, onerror =", ">= first_keycode and code < lastcode: del codes[i] else: i", "close. The default is X.DestroyAll, the other values are X.RetainPermanent", "self.display) return r.map def set_modifier_mapping(self, keycodes): \"\"\"Set the keycodes for", "None): \"\"\"Ungrab a grabbed keyboard and any queued events. See", "to that modifier. If any changed key is logically in", "the hope that it will be useful, # but WITHOUT", "the code ID with other sub-events and EVT is the", "request.GetAtomName(display = self.display, atom = atom) return r.name def get_selection_owner(self,", "arguments as a normal request error handler, but the second", "bell in Hz, -1 restores the default. bell_duration The duration", "# Find all supported extensions self.extensions = [] self.class_extension_dicts =", "0, onerror = None): \"\"\"Ring the bell at the volume", "new keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode, count) # Replace code->sym", "set_close_down_mode(self, mode, onerror = None): \"\"\"Control what will happen with", "or X.NONE if there is no owner for the selection.", "supported an object with the following attributes is returned: major_opcode", "is also a Window.send_event() method.\"\"\" request.SendEvent(display = self.display, onerror =", "time should be a timestamp or X.CurrentTime.\"\"\" request.AllowEvents(display = self.display,", "by the library will not be available. \"\"\" return self.display.resource_classes[type](self.display,", "number of pixels at once. To change the threshold, set", "list is used, X.DisableAccess otherwise. hosts The hosts on the", "it will be replaced with the width of src_window -", "name)) method = create_unbound_method(function, cls) # Maybe should check extension", "dst_y = y) def set_input_focus(self, focus, revert_to, time, onerror =", "of (event,subcode) # note this wraps the dict so you", "class_name in class_list: cls = _resource_baseclasses[class_name] if hasattr(cls, name): raise", "# Go through all extension modules for extname, modname in", "src_width = 0, src_height = 0, onerror = None): \"\"\"Move", "only_if_exists=0): if atomname in self._atom_cache: return self._atom_cache[atomname] r = request.InternAtom(display", "return self.display.next_event() def pending_events(self): \"\"\"Return the number of events queued,", "= None): \"\"\"Ungrab a grabbed keyboard and any queued events.", "window the pointer is only moved if the specified rectangle", "list of properties. Each entry has two attributes: name The", "led led_mode led_mode should be X.LedModeOff or X.LedModeOn. If led", "do_accel, do_thres = do_threshold, accel_num = accel_num, accel_denum = accel_denum,", "is not None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym) def", "the server if it was previously grabbed by this client.\"\"\"", "or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU", "Extension module interface ### def extension_add_method(self, object, name, function): \"\"\"extension_add_method(object,", "necessary in applications that never wait for events, and in", "changed codes lastcode = first_keycode + count for keysym, codes", "its atom number. If only_if_exists is true and the atom", "path) def get_font_path(self): \"\"\"Return the current font path as a", "pointer acceleration, set accel to a tuple (num, denum). The", "FOR A PARTICULAR PURPOSE. # See the GNU Lesser General", "cache. \"\"\" # Delete all sym->code maps for the changed", "return self.display.info.roots[sno] def screen_count(self): \"\"\"Return the total number of screens", "revert_to specifies where the focus reverts to if the focused", "is a list of the keycodes that should be bound", "get_pointer_control(self): \"\"\"Return an object with the following attributes: accel_num accel_denom", "grabbed by this client.\"\"\" request.UngrabServer(display = self.display, onerror = onerror)", "window that owns selection (an atom), or X.NONE if there", "list of eight lists, one for each modifier. The list", "count): \"\"\"Internal function, called to refresh the keymap cache. \"\"\"", "name of the font. min_bounds max_bounds min_char_or_byte2 max_char_or_byte2 default_char draw_direction", "except KeyError: return [] def refresh_keyboard_mapping(self, evt): \"\"\"This method should", "should be a list of strings. If path is empty,", "\"\"\"Send a synthetic event to the window destination which can", "default is X.DestroyAll, the other values are X.RetainPermanent and X.RetainTemporary.\"\"\"", "subcodes as a tuple of (event code, subcode) in the", "None: do_accel = 0 accel_num = 0 accel_denum = 0", "= 1 accel_num, accel_denum = accel if threshold is None:", "The values are a sorted list of tuples with two", "def warp_pointer(self, x, y, src_window = X.NONE, src_x = 0,", "some ICCCM properties not defined in Xlib.Xatom def __init__(self, *args,", "} _resource_hierarchy = { 'resource': ('drawable', 'window', 'pixmap', 'fontable', 'font',", "'gc', 'colormap', 'cursor'), 'drawable': ('window', 'pixmap'), 'fontable': ('font', 'gc') }", "src_width is 0 it will be replaced with the width", "for events, and in threaded applications.\"\"\" self.display.flush() def sync(self): \"\"\"Flush", "= self.display, onerror = onerror, src_window = src_window, dst_window =", "percent) def change_pointer_control(self, accel = None, threshold = None, onerror", "not, write to the # Free Software Foundation, Inc., #", "tuple of (event code, subcode) in the # extension dict", "allow Display objects to be passed select.select().\"\"\" return self.display.fileno() def", "\"\"\"Return an object with the attributes timeout, interval, prefer_blanking, allow_exposures.", "class_list: cls = _resource_baseclasses[class_name] if hasattr(cls, name): raise AssertionError('attempting to", "onerror = None): \"\"\"Release the server if it was previously", "instantiating the appropriate class directly, since any X extensions dynamically", "default colormaps. # Fix that by reinstantiating them. for screen", "= i + 1 # Get the new keyboard mapping", "import request, event, rq # Xlib.xobjects modules from .xobject import", "revert_to, focus = focus, time = time) def get_input_focus(self): \"\"\"Return", "bit in the byte representing key 8N.\"\"\" r = request.QueryKeymap(display", "distributed in the hope that it will be useful, #", "symcodes.sort() else: self._keymap_syms[sym] = [(index, code)] index = index +", "colormap from .xobject import cursor _resource_baseclasses = { 'resource': resource.Resource,", "to keysym. A list of tuples (keycode, index) is returned,", "self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym] =", "= self.display, name = name, only_if_exists = only_if_exists) return r.atom", "new event class will be set to CODE. If NAME", "the default screen, extracted from the display name.\"\"\" return self.display.get_default_screen()", "up the name of atom, returning it as a string.", "self.display, onerror = onerror, percent = percent) def change_pointer_control(self, accel", "already created some objects without the # extensions: the screen", "return request.GetScreenSaver(display = self.display) def change_hosts(self, mode, host_family, host, onerror", "(origcls,), dictionary) # Problem: we have already created some objects", "self.display.resource_classes[class_name] = type(origcls.__name__, (origcls,), dictionary) # Problem: we have already", "is trapped.\"\"\" # Do a light-weight replyrequest to sync. There", "returned.\"\"\" try: return self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol def keysym_to_keycode(self,", "= src_x, src_y = src_y, src_width = src_width, src_height =", "code if the extension have additional errors, or 0. If", "duration of the bell. \"\"\" return request.GetKeyboardControl(display = self.display) def", "rather than # extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event = rq.DictWrapper({}) exts = self.list_extensions()", "the code # or, when it's an event with a", "a normal function whose first argument is a 'self'. \"\"\"", "or X.InputFocus. event is the event object to send, instantiated", "handler should take two arguments as a normal request error", "onerror = None): \"\"\"See XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display = self.display, onerror =", "module and fetch it __import__('Xlib.ext.' + modname) mod = getattr(ext,", "at once. To change the threshold, set it to the", "first_keycode, count): \"\"\"Return the current keyboard mapping as a list", "to absolute coordinates, use Window.warp_pointer().\"\"\" request.WarpPointer(display = self.display, onerror =", "to the same logical number. If one of the buttons", "as published by the Free Software Foundation; either version 2.1", "fetch it __import__('Xlib.ext.' + modname) mod = getattr(ext, modname) info", "has two attributes: name The atom identifying this property. value", "X.ScreenSaverReset, the screen saver is deactivated as if device input", "= first_keycode for syms in keysyms: index = 0 for", "integers. List item N contains the bits for keys 8N", "(num, denum). The pointer will then move num/denum times the", "Foundation, Inc., # 59 Temple Place, # Suite 330, #", "a list with 256 elements. # Each element represents a", "values, the coding depends on family. For the Internet family,", "import drawable from .xobject import fontable from .xobject import colormap", "display object setattr(self.extension_event, name, (code,subcode)) def add_extension_error(self, code, err): \"\"\"add_extension_error(code,", "max_names will be returned.\"\"\" r = request.ListFonts(display = self.display, max_names", "fontable font gc colormap cursor This function can be used", "info) self.extensions.append(extname) # Finalize extensions by creating new classes for", "= None): \"\"\"Move the pointer relative its current position by", "the following attributes: focus The window which currently holds the", "the queued requests. Use this e.g. when it is important", "attr): try: function = self.display_extension_methods[attr] return types.MethodType(function, self) except KeyError:", "import colormap from .xobject import cursor _resource_baseclasses = { 'resource':", "is provided, it should be a 32-bit mask listing the", "tuple elements are # the keysyms bound to the key.", "\"\"\"See XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display = self.display, onerror = onerror, timeout =", "onerror = None): \"\"\"Control what will happen with the client's", "index) is returned, sorted primarily on the lowest index and", "the bell, coded as above. bell_pitch The pitch of the", "the normal speed if it moves beyond the threshold number", "font gc colormap cursor NAME is the name of the", "= self, name = atomname, only_if_exists = only_if_exists) # don't", "KeyError: raise AttributeError(attr) ### ### display information retrieval ### def", "set accel to a tuple (num, denum). The pointer will", "error from . import ext from . import X #", "= onerror, first_keycode = first_keycode, keysyms = keysyms) def get_keyboard_mapping(self,", "= map) return r.status def get_pointer_mapping(self): \"\"\"Return a list of", "Lesser General Public License for more details. # # You", "major opcode that the requests of this extension uses. first_event", "a list of the pointer button mappings. Entry N in", "Each entry has the following attributes: family X.FamilyInternet, X.FamilyDECnet, or", "If it is supported an object with the following attributes", "used by Window objects when # dealing with some ICCCM", "the font. min_bounds max_bounds min_char_or_byte2 max_char_or_byte2 default_char draw_direction min_byte1 max_byte1", "lastcode: del codes[i] else: i = i + 1 #", "src_y, src_width = src_width, src_height = src_height, dst_x = x,", "reverts to if the focused window becomes not visible, and", "with the least significant bit in the byte representing key", "name The atom identifying this property. value A 32-bit unsigned", "bell in milliseconds, -1 restores the default. led led_mode led_mode", "for details.\"\"\" return request.GetScreenSaver(display = self.display) def change_hosts(self, mode, host_family,", "keycode_to_keysym(self, keycode, index): \"\"\"Convert a keycode to a keysym, looking", "applications that never wait for events, and in threaded applications.\"\"\"", "self.keysym_translations.get(keysym) if s is not None: return s import Xlib.XK", "request.GetInputFocus(display = self.display) def query_keymap(self): \"\"\"Return a bit vector for", "tuple of (event,subcode) # note this wraps the dict so", "code self.display.add_extension_event(code, newevt) if name is None: name = evt.__name__", "keysyms # Update sym->code map code = first_keycode for syms", "the request queue, building and sending the queued requests. This", "object == 'display': if hasattr(self, name): raise AssertionError('attempting to replace", "set_pointer_mapping(self, map): \"\"\"Set the mapping of the pointer buttons. map", "accel_num = accel_num, accel_denum = accel_denum, threshold = threshold) def", "extension in self.extensions def create_resource_object(self, type, id): \"\"\"Create a resource", "time = time, event_mask = event_mask) def ungrab_keyboard(self, time, onerror", "atom): \"\"\"Look up the name of atom, returning it as", "some server restriction, X.MappingFailed is returned. Otherwise the mapping is", "[] def refresh_keyboard_mapping(self, evt): \"\"\"This method should be called once", "= time) def change_active_pointer_grab(self, event_mask, cursor, time, onerror = None):", "if it moves beyond the threshold number of pixels at", "number. If only_if_exists is true and the atom does not", "r.atom != X.NONE: self._atom_cache[atomname] = r.atom return r.atom class Display(object):", "destination, event_mask = event_mask, event = event) def ungrab_pointer(self, time,", "be called without blocking.\"\"\" return self.display.pending_events() def has_extension(self, extension): \"\"\"Check", "of tuples, starting at first_keycount and no more than count.\"\"\"", "possible.\"\"\" request.GrabServer(display = self.display, onerror = onerror) def ungrab_server(self, onerror", "the event class. EVT will be cloned, and the attribute", "def refresh_keyboard_mapping(self, evt): \"\"\"This method should be called once when", "= first_keycode, keysyms = keysyms) def get_keyboard_mapping(self, first_keycode, count): \"\"\"Return", "the logical number for the physical button n+1. Logical number", "set to CODE. If NAME is omitted, it will be", "be assigned to keycode first_keycode+n at index i.\"\"\" request.ChangeKeyboardMapping(display =", "the GNU Lesser General Public License # as published by", "by creating new classes for class_name, dictionary in self.class_extension_dicts.items(): origcls", "propagate = 0, onerror = None): \"\"\"Send a synthetic event", "the next event is fetched from the server.\"\"\" return self.display.next_event()", "otherwise the global state for the entire keyboard will be", "self.class_extension_dicts = {} self.display_extension_methods = {} # a dict that", "created and X.NONE is returned.\"\"\" r = request.InternAtom(display = self.display,", "X.MappingFailed is returned. Otherwise the mapping is changed and X.MappingSuccess", "index and secondarily on the lowest keycode.\"\"\" try: # Copy", "(the request) will be None. See section Error Handling.\"\"\" self.display.set_error_handler(handler)", "def keycode_to_keysym(self, keycode, index): \"\"\"Convert a keycode to a keysym,", "the extension name. If it is supported an object with", "% name) self.display_extension_methods[name] = function else: class_list = (object, )", "from the server.\"\"\" return self.display.next_event() def pending_events(self): \"\"\"Return the number", "or X.FamilyChaos. host is a list of bytes. For the", "to path, which should be a list of strings. If", "timeout, interval, prefer_blank, allow_exposures, onerror = None): \"\"\"See XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display", "terms of the GNU Lesser General Public License # as", "# Translations for keysyms to strings. self.keysym_translations = {} #", "= time) def grab_server(self, onerror = None): \"\"\"Disable processing of", "= 0, src_width = 0, src_height = 0, onerror =", "the new map self._keymap_codes[first_keycode:lastcode] = keysyms # Update sym->code map", "button numbers. map must be of the same length as", "= None): \"\"\"To change the pointer acceleration, set accel to", "onerror, timeout = timeout, interval = interval, prefer_blank = prefer_blank,", "and wait until the server has processed all the queued", "\"\"\"Return a list of font names matching pattern. No more", "code = code + 1 ### ### client-internal keysym to", "KEYSYM to NEWSTRING. If NEWSTRING is None, remove old translation", "otherwise. hosts The hosts on the access list. Each entry", "event to the window destination which can be a window", "method except KeyError: self.class_extension_dicts[class_name] = { name: method } def", "extension name. If it is supported an object with the", "additional errors, or 0. If the extension is not supported,", "font gc colormap cursor This function can be used when", "pointer will then move num/denum times the normal speed if", "on. key_click_percent The volume of key click, from 0 to", "atom) return r.name def get_selection_owner(self, selection): \"\"\"Return the window that", "to do it... self.get_pointer_control() def next_event(self): \"\"\"Return the next event.", "map self._keymap_codes[first_keycode:lastcode] = keysyms # Update sym->code map code =", "event) def ungrab_pointer(self, time, onerror = None): \"\"\"elease a grabbed", "See XGetScreenSaver(3X11) for details.\"\"\" return request.GetScreenSaver(display = self.display) def change_hosts(self,", "next event. If there are no events queued, it will", "and lowest code is returned. If keysym is not bound", "X.ScreenSaverActive the screen saver is activated. If it is X.ScreenSaverReset,", "set_access_control(self, mode, onerror = None): \"\"\"Enable use of access control", "ID has been fetched e.g. from an resource or a", "accel = None, threshold = None, onerror = None): \"\"\"To", "src_window is a window the pointer is only moved if", "first argument is a 'self'. \"\"\" if object == 'display':", "return r.fonts def list_fonts_with_info(self, pattern, max_names): \"\"\"Return a list of", "evt, [name]) Add an extension subevent. CODE is the numeric", "extension modules for extname, modname in ext.__extensions__: if extname in", "is ungrabbed. Server grabbing should be avoided as much as", "except KeyError: self.class_extension_dicts[class_name] = { name: method } def extension_add_event(self,", "exist.\"\"\" r = request.GetAtomName(display = self.display, atom = atom) return", "None, threshold = None, onerror = None): \"\"\"To change the", "if extname in exts: # Import the module and fetch", "extension_event. \"\"\" newevt = type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code = code", ". import error from . import ext from . import", "self._keymap_syms[keysym][0][1] except (KeyError, IndexError): return 0 def keysym_to_keycodes(self, keysym): \"\"\"Look", "Each element represents a keycode, and the tuple elements are", "59 Temple Place, # Suite 330, # Boston, MA 02111-1307", "time = time) def get_input_focus(self): \"\"\"Return an object with the", "Internet family, it is the 4 bytes of an IPv4", "bytes of an IPv4 address. \"\"\" return request.ListHosts(display = self.display)", "do_threshold = 1 request.ChangePointerControl(display = self.display, onerror = onerror, do_accel", "is used to insert an entry in the DictWrapper extension_event.", "self._keymap_syms[sym] = [(index, code)] index = index + 1 code", "\"\"\"This method should be called once when a MappingNotify event", "the base volume. See XBell(3X11).\"\"\" request.Bell(display = self.display, onerror =", "# elements each: (index, keycode) # keycode is the code", "0 def keysym_to_keycodes(self, keysym): \"\"\"Look up all the keycodes that", "evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt) if name is", "tuples of keysyms. keysyms[n][i] will be assigned to keycode first_keycode+n", "in case someone creates this later if r.atom != X.NONE:", "= threshold) def get_pointer_control(self): \"\"\"Return an object with the following", "list of strings.\"\"\" r = request.GetFontPath(display = self.display) return r.paths", "exist, it will not be created and X.NONE is returned.\"\"\"", "GNU Lesser General Public License for more details. # #", "keysyms: index = 0 for sym in syms: if sym", "def __init__(self, display = None): self.display = _BaseDisplay(display) # Create", "code is returned. If keysym is not bound to any", "See the descripton of XFontStruct in XGetFontProperty(3X11) for details on", "r = request.ListExtensions(display = self.display) return r.names def change_keyboard_mapping(self, first_keycode,", "keysym_to_keycodes(self, keysym): \"\"\"Look up all the keycodes that is bound", "window becomes not visible, and should be X.RevertToParent, RevertToPointerRoot, or", "dst_window = X.NONE, src_x = src_x, src_y = src_y, src_width", "\"\"\" return request.GetInputFocus(display = self.display) def query_keymap(self): \"\"\"Return a bit", "= 0 accel_denum = 0 else: do_accel = 1 accel_num,", "# This library is free software; you can redistribute it", "an object with the following attributes is returned: major_opcode The", "change. If led is not provided, all LEDs are changed.", "a 'self'. \"\"\" if object == 'display': if hasattr(self, name):", "self.display = _BaseDisplay(display) # Create the keymap cache self._keymap_codes =", "to be altered are logically in the down state, X.MappingBusy", "self.get_keyboard_mapping(first_keycode, count) # Replace code->sym map with the new map", "font_ascent font_descent replies_hint See the descripton of XFontStruct in XGetFontProperty(3X11)", "bit is on, autorepeat is enabled for the corresponding key.", "= accel if threshold is None: do_threshold = 0 else:", "translation if any. \"\"\" if newstring is None: try: del", "onerror = None): \"\"\"Move the pointer relative its current position", "colormap cursor NAME is the name of the method, a", "onerror = None): \"\"\"Change the dynamic parameters of a pointer", "of tuples of keysyms. keysyms[n][i] will be assigned to keycode", "vector is represented as a list of 32 integers. List", "not be available. \"\"\" return self.display.resource_classes[type](self.display, id) # We need", "to replace display method: %s' % name) self.display_extension_methods[name] = function", "origcls = self.display.resource_classes[class_name] self.display.resource_classes[class_name] = type(origcls.__name__, (origcls,), dictionary) # Problem:", "which should be a list of strings. If path is", "if threshold is None: do_threshold = 0 else: do_threshold =", "is bound to keysym. A list of tuples (keycode, index)", "is X.DisableAccess.\"\"\" request.SetAccessControl(display = self.display, onerror = onerror, mode =", "threshold number of pixels at once. To change the threshold,", "attributes: focus The window which currently holds the input focus,", "names matching pattern. No more than max_names will be returned.\"\"\"", "resource drawable window pixmap fontable font gc colormap cursor NAME", "support the X extension named extension.\"\"\" return extension in self.extensions", "keycode, index): \"\"\"Convert a keycode to a keysym, looking in", "match any font, None is returned.\"\"\" fid = self.display.allocate_resource_id() ec", "a subcode, to a tuple of (event,subcode) # note this", "self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid, owner = 1) def list_fonts(self,", "%s method: %s' % (class_name, name)) method = create_unbound_method(function, cls)", "keysym): \"\"\"Look up all the keycodes that is bound to", "will be modified.\"\"\" request.ChangeKeyboardControl(display = self.display, onerror = onerror, attrs", "code = codes[i][1] if code >= first_keycode and code <", "### def lookup_string(self, keysym): \"\"\"Return a string corresponding to KEYSYM,", "= self.display, onerror = onerror, mode = mode, time =", "Window.send_event() method.\"\"\" request.SendEvent(display = self.display, onerror = onerror, propagate =", "it's an event with a subcode, to a tuple of", "mod = getattr(ext, modname) info = self.query_extension(extname) self.display.set_extension_major(extname, info.major_opcode) #", "passed select.select().\"\"\" return self.display.fileno() def close(self): \"\"\"Close the display, freeing", "\"\"\"mode is either X.HostInsert or X.HostDelete. host_family is one of", "in the map for that keycode. def keycode_to_keysym(self, keycode, index):", "list of tuples, starting at first_keycount and no more than", "### client-internal keysym to string translations ### def lookup_string(self, keysym):", "= mode, time = time) def grab_server(self, onerror = None):", "import types # Python 2/3 compatibility. from six import create_unbound_method", "keymap cache. evt should be the event object.\"\"\" if isinstance(evt,", "intern_atom, using internal cache\"\"\" return self.display.get_atom(atom, only_if_exists) def get_atom_name(self, atom):", "event. If there are no events queued, it will block", "= 1) def list_fonts(self, pattern, max_names): \"\"\"Return a list of", "at index i.\"\"\" request.ChangeKeyboardMapping(display = self.display, onerror = onerror, first_keycode", "X.AutoRepeatModeOff, X.AutoRepeatModeOn, or X.AutoRepeatModeDefault. If key is provided, that key", "list of 32 integers. List item N contains the bits", "request error handler, but the second argument (the request) will", "return None else: cls = self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid,", "key_click_percent The volume of key clicks between 0 (off) and", "not bound to any key, 0 is returned.\"\"\" try: return", "= name, only_if_exists = only_if_exists) return r.atom def get_atom(self, atom,", "to add the function to, a string from this list:", "or X.PointerWindow or X.InputFocus. event is the event object to", "get_input_focus(self): \"\"\"Return an object with the following attributes: focus The", "= self.display_extension_methods[attr] return types.MethodType(function, self) except KeyError: raise AttributeError(attr) ###", "that should change. If led is not provided, all LEDs", "in the hope that it will be useful, # but", "to KEYSYM, or None if no reasonable translation is found.", "change the threshold, set it to the number of pixels.", "elements each: (index, keycode) # keycode is the code for", "resource or a command line argument. Resource objects should never", "received, to update the keymap cache. evt should be the", "drawable window pixmap fontable font gc colormap cursor This function", "self.display.resource_classes[type](self.display, id) # We need this to handle display extension", "\"\"\"Change the translation of KEYSYM to NEWSTRING. If NEWSTRING is", "be a window object, or X.PointerWindow or X.InputFocus. event is", "host) def list_hosts(self): \"\"\"Return an object with the following attributes:", "for the changed codes lastcode = first_keycode + count for", "disable if it is X.DisableAccess.\"\"\" request.SetAccessControl(display = self.display, onerror =", "enabled for the corresponding key. led_mask A 32-bit mask indicating", "= keysyms # Update sym->code map code = first_keycode for", "be available. \"\"\" return self.display.resource_classes[type](self.display, id) # We need this", "Get the new keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode, count) #", "event') def _update_keymap(self, first_keycode, count): \"\"\"Internal function, called to refresh", "method } def extension_add_event(self, code, evt, name = None): \"\"\"extension_add_event(code,", "= do_threshold, accel_num = accel_num, accel_denum = accel_denum, threshold =", "GNU Lesser General Public # License along with this library;", "events. See XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display = self.display, onerror = onerror, time", "list of fonts matching pattern. No more than max_names will", "\"\"\"Return an object with the following attributes: mode X.EnableAccess if", "# License along with this library; if not, write to", "one of the buttons to be altered are logically in", "drawable window pixmap fontable font gc colormap cursor NAME is", "the GNU Lesser General Public # License along with this", "\"\"\" return request.ListHosts(display = self.display) def set_access_control(self, mode, onerror =", "the tuple elements are # the keysyms bound to the", "(at your option) any later version. # # This library", "\"\"\" # Delete all sym->code maps for the changed codes", "interval = interval, prefer_blank = prefer_blank, allow_exposures = allow_exposures) def", "will revert, one of X.RevertToParent, RevertToPointerRoot, or RevertToNone. \"\"\" return", "its current position by the offsets (x, y). However, if", "we have already created some objects without the # extensions:", "LEDs are on. key_click_percent The volume of key click, from", "lowest index and lowest code is returned. If keysym is", "returned.\"\"\" r = request.ListFonts(display = self.display, max_names = max_names, pattern", "of bytes. For the Internet family, it should be the", "type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt) if name", "\"\"\"extension_add_event(code, evt, [name]) Add an extension event. CODE is the", "it as a string. Will raise BadAtom if atom does", "key to which this keysym is bound, and # index", "cls = self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid, owner = 1)", "try: # Copy the map list, reversing the arguments return", "happen with the client's resources at connection close. The default", "certain request is trapped.\"\"\" # Do a light-weight replyrequest to", "the bell in milliseconds, -1 restores the default. led led_mode", "= None): \"\"\"mode is either X.HostInsert or X.HostDelete. host_family is", "= self.display, onerror = onerror, first_keycode = first_keycode, keysyms =", ".xobject import colormap from .xobject import cursor _resource_baseclasses = {", "Place, # Suite 330, # Boston, MA 02111-1307 USA #", "name) if r.present: return r else: return None def list_extensions(self):", "extension methods def __getattr__(self, attr): try: function = self.display_extension_methods[attr] return", "= None): \"\"\"Ring the bell at the volume percent which", "pixels the pointer must move before the acceleration kicks in.\"\"\"", "should be a eight-element list where each entry is a", "an event with a subcode, to a tuple of (event,subcode)", "the map for that keycode. def keycode_to_keysym(self, keycode, index): \"\"\"Convert", "server if it was previously grabbed by this client.\"\"\" request.UngrabServer(display", "other sub-events and EVT is the event class. EVT will", "called without blocking.\"\"\" return self.display.pending_events() def has_extension(self, extension): \"\"\"Check if", "the resources that it holds.\"\"\" self.display.close() def set_error_handler(self, handler): \"\"\"Set", "keymap cache. \"\"\" # Delete all sym->code maps for the", "try: function = self.display_extension_methods[attr] return types.MethodType(function, self) except KeyError: raise", "self.display.info.min_keycode + 1)) # Translations for keysyms to strings. self.keysym_translations", "a light-weight replyrequest to sync. There must # be a", "sync. There must # be a better way to do", "implementation ### # The keycode->keysym map is stored in a", "= self.display) return r.paths def query_extension(self, name): \"\"\"Ask the server", "of KEYSYM to NEWSTRING. If NEWSTRING is None, remove old", "as keyword arguments: key_click_percent The volume of key clicks between", "name, function) Add an X extension module method. OBJECT is", "request.SetScreenSaver(display = self.display, onerror = onerror, timeout = timeout, interval", "onerror = None): \"\"\"Do nothing but send a request to", "NEWSTRING. If NEWSTRING is None, remove old translation if any.", "\"\"\"Set the font path to path, which should be a", "lowest code is returned. If keysym is not bound to", "later if r.atom != X.NONE: self._atom_cache[atomname] = r.atom return r.atom", "= timeout, interval = interval, prefer_blank = prefer_blank, allow_exposures =", "list. Each entry has the following attributes: family X.FamilyInternet, X.FamilyDECnet,", "X.CurrentTime.\"\"\" request.AllowEvents(display = self.display, onerror = onerror, mode = mode,", "currently pressed down. The vector is represented as a list", "argument is a 'self'. \"\"\" if object == 'display': if", "index in the map for that keycode. def keycode_to_keysym(self, keycode,", "attributes: family X.FamilyInternet, X.FamilyDECnet, or X.FamilyChaos. name A list of", "mapping, where the keys # are keysyms. The values are", "all the keycodes that is bound to keysym. A list", "is X.EnableAccess, disable if it is X.DisableAccess.\"\"\" request.SetAccessControl(display = self.display,", "when # dealing with some ICCCM properties not defined in", "be necessary in applications that never wait for events, and", "secondarily on the lowest keycode.\"\"\" try: # Copy the map", "which LEDs are on. key_click_percent The volume of key click,", "list, reversing the arguments return map(lambda x: (x[1], x[0]), self._keymap_syms[keysym])", "with the new map self._keymap_codes[first_keycode:lastcode] = keysyms # Update sym->code", "screens on the display.\"\"\" return len(self.display.info.roots) def get_default_screen(self): \"\"\"Return the", "= 0 for sym in syms: if sym != X.NoSymbol:", "r.owner def send_event(self, destination, event, event_mask = 0, propagate =", "provided, all LEDs are changed. key auto_repeat_mode auto_repeat_mode should be", "set_font_path(self, path, onerror = None): \"\"\"Set the font path to", "a keycode to a keysym, looking in entry index. Normally", "IndexError): return 0 def keysym_to_keycodes(self, keysym): \"\"\"Look up all the", "to update the keymap cache. evt should be the event", "the display, freeing the resources that it holds.\"\"\" self.display.close() def", "pixmap fontable font gc colormap cursor This function can be", "time) def grab_server(self, onerror = None): \"\"\"Disable processing of requests", "attributes: mode X.EnableAccess if the access control list is used,", "only_if_exists) return r.atom def get_atom(self, atom, only_if_exists = 0): \"\"\"Alias", "to the code # or, when it's an event with", "protocol_display.Display.__init__(self, *args, **keys) self._atom_cache = {} def get_atom(self, atomname, only_if_exists=0):", "in self.extensions def create_resource_object(self, type, id): \"\"\"Create a resource object", "to insert an entry in the DictWrapper extension_event. \"\"\" newevt", "treated in a similar way. To move the pointer to", "= request.ListExtensions(display = self.display) return r.names def change_keyboard_mapping(self, first_keycode, keysyms,", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "or X.AutoRepeatModeOff. auto_repeats A list of 32 integers. List item", "CODE is the numeric code, subcode is the sub-ID of", "one for each modifier. The list can be indexed using", "= onerror, path = path) def get_font_path(self): \"\"\"Return the current", "control lists at connection setup if mode is X.EnableAccess, disable", "__getattr__(self, attr): try: function = self.display_extension_methods[attr] return types.MethodType(function, self) except", "if the extension have additional errors, or 0. If the", "self.display.info.roots[sno] def screen_count(self): \"\"\"Return the total number of screens on", "lists, one for each modifier. The list can be indexed", "with 256 elements. # Each element represents a keycode, and", "revert_to Where the focus will revert, one of X.RevertToParent, RevertToPointerRoot,", "or 0. first_error The base error code if the extension", "if code >= first_keycode and code < lastcode: del codes[i]", "the translation of KEYSYM to NEWSTRING. If NEWSTRING is None,", "any key, 0 is returned.\"\"\" try: return self._keymap_syms[keysym][0][1] except (KeyError,", "bound to keysym. A list of tuples (keycode, index) is", "as a list of tuples, starting at first_keycount and no", "pitch of the bell in Hz, -1 restores the default.", "returned.\"\"\" r = request.SetPointerMapping(display = self.display, map = map) return", "evt.count) else: raise TypeError('expected a MappingNotify event') def _update_keymap(self, first_keycode,", "CODE is the numeric code, and ERR is the error", "the Internet family, it is the 4 bytes of an", "the list sets the logical button number for the physical", "protocol_display from .protocol import request, event, rq # Xlib.xobjects modules", "mode) def set_close_down_mode(self, mode, onerror = None): \"\"\"Control what will", "Xlib.XK return Xlib.XK.keysym_to_string(keysym) def rebind_string(self, keysym, newstring): \"\"\"Change the translation", "check extension overrides too try: self.class_extension_dicts[class_name][name] = method except KeyError:", "level display object # # Copyright (C) 2000 <NAME> <<EMAIL>>", "X.Mod4 and X.Mod5. keycodes should be a eight-element list where", "the server, either provided when creating the Display object, or", "extname, modname in ext.__extensions__: if extname in exts: # Import", "will block until the next event is fetched from the", "event.MappingNotify): if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected", "take two arguments as a normal request error handler, but", "= self.display.resource_classes['colormap'](self.display, screen.default_colormap.id) def get_display_name(self): \"\"\"Returns the name used to", "width of src_window - src_x. src_height is treated in a", "that Display.next_event() can be called without blocking.\"\"\" return self.display.pending_events() def", "self.display.add_extension_error(code, err) ### ### keymap cache implementation ### # The", "X.FamilyChaos. host is a list of bytes. For the Internet", "that the corresponding key is currently pressed down. The vector", "the keymap cache self._keymap_codes = [()] * 256 self._keymap_syms =", "lastcode = first_keycode + count for keysym, codes in self._keymap_syms.items():", "be returned. Each list item represents one font and has", "sublists list the keycodes bound to that modifier.\"\"\" r =", "r.name def get_selection_owner(self, selection): \"\"\"Return the window that owns selection", "name) self.sync() if ec.get_error(): self.display.free_resource_id(fid) return None else: cls =", "return request.ListHosts(display = self.display) def set_access_control(self, mode, onerror = None):", "if r.atom != X.NONE: self._atom_cache[atomname] = r.atom return r.atom class", "or X.LedModeOn. If led is provided, it should be a", "once when a MappingNotify event is received, to update the", "while i < len(codes): code = codes[i][1] if code >=", "once. To change the threshold, set it to the number", "all LEDs are changed. key auto_repeat_mode auto_repeat_mode should be one", "Can raise BadAtom.\"\"\" r = request.GetSelectionOwner(display = self.display, selection =", "is the event class. EVT will be cloned, and the", "exts: # Import the module and fetch it __import__('Xlib.ext.' +", "onerror = None): \"\"\"Disable processing of requests on all other", "get_font_path(self): \"\"\"Return the current font path as a list of", "map code = first_keycode for syms in keysyms: index =", "id): \"\"\"Create a resource object of type for the integer", "map(lambda x: (x[1], x[0]), self._keymap_syms[keysym]) except KeyError: return [] def", "will be set to CODE. If NAME is omitted, it", "as much as possible.\"\"\" request.GrabServer(display = self.display, onerror = onerror)", "should be the four bytes of an IPv4 address.\"\"\" request.ChangeHosts(display", "If only_if_exists is true and the atom does not already", "the library will not be available. \"\"\" return self.display.resource_classes[type](self.display, id)", "which this keysym is bound, and # index is the", "the number of pixels. -1 restores the default.\"\"\" if accel", "is not provided, all LEDs are changed. key auto_repeat_mode auto_repeat_mode", "(index, keycode) # keycode is the code for a key", "\"\"\"Return an object with the following attributes: focus The window", "name of atom, returning it as a string. Will raise", "return X.NoSymbol def keysym_to_keycode(self, keysym): \"\"\"Look up the primary keycode", "To change the threshold, set it to the number of", "fetched e.g. from an resource or a command line argument.", "font object. If name does not match any font, None", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "if object == 'display': if hasattr(self, name): raise AssertionError('attempting to", "= 0, onerror = None): \"\"\"Ring the bell at the", "{} self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode - self.display.info.min_keycode + 1)) # Translations for", "for the eight modifiers X.Shift, X.Lock, X.Control, X.Mod1, X.Mod2, X.Mod3,", "self.display, map = map) return r.status def get_pointer_mapping(self): \"\"\"Return a", "is bound, and # index is the keysyms index in", "This name is used to insert an entry in the", "led_mask A 32-bit mask indicating which LEDs are on. key_click_percent", "= host) def list_hosts(self): \"\"\"Return an object with the following", "and return its font object. If name does not match", "0): \"\"\"Alias for intern_atom, using internal cache\"\"\" return self.display.get_atom(atom, only_if_exists)", "keycodes = keycodes) return r.status def get_modifier_mapping(self): \"\"\"Return a list", "get_atom(self, atom, only_if_exists = 0): \"\"\"Alias for intern_atom, using internal", "mode X.EnableAccess if the access control list is used, X.DisableAccess", "values. properties A list of properties. Each entry has two", "**keys): protocol_display.Display.__init__(self, *args, **keys) self._atom_cache = {} def get_atom(self, atomname,", "first_keycode for syms in keysyms: index = 0 for sym", "element represents a keycode, and the tuple elements are #", "= onerror, src_window = src_window, dst_window = X.NONE, src_x =", "is a window the pointer is only moved if the", "(KeyError, IndexError): return 0 def keysym_to_keycodes(self, keysym): \"\"\"Look up all", "def allow_events(self, mode, time, onerror = None): \"\"\"Release some queued", "button number for the physical button N+1.\"\"\" r = request.GetPointerMapping(display", "selection) return r.owner def send_event(self, destination, event, event_mask = 0,", "the acceleration kicks in.\"\"\" return request.GetPointerControl(display = self.display) def set_screen_saver(self,", "# See the GNU Lesser General Public License for more", "_update_keymap(self, first_keycode, count): \"\"\"Internal function, called to refresh the keymap", "revert_to = revert_to, focus = focus, time = time) def", "never be created by instantiating the appropriate class directly, since", "this list: display resource drawable window pixmap fontable font gc", "subcode, evt, name = None): \"\"\"extension_add_subevent(code, evt, [name]) Add an", "modules from .protocol import display as protocol_display from .protocol import", "def list_hosts(self): \"\"\"Return an object with the following attributes: mode", "code)) symcodes.sort() else: self._keymap_syms[sym] = [(index, code)] index = index", "connection setup if mode is X.EnableAccess, disable if it is", "queued, it will block until the next event is fetched", "list of tuples with two # elements each: (index, keycode)", "onerror = None): \"\"\"Ungrab a grabbed keyboard and any queued", "draw_direction min_byte1 max_byte1 all_chars_exist font_ascent font_descent replies_hint See the descripton", "is received, to update the keymap cache. evt should be", "def change_active_pointer_grab(self, event_mask, cursor, time, onerror = None): \"\"\"Change the", "r = request.GetKeyboardMapping(display = self.display, first_keycode = first_keycode, count =", "0 to 100. bell_percent bell_pitch bell_duration The volume, pitch and", "object with the following attributes: focus The window which currently", "(load). -1 will restore default setting. bell_percent The base volume", "a string from this list: display resource drawable window pixmap", "function = self.display_extension_methods[attr] return types.MethodType(function, self) except KeyError: raise AttributeError(attr)", "contains it. If src_width is 0 it will be replaced", "2/3 compatibility. from six import create_unbound_method # Xlib modules from", "atomname, only_if_exists=0): if atomname in self._atom_cache: return self._atom_cache[atomname] r =", "request is trapped.\"\"\" # Do a light-weight replyrequest to sync.", "symcodes = self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym] = [(index,", "any font, None is returned.\"\"\" fid = self.display.allocate_resource_id() ec =", "of logical button numbers. map must be of the same", "Where the focus will revert, one of X.RevertToParent, RevertToPointerRoot, or", "the string name, returning its atom number. If only_if_exists is", "keycodes for the eight modifiers X.Shift, X.Lock, X.Control, X.Mod1, X.Mod2,", "keycodes should be a eight-element list where each entry is", "accel_num = 0 accel_denum = 0 else: do_accel = 1", "synthetic event to the window destination which can be a", "host_family, host, onerror = None): \"\"\"mode is either X.HostInsert or", "Resource objects should never be created by instantiating the appropriate", "logical button number for the physical button N+1.\"\"\" r =", "onerror = onerror, src_window = src_window, dst_window = X.NONE, src_x", "old translation if any. \"\"\" if newstring is None: try:", "The volume, pitch and duration of the bell. \"\"\" return", "returned and the mapping is not changed. Otherwise the mapping", "prefer_blank = prefer_blank, allow_exposures = allow_exposures) def get_screen_saver(self): \"\"\"Return an", "RevertToPointerRoot, or RevertToNone. See XSetInputFocus(3X11) for details. There is also", "that modifier.\"\"\" r = request.GetModifierMapping(display = self.display) return r.keycodes def", "a similar way. To move the pointer to absolute coordinates,", "modules from .xobject import resource from .xobject import drawable from", "\"\"\"Create a resource object of type for the integer id.", "is fetched from the server.\"\"\" return self.display.next_event() def pending_events(self): \"\"\"Return", "ec = error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror = ec, fid", "= code + 1 ### ### client-internal keysym to string", "raise TypeError('expected a MappingNotify event') def _update_keymap(self, first_keycode, count): \"\"\"Internal", "of font names matching pattern. No more than max_names will", "X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected a MappingNotify event') def", "the new keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode, count) # Replace", "0 (off) and 100 (load). -1 will restore default setting.", "nothing but send a request to the server.\"\"\" request.NoOperation(display =", "time) def change_active_pointer_grab(self, event_mask, cursor, time, onerror = None): \"\"\"Change", "input focus, X.NONE or X.PointerRoot. revert_to Where the focus will", ". import X # Xlib.protocol modules from .protocol import display", "cls(self.display, fid, owner = 1) def list_fonts(self, pattern, max_names): \"\"\"Return", "try: return self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol def keysym_to_keycode(self, keysym):", "0 while i < len(codes): code = codes[i][1] if code", "list_fonts_with_info(self, pattern, max_names): \"\"\"Return a list of fonts matching pattern.", "### display information retrieval ### def screen(self, sno = None):", "dict that maps the event name to the code #", "blocking.\"\"\" return self.display.pending_events() def has_extension(self, extension): \"\"\"Check if both the", "code, and EVT is the event class. EVT will be", "== X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected a MappingNotify event')", "server will be restored.\"\"\" request.SetFontPath(display = self.display, onerror = onerror,", "mapping as a list of tuples, starting at first_keycount and", "relative the base volume. See XBell(3X11).\"\"\" request.Bell(display = self.display, onerror", "the terms of the GNU Lesser General Public License #", "supported extensions self.extensions = [] self.class_extension_dicts = {} self.display_extension_methods =", "of (event code, subcode) in the # extension dict maintained", "pressed down. The vector is represented as a list of", "list of all the extensions provided by the server.\"\"\" r", "is deactivated as if device input had been received.\"\"\" request.ForceScreenSaver(display", "atom = atom) return r.name def get_selection_owner(self, selection): \"\"\"Return the", "%s' % (class_name, name)) method = create_unbound_method(function, cls) # Maybe", "duration of the bell in milliseconds, -1 restores the default.", "self.display.close() def set_error_handler(self, handler): \"\"\"Set the default error handler which", "Display object, or fetched from the environmental variable $DISPLAY.\"\"\" return", "is alt grid, and 3 is shift+alt grid. If that", "be used when a resource ID has been fetched e.g.", "# Import the module and fetch it __import__('Xlib.ext.' + modname)", "onerror = None): \"\"\"elease a grabbed pointer and any queued", "from the environmental variable $DISPLAY.\"\"\" return self.display.get_display_name() def fileno(self): \"\"\"Returns", "= {} self.display_extension_methods = {} # a dict that maps", "X.AutoRepeatModeOn, or X.AutoRepeatModeDefault. If key is provided, that key will", "indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on. The sublists list", "pixmap fontable font gc colormap cursor NAME is the name", "handler): \"\"\"Set the default error handler which will be called", "request.ChangeKeyboardControl(display = self.display, onerror = onerror, attrs = keys) def", "fid = self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror", "= name) if r.present: return r else: return None def", "event class will be set to CODE. If NAME is", "the width of src_window - src_x. src_height is treated in", "keycodes bound to that modifier.\"\"\" r = request.GetModifierMapping(display = self.display)", "has been fetched e.g. from an resource or a command", "selection = selection) return r.owner def send_event(self, destination, event, event_mask", "request.ChangeKeyboardMapping(display = self.display, onerror = onerror, first_keycode = first_keycode, keysyms", "of the server will be restored.\"\"\" request.SetFontPath(display = self.display, onerror", "times the normal speed if it moves beyond the threshold", "RevertToNone. See XSetInputFocus(3X11) for details. There is also a Window.set_input_focus().\"\"\"", "clicks between 0 (off) and 100 (load). -1 will restore", "store subcodes as a tuple of (event code, subcode) in", "each: (index, keycode) # keycode is the code for a", "= event_mask) def ungrab_keyboard(self, time, onerror = None): \"\"\"Ungrab a", "return self._keymap_syms[keysym][0][1] except (KeyError, IndexError): return 0 def keysym_to_keycodes(self, keysym):", "x, y, src_window = X.NONE, src_x = 0, src_y =", "def get_atom(self, atom, only_if_exists = 0): \"\"\"Alias for intern_atom, using", "or X.AutoRepeatModeDefault. If key is provided, that key will be", "set_error_handler(self, handler): \"\"\"Set the default error handler which will be", "acceleration kicks in.\"\"\" return request.GetPointerControl(display = self.display) def set_screen_saver(self, timeout,", "list item represents one font and has the following properties:", "of the keyboard, where each bit set to 1 indicates", "Suite 330, # Boston, MA 02111-1307 USA # Python modules", "resource drawable window pixmap fontable font gc colormap cursor This", "= None, onerror = None): \"\"\"To change the pointer acceleration,", "'pixmap', 'fontable', 'font', 'gc', 'colormap', 'cursor'), 'drawable': ('window', 'pixmap'), 'fontable':", "-1 restores the default.\"\"\" if accel is None: do_accel =", "acceleration, set accel to a tuple (num, denum). The pointer", "flush(self): \"\"\"Flush the request queue, building and sending the queued", "# # Copyright (C) 2000 <NAME> <<EMAIL>> # # This", "def list_fonts_with_info(self, pattern, max_names): \"\"\"Return a list of fonts matching", "case someone creates this later if r.atom != X.NONE: self._atom_cache[atomname]", "but send a request to the server.\"\"\" request.NoOperation(display = self.display,", "onerror = onerror, mode = mode, time = time) def", "X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes should be", "host is a list of bytes. For the Internet family,", "+ 1 ### ### client-internal keysym to string translations ###", "function whose first argument is a 'self'. \"\"\" if object", "prefer_blank, allow_exposures, onerror = None): \"\"\"See XSetScreenSaver(3X11).\"\"\" request.SetScreenSaver(display = self.display,", "all sym->code maps for the changed codes lastcode = first_keycode", "current position by the offsets (x, y). However, if src_window", "moved if the specified rectangle in src_window contains it. If", "List item N contains the bits for keys 8N to", "it and/or # modify it under the terms of the", "# The keycode->keysym map is stored in a list with", "onerror, attrs = keys) def get_keyboard_control(self): \"\"\"Return an object with", "the lowest keycode.\"\"\" try: # Copy the map list, reversing", "def list_fonts(self, pattern, max_names): \"\"\"Return a list of font names", "interval, prefer_blank = prefer_blank, allow_exposures = allow_exposures) def get_screen_saver(self): \"\"\"Return", "timeout = timeout, interval = interval, prefer_blank = prefer_blank, allow_exposures", "err) Add an extension error. CODE is the numeric code,", "not already exist, it will not be created and X.NONE", "instantiated from one of the classes in protocol.events. See XSendEvent(3X11)", "= onerror) def warp_pointer(self, x, y, src_window = X.NONE, src_x", "in self._atom_cache: return self._atom_cache[atomname] r = request.InternAtom(display = self, name", "when a resource ID has been fetched e.g. from an", "time, onerror = None): \"\"\"Ungrab a grabbed keyboard and any", "changed. key auto_repeat_mode auto_repeat_mode should be one of X.AutoRepeatModeOff, X.AutoRepeatModeOn,", "raise BadAtom if atom does not exist.\"\"\" r = request.GetAtomName(display", "extension is not supported, None is returned.\"\"\" r = request.QueryExtension(display", "onerror, path = path) def get_font_path(self): \"\"\"Return the current font", "more details. # # You should have received a copy", "properties: name The name of the font. min_bounds max_bounds min_char_or_byte2", "else: do_accel = 1 accel_num, accel_denum = accel if threshold", "list of the keycodes that should be bound to that", "be useful, # but WITHOUT ANY WARRANTY; without even the", "is the keysyms index in the map for that keycode.", "Import the module and fetch it __import__('Xlib.ext.' + modname) mod", "and/or # modify it under the terms of the GNU", "del self.keysym_translations[keysym] except KeyError: pass else: self.keysym_translations[keysym] = newstring ###", "### ### display information retrieval ### def screen(self, sno =", "subcode) in the # extension dict maintained in the display", "that the requests of this extension uses. first_event The base", "self.extensions = [] self.class_extension_dicts = {} self.display_extension_methods = {} #", "accel_denum = accel_denum, threshold = threshold) def get_pointer_control(self): \"\"\"Return an", "time, onerror = None): \"\"\"elease a grabbed pointer and any", "FUNCTION is a normal function whose first argument is a", "import resource from .xobject import drawable from .xobject import fontable", "= max_names, pattern = pattern) def set_font_path(self, path, onerror =", "details on these values. properties A list of properties. Each", "be created and X.NONE is returned.\"\"\" r = request.InternAtom(display =", "milliseconds, -1 restores the default. led led_mode led_mode should be", "raise AssertionError('attempting to replace %s method: %s' % (class_name, name))", "If that key entry is not bound, X.NoSymbol is returned.\"\"\"", "for the selection. Can raise BadAtom.\"\"\" r = request.GetSelectionOwner(display =", "entry is not bound, X.NoSymbol is returned.\"\"\" try: return self._keymap_codes[keycode][index]", "event is the event object to send, instantiated from one", "focus, time = time) def get_input_focus(self): \"\"\"Return an object with", "which currently holds the input focus, X.NONE or X.PointerRoot. revert_to", "The pointer will then move num/denum times the normal speed", "is bound to keysym. If several keycodes are found, the", "an IPv4 address.\"\"\" request.ChangeHosts(display = self.display, onerror = onerror, mode", "evt.__name__ # store subcodes as a tuple of (event code,", "mapping keysyms = self.get_keyboard_mapping(first_keycode, count) # Replace code->sym map with", "max_bounds min_char_or_byte2 max_char_or_byte2 default_char draw_direction min_byte1 max_byte1 all_chars_exist font_ascent font_descent", "number for the physical button N+1.\"\"\" r = request.GetPointerMapping(display =", "be avoided as much as possible.\"\"\" request.GrabServer(display = self.display, onerror", "mapping of the pointer buttons. map is a list of", "sets the logical button number for the physical button N+1.\"\"\"", "write to the # Free Software Foundation, Inc., # 59", "evt.__bases__, evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt, subcode) if name", "If name does not match any font, None is returned.\"\"\"", "that is bound to keysym. If several keycodes are found,", "XFontStruct in XGetFontProperty(3X11) for details on these values. properties A", "mapping violates some server restriction, X.MappingFailed is returned. Otherwise the", "for details. There is also a Window.send_event() method.\"\"\" request.SendEvent(display =", "def grab_server(self, onerror = None): \"\"\"Disable processing of requests on", "opcode that the requests of this extension uses. first_event The", "Copyright (C) 2000 <NAME> <<EMAIL>> # # This library is", "extension overrides too try: self.class_extension_dicts[class_name][name] = method except KeyError: self.class_extension_dicts[class_name]", "# Update sym->code map code = first_keycode for syms in", "*args, **keys) self._atom_cache = {} def get_atom(self, atomname, only_if_exists=0): if", "only_if_exists) # don't cache NONE responses in case someone creates", "using internal cache\"\"\" return self.display.get_atom(atom, only_if_exists) def get_atom_name(self, atom): \"\"\"Look", "the name of atom, returning it as a string. Will", "in.\"\"\" return request.GetPointerControl(display = self.display) def set_screen_saver(self, timeout, interval, prefer_blank,", "send_event(self, destination, event, event_mask = 0, propagate = 0, onerror", "later version. # # This library is distributed in the", "X.LedModeOn. If led is provided, it should be a 32-bit", "window pixmap fontable font gc colormap cursor NAME is the", "revert, one of X.RevertToParent, RevertToPointerRoot, or RevertToNone. \"\"\" return request.GetInputFocus(display", "self.get_pointer_control() def next_event(self): \"\"\"Return the next event. If there are", "is X.ScreenSaverReset, the screen saver is deactivated as if device", "_resource_baseclasses = { 'resource': resource.Resource, 'drawable': drawable.Drawable, 'window': drawable.Window, 'pixmap':", "a window object, or X.PointerWindow or X.InputFocus. event is the", "client library support the X extension named extension.\"\"\" return extension", "code + 1 ### ### client-internal keysym to string translations", "keycode) # keycode is the code for a key to", "y) def set_input_focus(self, focus, revert_to, time, onerror = None): \"\"\"Set", "whose first argument is a 'self'. \"\"\" if object ==", "self.display) def query_keymap(self): \"\"\"Return a bit vector for the logical", "map is a list of logical button numbers. map must", "'window': drawable.Window, 'pixmap': drawable.Pixmap, 'fontable': fontable.Fontable, 'font': fontable.Font, 'gc': fontable.GC,", "to string translations ### def lookup_string(self, keysym): \"\"\"Return a string", "= self.display, keycodes = keycodes) return r.status def get_modifier_mapping(self): \"\"\"Return", "the numeric code, and EVT is the event class. EVT", "__import__('Xlib.ext.' + modname) mod = getattr(ext, modname) info = self.query_extension(extname)", "request to the server.\"\"\" request.NoOperation(display = self.display, onerror = onerror)", "x, dst_y = y) def set_input_focus(self, focus, revert_to, time, onerror", "event code if the extension have additional events, or 0.", "create_resource_object(self, type, id): \"\"\"Create a resource object of type for", "a list of fonts matching pattern. No more than max_names", "1)) # Translations for keysyms to strings. self.keysym_translations = {}", "threshold is None: do_threshold = 0 else: do_threshold = 1", "the threshold, set it to the number of pixels. -1", "creating new classes for class_name, dictionary in self.class_extension_dicts.items(): origcls =", "send, instantiated from one of the classes in protocol.events. See", "DictWrapper extension_event. \"\"\" newevt = type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code =", "try: del self.keysym_translations[keysym] except KeyError: pass else: self.keysym_translations[keysym] = newstring", "keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode, count) # Replace code->sym map", "if both the server and the client library support the", "1 request.ChangePointerControl(display = self.display, onerror = onerror, do_accel = do_accel,", "first_keycode and code < lastcode: del codes[i] else: i =", "representing key 8N.\"\"\" r = request.QueryKeymap(display = self.display) return r.map", "'self'. \"\"\" if object == 'display': if hasattr(self, name): raise", "def pending_events(self): \"\"\"Return the number of events queued, i.e. the", "8N + 7 with the least significant bit in the", "self.display.next_event() def pending_events(self): \"\"\"Return the number of events queued, i.e.", "had been received.\"\"\" request.ForceScreenSaver(display = self.display, onerror = onerror, mode", "OBJECT is the type of object to add the function", "is X.ScreenSaverActive the screen saver is activated. If it is", "self.display, onerror = onerror, mode = mode, host_family = host_family,", "class_name, dictionary in self.class_extension_dicts.items(): origcls = self.display.resource_classes[class_name] self.display.resource_classes[class_name] = type(origcls.__name__,", "name = atomname, only_if_exists = only_if_exists) # don't cache NONE", "id) # We need this to handle display extension methods", "is not bound, X.NoSymbol is returned.\"\"\" try: return self._keymap_codes[keycode][index] except", "not changed. If the mapping violates some server restriction, X.MappingFailed", "return request.GetKeyboardControl(display = self.display) def bell(self, percent = 0, onerror", "is the numeric code, subcode is the sub-ID of this", "by the Free Software Foundation; either version 2.1 # of", "and any queued events. See XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display = self.display, onerror", "as possible.\"\"\" request.GrabServer(display = self.display, onerror = onerror) def ungrab_server(self,", "keysym to string translations ### def lookup_string(self, keysym): \"\"\"Return a", "should check extension overrides too try: self.class_extension_dicts[class_name][name] = method except", "sorted primarily on the lowest index and secondarily on the", "can be used when a resource ID has been fetched", "grab. See XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display = self.display, onerror = onerror, cursor", "= keysyms) def get_keyboard_mapping(self, first_keycode, count): \"\"\"Return the current keyboard", "tuples with two # elements each: (index, keycode) # keycode", "The acceleration as numerator/denumerator. threshold The number of pixels the", "r = request.InternAtom(display = self, name = atomname, only_if_exists =", "corresponding key is currently pressed down. The vector is represented", "buttons. map is a list of logical button numbers. map", "extname in exts: # Import the module and fetch it", "X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be a timestamp or", "= destination, event_mask = event_mask, event = event) def ungrab_pointer(self,", "the extension have additional errors, or 0. If the extension", "is the code for a key to which this keysym", "library is distributed in the hope that it will be", "each modifier. The list can be indexed using X.ShiftMapIndex, X.Mod1MapIndex,", "that key entry is not bound, X.NoSymbol is returned.\"\"\" try:", "32-bit mask indicating which LEDs are on. key_click_percent The volume", "extensions self.extensions = [] self.class_extension_dicts = {} self.display_extension_methods = {}", "with some ICCCM properties not defined in Xlib.Xatom def __init__(self,", "is relative the base volume. See XBell(3X11).\"\"\" request.Bell(display = self.display,", "= self.display, selection = selection) return r.owner def send_event(self, destination,", "returned and the mapping is not changed. If the mapping", "extension_add_event(self, code, evt, name = None): \"\"\"extension_add_event(code, evt, [name]) Add", "except IndexError: return X.NoSymbol def keysym_to_keycode(self, keysym): \"\"\"Look up the", "- self.display.info.min_keycode + 1)) # Translations for keysyms to strings.", "keysym is not bound to any key, 0 is returned.\"\"\"", "code < lastcode: del codes[i] else: i = i +", "None): \"\"\"Modify the keyboard mapping, starting with first_keycode. keysyms is", "hosts The hosts on the access list. Each entry has", "request.SetAccessControl(display = self.display, onerror = onerror, mode = mode) def", "if hasattr(cls, name): raise AssertionError('attempting to replace %s method: %s'", "return r.name def get_selection_owner(self, selection): \"\"\"Return the window that owns", "accel_num, accel_denum = accel if threshold is None: do_threshold =", "def ungrab_pointer(self, time, onerror = None): \"\"\"elease a grabbed pointer", "it should be the four bytes of an IPv4 address.\"\"\"", "= None): \"\"\"Control what will happen with the client's resources", "Do a light-weight replyrequest to sync. There must # be", "r.present: return r else: return None def list_extensions(self): \"\"\"Return a", "least significant bit in the byte representing key 8N. If", "has the following attributes: family X.FamilyInternet, X.FamilyDECnet, or X.FamilyChaos. name", "evt.__dict__.copy()) newevt._code = code self.display.add_extension_event(code, newevt, subcode) if name is", "or X.PointerRoot. revert_to Where the focus will revert, one of", "= src_y, src_width = src_width, src_height = src_height, dst_x =", "request.GetPointerMapping(display = self.display) return r.map def set_modifier_mapping(self, keycodes): \"\"\"Set the", "exts = self.list_extensions() # Go through all extension modules for", "\"\"\"extension_add_subevent(code, evt, [name]) Add an extension subevent. CODE is the", "a window the pointer is only moved if the specified", "code)] index = index + 1 code = code +", "it as # extension_event.EXTENSION_EVENT_NAME rather than # extension_event[\"EXTENSION_EVENT_NAME\"] self.extension_event =", "= X.NONE, src_x = 0, src_y = 0, src_width =", "with the following attributes: global_auto_repeat X.AutoRepeatModeOn or X.AutoRepeatModeOff. auto_repeats A", "applications.\"\"\" self.display.flush() def sync(self): \"\"\"Flush the queue and wait until", "change_active_pointer_grab(self, event_mask, cursor, time, onerror = None): \"\"\"Change the dynamic", "the mapping violates some server restriction, X.MappingFailed is returned. Otherwise", "set_modifier_mapping(self, keycodes): \"\"\"Set the keycodes for the eight modifiers X.Shift,", "mapping, starting with first_keycode. keysyms is a list of tuples", "name, function): \"\"\"extension_add_method(object, name, function) Add an X extension module", "for syms in keysyms: index = 0 for sym in", "that key will be modified, otherwise the global state for", "screen in self.display.info.roots: screen.root = self.display.resource_classes['window'](self.display, screen.root.id) screen.default_colormap = self.display.resource_classes['colormap'](self.display,", "not bound, X.NoSymbol is returned.\"\"\" try: return self._keymap_codes[keycode][index] except IndexError:", "and any queued events. See XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display = self.display, onerror", "### X requests ### def intern_atom(self, name, only_if_exists = 0):", "are logically in the down state, X.MappingBusy is returned and", "= 0, src_y = 0, src_width = 0, src_height =", "do_accel = 1 accel_num, accel_denum = accel if threshold is", "# Implement a cache of atom names, used by Window", "is returned.\"\"\" r = request.SetPointerMapping(display = self.display, map = map)", "return 0 def keysym_to_keycodes(self, keysym): \"\"\"Look up all the keycodes", "name = name, only_if_exists = only_if_exists) return r.atom def get_atom(self,", "= 0, propagate = 0, onerror = None): \"\"\"Send a", "integer id. type should be one of the following strings:", "names, used by Window objects when # dealing with some", "= 0 else: do_threshold = 1 request.ChangePointerControl(display = self.display, onerror", "dst_x = x, dst_y = y) def set_input_focus(self, focus, revert_to,", "screen, extracted from the display name.\"\"\" return self.display.get_default_screen() ### ###", "def send_event(self, destination, event, event_mask = 0, propagate = 0,", "entry has the following attributes: family X.FamilyInternet, X.FamilyDECnet, or X.FamilyChaos.", "pointer to absolute coordinates, use Window.warp_pointer().\"\"\" request.WarpPointer(display = self.display, onerror", "the corresponding key. led_mask A 32-bit mask indicating which LEDs", "If the extension is not supported, None is returned.\"\"\" r", "is X.DestroyAll, the other values are X.RetainPermanent and X.RetainTemporary.\"\"\" request.SetCloseDownMode(display", "self.class_extension_dicts.items(): origcls = self.display.resource_classes[class_name] self.display.resource_classes[class_name] = type(origcls.__name__, (origcls,), dictionary) #", "or a command line argument. Resource objects should never be", "is a list of tuples of keysyms. keysyms[n][i] will be", "# Maybe should check extension overrides too try: self.class_extension_dicts[class_name][name] =", "# This library is distributed in the hope that it", "def screen_count(self): \"\"\"Return the total number of screens on the", ".xobject import fontable from .xobject import colormap from .xobject import", "self.display_extension_methods = {} # a dict that maps the event", "of tuples with two # elements each: (index, keycode) #", "N contains the bits for keys 8N to 8N +", "returned: major_opcode The major opcode that the requests of this", "the least significant bit in the byte representing key 8N.", "the number of times that Display.next_event() can be called without", "string. FUNCTION is a normal function whose first argument is", "threshold = None, onerror = None): \"\"\"To change the pointer", "returned by Display.get_pointer_mapping(). map[n] sets the logical number for the", "of the pointer buttons. map is a list of logical", "= path) def get_font_path(self): \"\"\"Return the current font path as", "Software Foundation, Inc., # 59 Temple Place, # Suite 330,", "led_mode led_mode should be X.LedModeOff or X.LedModeOn. If led is", "should be X.LedModeOff or X.LedModeOn. If led is provided, it", "\"\"\"Release the server if it was previously grabbed by this", "arguments return map(lambda x: (x[1], x[0]), self._keymap_syms[keysym]) except KeyError: return", "bit set to 1 indicates that the corresponding key is", "window, X.PointerRoot or X.NONE. revert_to specifies where the focus reverts", "the LEDs that should change. If led is not provided,", "_resource_baseclasses.copy() # Implement a cache of atom names, used by", "request, event, rq # Xlib.xobjects modules from .xobject import resource", "path is empty, the default font path of the server", "mode, host_family, host, onerror = None): \"\"\"mode is either X.HostInsert", "details. There is also a Window.set_input_focus().\"\"\" request.SetInputFocus(display = self.display, onerror", "the following attributes: accel_num accel_denom The acceleration as numerator/denumerator. threshold", "'gc': fontable.GC, 'colormap': colormap.Colormap, 'cursor': cursor.Cursor, } _resource_hierarchy = {", "internal cache\"\"\" return self.display.get_atom(atom, only_if_exists) def get_atom_name(self, atom): \"\"\"Look up", "map) return r.status def get_pointer_mapping(self): \"\"\"Return a list of the", "the dynamic parameters of a pointer grab. See XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display", "one of X.RevertToParent, RevertToPointerRoot, or RevertToNone. \"\"\" return request.GetInputFocus(display =", "option) any later version. # # This library is distributed", "be the event object.\"\"\" if isinstance(evt, event.MappingNotify): if evt.request ==", "onerror, time = time) def allow_events(self, mode, time, onerror =", "self.display, onerror = onerror, do_accel = do_accel, do_thres = do_threshold,", "an object with the following attributes: global_auto_repeat X.AutoRepeatModeOn or X.AutoRepeatModeOff.", "the keyboard, where each bit set to 1 indicates that", "a mapping, where the keys # are keysyms. The values", "no_operation(self, onerror = None): \"\"\"Do nothing but send a request", "or, when it's an event with a subcode, to a", "caused by a certain request is trapped.\"\"\" # Do a", "License, or (at your option) any later version. # #", "modifiers X.Shift, X.Lock, X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5.", "keysym is bound, and # index is the keysyms index", "r = request.GetModifierMapping(display = self.display) return r.keycodes def no_operation(self, onerror", "X extensions dynamically added by the library will not be", "index = index + 1 code = code + 1", "(event code, subcode) in the # extension dict maintained in", "bell_pitch The pitch of the bell in Hz, -1 restores", "the module and fetch it __import__('Xlib.ext.' + modname) mod =", "Lesser General Public License # as published by the Free", "threshold) def get_pointer_control(self): \"\"\"Return an object with the following attributes:", "= self.display, map = map) return r.status def get_pointer_mapping(self): \"\"\"Return", "the DictWrapper extension_event. \"\"\" newevt = type(evt.__name__, evt.__bases__, evt.__dict__.copy()) newevt._code", "sets the logical number for the physical button n+1. Logical", "version 2.1 # of the License, or (at your option)", "\"\"\"Return the total number of screens on the display.\"\"\" return", "list of bytes. For the Internet family, it should be", "will not be available. \"\"\" return self.display.resource_classes[type](self.display, id) # We", "keycode.\"\"\" try: # Copy the map list, reversing the arguments", "None): \"\"\"Change the dynamic parameters of a pointer grab. See", "time) def get_input_focus(self): \"\"\"Return an object with the following attributes:", "= self.display) def set_access_control(self, mode, onerror = None): \"\"\"Enable use", "the key. # The keysym->keycode map is stored in a", "library; if not, write to the # Free Software Foundation,", "hosts on the access list. Each entry has the following", "event_mask = 0, propagate = 0, onerror = None): \"\"\"Send", "following strings: resource drawable window pixmap fontable font gc colormap", "\"\"\" if newstring is None: try: del self.keysym_translations[keysym] except KeyError:", "display object # # Copyright (C) 2000 <NAME> <<EMAIL>> #", "the screen roots and default colormaps. # Fix that by", "module method. OBJECT is the type of object to add", "the window destination which can be a window object, or", "The name of the font. min_bounds max_bounds min_char_or_byte2 max_char_or_byte2 default_char", "base volume of the bell, coded as above. bell_pitch The", "request.ChangeHosts(display = self.display, onerror = onerror, mode = mode, host_family", "sno is None: return self.display.info.roots[self.display.default_screen] else: return self.display.info.roots[sno] def screen_count(self):", "onerror = onerror, revert_to = revert_to, focus = focus, time", "X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes should be a eight-element", "library will not be available. \"\"\" return self.display.resource_classes[type](self.display, id) #", ".protocol import request, event, rq # Xlib.xobjects modules from .xobject", "atom names, used by Window objects when # dealing with", "resources that it holds.\"\"\" self.display.close() def set_error_handler(self, handler): \"\"\"Set the", "src_height is treated in a similar way. To move the", "name): \"\"\"Ask the server if it supports the extension name.", "[(index, code)] index = index + 1 code = code", "request.GetSelectionOwner(display = self.display, selection = selection) return r.owner def send_event(self,", "fileno(self): \"\"\"Returns the file descriptor number of the underlying socket.", "only_if_exists = only_if_exists) # don't cache NONE responses in case", "font, None is returned.\"\"\" fid = self.display.allocate_resource_id() ec = error.CatchError(error.BadName)", "for the entire keyboard will be modified.\"\"\" request.ChangeKeyboardControl(display = self.display,", "Otherwise the mapping is changed and X.MappingSuccess is returned.\"\"\" r", "0, onerror = None): \"\"\"Send a synthetic event to the", "\"\"\"Set the default error handler which will be called for", "None: name = evt.__name__ setattr(self.extension_event, name, code) def extension_add_subevent(self, code,", "refresh the keymap cache. \"\"\" # Delete all sym->code maps", "self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol def keysym_to_keycode(self, keysym): \"\"\"Look up", "= None): \"\"\"extension_add_subevent(code, evt, [name]) Add an extension subevent. CODE", "grabbed pointer and any queued events. See XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display =", "method: %s' % name) self.display_extension_methods[name] = function else: class_list =", "represents a keycode, and the tuple elements are # the", "if device input had been received.\"\"\" request.ForceScreenSaver(display = self.display, onerror", "get_pointer_mapping(self): \"\"\"Return a list of the pointer button mappings. Entry", "key auto_repeat_mode auto_repeat_mode should be one of X.AutoRepeatModeOff, X.AutoRepeatModeOn, or", "in protocol.events. See XSendEvent(3X11) for details. There is also a", "a sorted list of tuples with two # elements each:", "pointer relative its current position by the offsets (x, y).", "contains the bits for keys 8N to 8N + 7", "button n+1. Logical number 0 disables the button. Two physical", "The keycode->keysym map is stored in a list with 256", "handle display extension methods def __getattr__(self, attr): try: function =", "in threaded applications.\"\"\" self.display.flush() def sync(self): \"\"\"Flush the queue and", "has_extension(self, extension): \"\"\"Check if both the server and the client", "!= X.NoSymbol: if sym in self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index,", "KeyError: self.class_extension_dicts[class_name] = { name: method } def extension_add_event(self, code,", "been fetched e.g. from an resource or a command line", "key. # The keysym->keycode map is stored in a mapping,", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #", "any queued events. See XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display = self.display, onerror =", "See XUngrabKeyboard(3X11).\"\"\" request.UngrabKeyboard(display = self.display, onerror = onerror, time =", "will be modified, otherwise the global state for the entire", "the pointer must move before the acceleration kicks in.\"\"\" return", "X.EnableAccess, disable if it is X.DisableAccess.\"\"\" request.SetAccessControl(display = self.display, onerror", "self.display, max_names = max_names, pattern = pattern) return r.fonts def", "of pixels at once. To change the threshold, set it", "much as possible.\"\"\" request.GrabServer(display = self.display, onerror = onerror) def", "Find all supported extensions self.extensions = [] self.class_extension_dicts = {}", "RevertToNone. \"\"\" return request.GetInputFocus(display = self.display) def query_keymap(self): \"\"\"Return a", "Xlib modules from . import error from . import ext", "and has the following properties: name The name of the", "the total number of screens on the display.\"\"\" return len(self.display.info.roots)", "the error class. \"\"\" self.display.add_extension_error(code, err) ### ### keymap cache", "keysym, newstring): \"\"\"Change the translation of KEYSYM to NEWSTRING. If", "of type for the integer id. type should be one", "self.display.get_display_name() def fileno(self): \"\"\"Returns the file descriptor number of the", "for intern_atom, using internal cache\"\"\" return self.display.get_atom(atom, only_if_exists) def get_atom_name(self,", "return extension in self.extensions def create_resource_object(self, type, id): \"\"\"Create a", "key, 0 is returned.\"\"\" try: return self._keymap_syms[keysym][0][1] except (KeyError, IndexError):", "cache NONE responses in case someone creates this later if", "allow_exposures) def get_screen_saver(self): \"\"\"Return an object with the attributes timeout,", "= None): \"\"\"Change the dynamic parameters of a pointer grab.", "r = request.QueryKeymap(display = self.display) return r.map def open_font(self, name):", "Each list item represents one font and has the following", "a better way to do it... self.get_pointer_control() def next_event(self): \"\"\"Return", "the window that owns selection (an atom), or X.NONE if", "queued, i.e. the number of times that Display.next_event() can be", "it supports the extension name. If it is supported an", "the keycodes for the eight modifiers X.Shift, X.Lock, X.Control, X.Mod1,", "Call initialiasation function mod.init(self, info) self.extensions.append(extname) # Finalize extensions by", "import cursor _resource_baseclasses = { 'resource': resource.Resource, 'drawable': drawable.Drawable, 'window':", "client-internal keysym to string translations ### def lookup_string(self, keysym): \"\"\"Return", "ungrab_keyboard(self, time, onerror = None): \"\"\"Ungrab a grabbed keyboard and", "dynamic parameters of a pointer grab. See XChangeActivePointerGrab(3X11).\"\"\" request.ChangeActivePointerGrab(display =", "significant bit in the byte representing key 8N.\"\"\" r =", "create_unbound_method # Xlib modules from . import error from .", "this to handle display extension methods def __getattr__(self, attr): try:", "X.NONE if there is no owner for the selection. Can", "# index is the keysyms index in the map for", "return self.display.get_display_name() def fileno(self): \"\"\"Returns the file descriptor number of", "(an atom), or X.NONE if there is no owner for", "object with the following attributes: accel_num accel_denom The acceleration as", "this wraps the dict so you address it as #", "provided when creating the Display object, or fetched from the", "onerror = None): \"\"\"mode is either X.HostInsert or X.HostDelete. host_family", "length as the list returned by Display.get_pointer_mapping(). map[n] sets the", "# dealing with some ICCCM properties not defined in Xlib.Xatom", "number. If one of the buttons to be altered are", "with the following attributes: mode X.EnableAccess if the access control", "setting. bell_percent The base volume of the bell, coded as", "font path to path, which should be a list of", "None): \"\"\"Send a synthetic event to the window destination which", "0, src_height = 0, onerror = None): \"\"\"Move the pointer", "of times that Display.next_event() can be called without blocking.\"\"\" return", "request.ListExtensions(display = self.display) return r.names def change_keyboard_mapping(self, first_keycode, keysyms, onerror", "\"\"\"Return an object with the following attributes: global_auto_repeat X.AutoRepeatModeOn or", "def intern_atom(self, name, only_if_exists = 0): \"\"\"Intern the string name,", "display resource drawable window pixmap fontable font gc colormap cursor", "Xlib.xobjects modules from .xobject import resource from .xobject import drawable", "list the keycodes bound to that modifier.\"\"\" r = request.GetModifierMapping(display", "will be None. See section Error Handling.\"\"\" self.display.set_error_handler(handler) def flush(self):", "the default font path of the server will be restored.\"\"\"", "returned.\"\"\" fid = self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display = self.display,", "return None def list_extensions(self): \"\"\"Return a list of all the", "four bytes of an IPv4 address.\"\"\" request.ChangeHosts(display = self.display, onerror", "def get_display_name(self): \"\"\"Returns the name used to connect to the", "be a window, X.PointerRoot or X.NONE. revert_to specifies where the", "extensions provided by the server.\"\"\" r = request.ListExtensions(display = self.display)", "as a normal request error handler, but the second argument", "numeric code, subcode is the sub-ID of this event that", "sym in syms: if sym != X.NoSymbol: if sym in", "events queued, it will block until the next event is", "logical state of the keyboard, where each bit set to", "= None): \"\"\"If mode is X.ScreenSaverActive the screen saver is", "evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected a MappingNotify", "\"\"\"Internal function, called to refresh the keymap cache. \"\"\" #", "= onerror, revert_to = revert_to, focus = focus, time =", "is used, X.DisableAccess otherwise. hosts The hosts on the access", "= self.display, onerror = onerror, mode = mode) def set_close_down_mode(self,", "X.Mod3, X.Mod4 and X.Mod5. keycodes should be a eight-element list", "the Internet family, it should be the four bytes of", "Update sym->code map code = first_keycode for syms in keysyms:", "# Get the new keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode, count)", "self.class_extension_dicts[class_name] = { name: method } def extension_add_event(self, code, evt,", "modname in ext.__extensions__: if extname in exts: # Import the", "request queue, building and sending the queued requests. This can", "self.display, onerror = onerror, cursor = cursor, time = time,", "looking in entry index. Normally index 0 is unshifted, 1", "interval, prefer_blanking, allow_exposures. See XGetScreenSaver(3X11) for details.\"\"\" return request.GetScreenSaver(display =", "src_x. src_height is treated in a similar way. To move", "objects when # dealing with some ICCCM properties not defined", "avoided as much as possible.\"\"\" request.GrabServer(display = self.display, onerror =", "Go through all extension modules for extname, modname in ext.__extensions__:", "No more than max_names will be returned. Each list item", "restored.\"\"\" request.SetFontPath(display = self.display, onerror = onerror, path = path)", "a list of logical button numbers. map must be of", "button. Two physical buttons cannot be mapped to the same", "of XFontStruct in XGetFontProperty(3X11) for details on these values. properties", "of events queued, i.e. the number of times that Display.next_event()", "onerror = onerror, time = time) def change_active_pointer_grab(self, event_mask, cursor,", "modules import types # Python 2/3 compatibility. from six import", "it holds.\"\"\" self.display.close() def set_error_handler(self, handler): \"\"\"Set the default error", "a certain request is trapped.\"\"\" # Do a light-weight replyrequest", "= self.display, onerror = ec, fid = fid, name =", "XUngrabPointer(3X11).\"\"\" request.UngrabPointer(display = self.display, onerror = onerror, time = time)", "(keycode, index) is returned, sorted primarily on the lowest index", "= 0, onerror = None): \"\"\"Move the pointer relative its", "be returned.\"\"\" r = request.ListFonts(display = self.display, max_names = max_names,", "as if device input had been received.\"\"\" request.ForceScreenSaver(display = self.display,", "alt grid, and 3 is shift+alt grid. If that key", "extensions: the screen roots and default colormaps. # Fix that", "r = request.InternAtom(display = self.display, name = name, only_if_exists =", "altered are logically in the down state, X.MappingBusy is returned", "resources at connection close. The default is X.DestroyAll, the other", "onerror = None): \"\"\"Send a synthetic event to the window", "keymap cache implementation ### # The keycode->keysym map is stored", "keysyms) def get_keyboard_mapping(self, first_keycode, count): \"\"\"Return the current keyboard mapping", "map is stored in a mapping, where the keys #", "one of X.AutoRepeatModeOff, X.AutoRepeatModeOn, or X.AutoRepeatModeDefault. If key is provided,", "X extension module method. OBJECT is the type of object", "to replace %s method: %s' % (class_name, name)) method =", "None): \"\"\"Disable processing of requests on all other client connections", "i = 0 while i < len(codes): code = codes[i][1]", "\"\"\"Return the current keyboard mapping as a list of tuples,", "request.SetPointerMapping(display = self.display, map = map) return r.status def get_pointer_mapping(self):", "dynamically added by the library will not be available. \"\"\"", "list of strings. If path is empty, the default font", "server.\"\"\" return self.display.next_event() def pending_events(self): \"\"\"Return the number of events", "any X extensions dynamically added by the library will not", "bound, and # index is the keysyms index in the", "and so on. The sublists list the keycodes bound to", "self._atom_cache: return self._atom_cache[atomname] r = request.InternAtom(display = self, name =", "it is important that errors caused by a certain request", "to keycode first_keycode+n at index i.\"\"\" request.ChangeKeyboardMapping(display = self.display, onerror", "host_family is one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is", "Public License # as published by the Free Software Foundation;", "The number of pixels the pointer must move before the", "onerror, mode = mode) def set_pointer_mapping(self, map): \"\"\"Set the mapping", "index and lowest code is returned. If keysym is not", "entry in the DictWrapper extension_event. \"\"\" newevt = type(evt.__name__, evt.__bases__,", "= self.display, onerror = onerror, mode = mode, host_family =", "change_keyboard_control(self, onerror = None, **keys): \"\"\"Change the parameters provided as", "no owner for the selection. Can raise BadAtom.\"\"\" r =", "request.GetScreenSaver(display = self.display) def change_hosts(self, mode, host_family, host, onerror =", "MappingNotify event') def _update_keymap(self, first_keycode, count): \"\"\"Internal function, called to", "it. If src_width is 0 it will be replaced with", "self.display, onerror = onerror, attrs = keys) def get_keyboard_control(self): \"\"\"Return", "Replace code->sym map with the new map self._keymap_codes[first_keycode:lastcode] = keysyms", "extension uses. first_event The base event code if the extension", "screen saver is deactivated as if device input had been", "self.display, atom = atom) return r.name def get_selection_owner(self, selection): \"\"\"Return", "subcode is the sub-ID of this event that shares the", "self.query_extension(extname) self.display.set_extension_major(extname, info.major_opcode) # Call initialiasation function mod.init(self, info) self.extensions.append(extname)", "dictionary) # Problem: we have already created some objects without", "any later version. # # This library is distributed in", "there is no owner for the selection. Can raise BadAtom.\"\"\"", "the numeric code, and ERR is the error class. \"\"\"", "self.display) def set_access_control(self, mode, onerror = None): \"\"\"Enable use of", "\"\"\"Return a list of fonts matching pattern. No more than", "and no more than count.\"\"\" r = request.GetKeyboardMapping(display = self.display,", "request.InternAtom(display = self, name = atomname, only_if_exists = only_if_exists) #", "r.map def set_modifier_mapping(self, keycodes): \"\"\"Set the keycodes for the eight", "translation is found. \"\"\" s = self.keysym_translations.get(keysym) if s is", "either provided when creating the Display object, or fetched from", "the mapping of the pointer buttons. map is a list", "event_mask = event_mask) def ungrab_keyboard(self, time, onerror = None): \"\"\"Ungrab", "keysym. If several keycodes are found, the one with the", "keyword arguments: key_click_percent The volume of key clicks between 0", "onerror = onerror, do_accel = do_accel, do_thres = do_threshold, accel_num", "keysym. A list of tuples (keycode, index) is returned, sorted", "are X.RetainPermanent and X.RetainTemporary.\"\"\" request.SetCloseDownMode(display = self.display, onerror = onerror,", "setattr(self.extension_event, name, (code,subcode)) def add_extension_error(self, code, err): \"\"\"add_extension_error(code, err) Add", "General Public # License along with this library; if not,", "not defined in Xlib.Xatom def __init__(self, *args, **keys): protocol_display.Display.__init__(self, *args,", "be X.RevertToParent, RevertToPointerRoot, or RevertToNone. See XSetInputFocus(3X11) for details. There", "returning its atom number. If only_if_exists is true and the", "keysym, codes in self._keymap_syms.items(): i = 0 while i <", "client.\"\"\" request.UngrabServer(display = self.display, onerror = onerror) def warp_pointer(self, x,", "class. \"\"\" self.display.add_extension_error(code, err) ### ### keymap cache implementation ###", "onerror, src_window = src_window, dst_window = X.NONE, src_x = src_x,", "keysyms index in the map for that keycode. def keycode_to_keysym(self,", "event object.\"\"\" if isinstance(evt, event.MappingNotify): if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode,", "= None): \"\"\"extension_add_event(code, evt, [name]) Add an extension event. CODE", "from . import X # Xlib.protocol modules from .protocol import", "s is not None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym)", "item N contains the bits for keys 8N to 8N", "errors, or 0. If the extension is not supported, None", "of the bell. \"\"\" return request.GetKeyboardControl(display = self.display) def bell(self,", "= onerror, do_accel = do_accel, do_thres = do_threshold, accel_num =", "EVT. This name is used to insert an entry in", "the keymap cache. evt should be the event object.\"\"\" if", "code, subcode is the sub-ID of this event that shares", "keysym, looking in entry index. Normally index 0 is unshifted,", "def force_screen_saver(self, mode, onerror = None): \"\"\"If mode is X.ScreenSaverActive", "all other client connections until the server is ungrabbed. Server", "the offsets (x, y). However, if src_window is a window", "self.keysym_translations[keysym] except KeyError: pass else: self.keysym_translations[keysym] = newstring ### ###", "a cache of atom names, used by Window objects when", "def change_keyboard_mapping(self, first_keycode, keysyms, onerror = None): \"\"\"Modify the keyboard", "the queued requests. This can be necessary in applications that", "it... self.get_pointer_control() def next_event(self): \"\"\"Return the next event. If there", "it is supported an object with the following attributes is", "following attributes is returned: major_opcode The major opcode that the", "e.g. from an resource or a command line argument. Resource", "keycodes that is bound to keysym. A list of tuples", "hasattr(cls, name): raise AssertionError('attempting to replace %s method: %s' %", "of atom, returning it as a string. Will raise BadAtom", "input had been received.\"\"\" request.ForceScreenSaver(display = self.display, onerror = onerror,", "window object, or X.PointerWindow or X.InputFocus. event is the event", "# or, when it's an event with a subcode, to", "0, onerror = None): \"\"\"Move the pointer relative its current", "= self.display, atom = atom) return r.name def get_selection_owner(self, selection):", "XSetInputFocus(3X11) for details. There is also a Window.set_input_focus().\"\"\" request.SetInputFocus(display =", "screen.root.id) screen.default_colormap = self.display.resource_classes['colormap'](self.display, screen.default_colormap.id) def get_display_name(self): \"\"\"Returns the name", "to handle display extension methods def __getattr__(self, attr): try: function", "src_height = 0, onerror = None): \"\"\"Move the pointer relative", "X.FamilyChaos. name A list of byte values, the coding depends", "Delete all sym->code maps for the changed codes lastcode =", "a tuple of (event code, subcode) in the # extension", "the focused window becomes not visible, and should be X.RevertToParent,", "queued events. mode should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard,", "holds the input focus, X.NONE or X.PointerRoot. revert_to Where the", "byte values, the coding depends on family. For the Internet", "'fontable', 'font', 'gc', 'colormap', 'cursor'), 'drawable': ('window', 'pixmap'), 'fontable': ('font',", "font and has the following properties: name The name of", "< lastcode: del codes[i] else: i = i + 1", "100. bell_percent bell_pitch bell_duration The volume, pitch and duration of", "return request.GetPointerControl(display = self.display) def set_screen_saver(self, timeout, interval, prefer_blank, allow_exposures,", "represented as a list of 32 integers. List item N", "it moves beyond the threshold number of pixels at once.", "name): raise AssertionError('attempting to replace %s method: %s' % (class_name,", "map list, reversing the arguments return map(lambda x: (x[1], x[0]),", "bell(self, percent = 0, onerror = None): \"\"\"Ring the bell", "shares the code ID with other sub-events and EVT is", "the access control list is used, X.DisableAccess otherwise. hosts The", "when it's an event with a subcode, to a tuple", "volume percent which is relative the base volume. See XBell(3X11).\"\"\"", "= None): \"\"\"elease a grabbed pointer and any queued events.", "X.AutoRepeatModeOff. auto_repeats A list of 32 integers. List item N", ". import ext from . import X # Xlib.protocol modules", "following attributes: family X.FamilyInternet, X.FamilyDECnet, or X.FamilyChaos. name A list", "new map self._keymap_codes[first_keycode:lastcode] = keysyms # Update sym->code map code", "number of the default screen, extracted from the display name.\"\"\"", "try: self.class_extension_dicts[class_name][name] = method except KeyError: self.class_extension_dicts[class_name] = { name:", "bit vector for the logical state of the keyboard, where", "= [()] * 256 self._keymap_syms = {} self._update_keymap(self.display.info.min_keycode, (self.display.info.max_keycode -", "cls) # Maybe should check extension overrides too try: self.class_extension_dicts[class_name][name]", "keycode, and the tuple elements are # the keysyms bound", "= None): \"\"\"Enable use of access control lists at connection", "The list can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so", "attributes: global_auto_repeat X.AutoRepeatModeOn or X.AutoRepeatModeOff. auto_repeats A list of 32", "# be a better way to do it... self.get_pointer_control() def", "true and the atom does not already exist, it will", "class directly, since any X extensions dynamically added by the", "### # The keycode->keysym map is stored in a list", "_code of the new event class will be set to", "src_width, src_height = src_height, dst_x = x, dst_y = y)", "= focus, time = time) def get_input_focus(self): \"\"\"Return an object", "of X.AutoRepeatModeOff, X.AutoRepeatModeOn, or X.AutoRepeatModeDefault. If key is provided, that", "the following attributes: mode X.EnableAccess if the access control list", "to strings. self.keysym_translations = {} # Find all supported extensions", "X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be a timestamp", "colormap.Colormap, 'cursor': cursor.Cursor, } _resource_hierarchy = { 'resource': ('drawable', 'window',", "sym != X.NoSymbol: if sym in self._keymap_syms: symcodes = self._keymap_syms[sym]", "X.EnableAccess if the access control list is used, X.DisableAccess otherwise.", "def __init__(self, *args, **keys): protocol_display.Display.__init__(self, *args, **keys) self._atom_cache = {}", "to sync. There must # be a better way to", "the keymap cache. \"\"\" # Delete all sym->code maps for", "A PARTICULAR PURPOSE. # See the GNU Lesser General Public", "= self.display, onerror = onerror) def ungrab_server(self, onerror = None):", "current keyboard mapping as a list of tuples, starting at", "and # index is the keysyms index in the map", "a 32-bit mask listing the LEDs that should change. If", "an object with the following attributes: focus The window which", "the server and the client library support the X extension", "'cursor'), 'drawable': ('window', 'pixmap'), 'fontable': ('font', 'gc') } class _BaseDisplay(protocol_display.Display):", "mode) def force_screen_saver(self, mode, onerror = None): \"\"\"If mode is", "destination = destination, event_mask = event_mask, event = event) def", "method: %s' % (class_name, name)) method = create_unbound_method(function, cls) #", "Window.set_input_focus().\"\"\" request.SetInputFocus(display = self.display, onerror = onerror, revert_to = revert_to,", "If several keycodes are found, the one with the lowest", "attributes: accel_num accel_denom The acceleration as numerator/denumerator. threshold The number", "else: raise TypeError('expected a MappingNotify event') def _update_keymap(self, first_keycode, count):", "someone creates this later if r.atom != X.NONE: self._atom_cache[atomname] =", "Lesser General Public # License along with this library; if", "= create_unbound_method(function, cls) # Maybe should check extension overrides too", "does not exist.\"\"\" r = request.GetAtomName(display = self.display, atom =", "a bit is on, autorepeat is enabled for the corresponding", "onerror, mode = mode) def force_screen_saver(self, mode, onerror = None):", "\"\"\"Release some queued events. mode should be one of X.AsyncPointer,", "an IPv4 address. \"\"\" return request.ListHosts(display = self.display) def set_access_control(self,", "# # You should have received a copy of the", "move num/denum times the normal speed if it moves beyond", "codes[i] else: i = i + 1 # Get the", "Display(object): def __init__(self, display = None): self.display = _BaseDisplay(display) #", "keyboard will be modified.\"\"\" request.ChangeKeyboardControl(display = self.display, onerror = onerror,", "cursor, time, onerror = None): \"\"\"Change the dynamic parameters of", "no reasonable translation is found. \"\"\" s = self.keysym_translations.get(keysym) if", "without even the implied warranty of # MERCHANTABILITY or FITNESS", "= onerror, mode = mode, time = time) def grab_server(self,", "not None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym) def rebind_string(self," ]
[ "range(n): for j in range(m): sij = s[i][j] if sij", "range(26)] for i in range(n): for j in range(m): sij", "= [input() for _ in range(q_large)] pos = [None for", "_ in range(q_large)] pos = [None for _ in range(26)]", "+ 1) for qi in q: index = ascii_uppercase.index(qi) p", "in range(m): sij = s[i][j] if sij != \"*\": index", "-*- coding: utf-8 -*- def main(): from string import ascii_uppercase", "= [list(input()) for _ in range(n)] q = [input() for", "\"*\": index = ascii_uppercase.index(sij) pos[index] = (i + 1, j", "index = ascii_uppercase.index(sij) pos[index] = (i + 1, j +", "is None: print(\"NA\") else: print(p[0], p[1]) if __name__ == \"__main__\":", "= ascii_uppercase.index(qi) p = pos[index] if p is None: print(\"NA\")", "q_large = map(int, input().split()) s = [list(input()) for _ in", "[list(input()) for _ in range(n)] q = [input() for _", "m, q_large = map(int, input().split()) s = [list(input()) for _", "range(m): sij = s[i][j] if sij != \"*\": index =", "!= \"*\": index = ascii_uppercase.index(sij) pos[index] = (i + 1,", "None: print(\"NA\") else: print(p[0], p[1]) if __name__ == \"__main__\": main()", "+ 1, j + 1) for qi in q: index", "main(): from string import ascii_uppercase n, m, q_large = map(int,", "coding: utf-8 -*- def main(): from string import ascii_uppercase n,", "for _ in range(26)] for i in range(n): for j", "(i + 1, j + 1) for qi in q:", "for j in range(m): sij = s[i][j] if sij !=", "def main(): from string import ascii_uppercase n, m, q_large =", "map(int, input().split()) s = [list(input()) for _ in range(n)] q", "s = [list(input()) for _ in range(n)] q = [input()", "pos = [None for _ in range(26)] for i in", "in range(26)] for i in range(n): for j in range(m):", "n, m, q_large = map(int, input().split()) s = [list(input()) for", "= s[i][j] if sij != \"*\": index = ascii_uppercase.index(sij) pos[index]", "if p is None: print(\"NA\") else: print(p[0], p[1]) if __name__", "_ in range(n)] q = [input() for _ in range(q_large)]", "p = pos[index] if p is None: print(\"NA\") else: print(p[0],", "s[i][j] if sij != \"*\": index = ascii_uppercase.index(sij) pos[index] =", "1) for qi in q: index = ascii_uppercase.index(qi) p =", "= ascii_uppercase.index(sij) pos[index] = (i + 1, j + 1)", "string import ascii_uppercase n, m, q_large = map(int, input().split()) s", "sij = s[i][j] if sij != \"*\": index = ascii_uppercase.index(sij)", "= map(int, input().split()) s = [list(input()) for _ in range(n)]", "p is None: print(\"NA\") else: print(p[0], p[1]) if __name__ ==", "from string import ascii_uppercase n, m, q_large = map(int, input().split())", "q = [input() for _ in range(q_large)] pos = [None", "_ in range(26)] for i in range(n): for j in", "pos[index] = (i + 1, j + 1) for qi", "index = ascii_uppercase.index(qi) p = pos[index] if p is None:", "for i in range(n): for j in range(m): sij =", "import ascii_uppercase n, m, q_large = map(int, input().split()) s =", "ascii_uppercase.index(qi) p = pos[index] if p is None: print(\"NA\") else:", "= pos[index] if p is None: print(\"NA\") else: print(p[0], p[1])", "input().split()) s = [list(input()) for _ in range(n)] q =", "q: index = ascii_uppercase.index(qi) p = pos[index] if p is", "i in range(n): for j in range(m): sij = s[i][j]", "pos[index] if p is None: print(\"NA\") else: print(p[0], p[1]) if", "in range(q_large)] pos = [None for _ in range(26)] for", "j in range(m): sij = s[i][j] if sij != \"*\":", "ascii_uppercase.index(sij) pos[index] = (i + 1, j + 1) for", "ascii_uppercase n, m, q_large = map(int, input().split()) s = [list(input())", "for qi in q: index = ascii_uppercase.index(qi) p = pos[index]", "if sij != \"*\": index = ascii_uppercase.index(sij) pos[index] = (i", "range(q_large)] pos = [None for _ in range(26)] for i", "= [None for _ in range(26)] for i in range(n):", "in range(n)] q = [input() for _ in range(q_large)] pos", "range(n)] q = [input() for _ in range(q_large)] pos =", "in q: index = ascii_uppercase.index(qi) p = pos[index] if p", "j + 1) for qi in q: index = ascii_uppercase.index(qi)", "qi in q: index = ascii_uppercase.index(qi) p = pos[index] if", "-*- def main(): from string import ascii_uppercase n, m, q_large", "for _ in range(q_large)] pos = [None for _ in", "# -*- coding: utf-8 -*- def main(): from string import", "[input() for _ in range(q_large)] pos = [None for _", "sij != \"*\": index = ascii_uppercase.index(sij) pos[index] = (i +", "<reponame>KATO-Hiro/AtCoder<filename>Others/qupc/qupc2014/c/main.py # -*- coding: utf-8 -*- def main(): from string", "1, j + 1) for qi in q: index =", "in range(n): for j in range(m): sij = s[i][j] if", "for _ in range(n)] q = [input() for _ in", "= (i + 1, j + 1) for qi in", "[None for _ in range(26)] for i in range(n): for", "utf-8 -*- def main(): from string import ascii_uppercase n, m," ]
[ "\"\"\" Designed to compare the the adapter and the DProtocol", "a incoming request against a candidate DProtocol implementation registered as", "protocol argument will raise AttributeError. \"\"\" adapter = Attribute(\"The implementer", "to compare the the adapter and the DProtocol signature if", "attribute is designed to be provided by classes which are", "The `protocol` attribute is designed to be provided by classes", "from zope.interface import Interface, Attribute class IBaseResourceSubscriber(Interface): \"\"\" IBaseResourceSubscriber provides", "IBaseResourceSubscriber(Interface): \"\"\" IBaseResourceSubscriber provides functionality for comparison of the signature", "for comparison of the signature on a incoming request against", "instance\") def compare(): \"\"\" Designed to compare the the adapter", "implementation registered as IJSONResource The `adapter` is our first argument", "argument will raise AttributeError. \"\"\" adapter = Attribute(\"The implementer have", "the signatures is equal \"\"\" class IJSONResourceSubscriber(Interface): \"\"\" \"\"\" class", "AttributeError. \"\"\" adapter = Attribute(\"The implementer have to provide implementation", "the constructor. It's used from the adapter pattern and have", "signatures is equal \"\"\" class IJSONResourceSubscriber(Interface): \"\"\" \"\"\" class IXMLResourceSubscriber(Interface):", "Attribute(\"The implementer have to provide implementation of IJSONResource\") protocol =", "on a incoming request against a candidate DProtocol implementation registered", "adapter and the DProtocol signature if the signatures is equal", "DProtocol signature if the signatures is equal \"\"\" class IJSONResourceSubscriber(Interface):", "constructor. It's used from the adapter pattern and have to", "registered as IJSONResource The `adapter` is our first argument in", "raise AttributeError. \"\"\" adapter = Attribute(\"The implementer have to provide", "provided by classes which are implements IJSONResourceSubscriber, or inherit from", "from the adapter pattern and have to be from type", "and the DProtocol signature if the signatures is equal \"\"\"", "first argument in the constructor. It's used from the adapter", "from DProtocolSubscriber. If subclass does not provide the protocol argument", "\"\"\" IBaseResourceSubscriber provides functionality for comparison of the signature on", "in the constructor. It's used from the adapter pattern and", "IJSONResource The `protocol` attribute is designed to be provided by", "It's used from the adapter pattern and have to be", "implementer have to provide implementation of IJSONResource\") protocol = Attribute(\"DProtocol", "`protocol` attribute is designed to be provided by classes which", "import Interface, Attribute class IBaseResourceSubscriber(Interface): \"\"\" IBaseResourceSubscriber provides functionality for", "have to be from type IJSONResource The `protocol` attribute is", "used from the adapter pattern and have to be from", "designed to be provided by classes which are implements IJSONResourceSubscriber,", "adapter pattern and have to be from type IJSONResource The", "request against a candidate DProtocol implementation registered as IJSONResource The", "provide the protocol argument will raise AttributeError. \"\"\" adapter =", "our first argument in the constructor. It's used from the", "is equal \"\"\" class IJSONResourceSubscriber(Interface): \"\"\" \"\"\" class IXMLResourceSubscriber(Interface): \"\"\"", "not provide the protocol argument will raise AttributeError. \"\"\" adapter", "compare(): \"\"\" Designed to compare the the adapter and the", "is our first argument in the constructor. It's used from", "__author__ = 'dimd' from zope.interface import Interface, Attribute class IBaseResourceSubscriber(Interface):", "are implements IJSONResourceSubscriber, or inherit from DProtocolSubscriber. If subclass does", "incoming request against a candidate DProtocol implementation registered as IJSONResource", "does not provide the protocol argument will raise AttributeError. \"\"\"", "the adapter pattern and have to be from type IJSONResource", "against a candidate DProtocol implementation registered as IJSONResource The `adapter`", "or inherit from DProtocolSubscriber. If subclass does not provide the", "be provided by classes which are implements IJSONResourceSubscriber, or inherit", "functionality for comparison of the signature on a incoming request", "have to provide implementation of IJSONResource\") protocol = Attribute(\"DProtocol instance\")", "as IJSONResource The `adapter` is our first argument in the", "candidate DProtocol implementation registered as IJSONResource The `adapter` is our", "\"\"\" adapter = Attribute(\"The implementer have to provide implementation of", "of the signature on a incoming request against a candidate", "classes which are implements IJSONResourceSubscriber, or inherit from DProtocolSubscriber. If", "IJSONResource The `adapter` is our first argument in the constructor.", "type IJSONResource The `protocol` attribute is designed to be provided", "Attribute class IBaseResourceSubscriber(Interface): \"\"\" IBaseResourceSubscriber provides functionality for comparison of", "DProtocolSubscriber. If subclass does not provide the protocol argument will", "= 'dimd' from zope.interface import Interface, Attribute class IBaseResourceSubscriber(Interface): \"\"\"", "to be provided by classes which are implements IJSONResourceSubscriber, or", "If subclass does not provide the protocol argument will raise", "the protocol argument will raise AttributeError. \"\"\" adapter = Attribute(\"The", "of IJSONResource\") protocol = Attribute(\"DProtocol instance\") def compare(): \"\"\" Designed", "implements IJSONResourceSubscriber, or inherit from DProtocolSubscriber. If subclass does not", "IBaseResourceSubscriber provides functionality for comparison of the signature on a", "protocol = Attribute(\"DProtocol instance\") def compare(): \"\"\" Designed to compare", "from type IJSONResource The `protocol` attribute is designed to be", "equal \"\"\" class IJSONResourceSubscriber(Interface): \"\"\" \"\"\" class IXMLResourceSubscriber(Interface): \"\"\" \"\"\"", "which are implements IJSONResourceSubscriber, or inherit from DProtocolSubscriber. If subclass", "provide implementation of IJSONResource\") protocol = Attribute(\"DProtocol instance\") def compare():", "<filename>NetCatKS/DProtocol/api/interfaces/subscribers/__init__.py<gh_stars>0 __author__ = 'dimd' from zope.interface import Interface, Attribute class", "be from type IJSONResource The `protocol` attribute is designed to", "Interface, Attribute class IBaseResourceSubscriber(Interface): \"\"\" IBaseResourceSubscriber provides functionality for comparison", "Attribute(\"DProtocol instance\") def compare(): \"\"\" Designed to compare the the", "compare the the adapter and the DProtocol signature if the", "comparison of the signature on a incoming request against a", "pattern and have to be from type IJSONResource The `protocol`", "to be from type IJSONResource The `protocol` attribute is designed", "the DProtocol signature if the signatures is equal \"\"\" class", "inherit from DProtocolSubscriber. If subclass does not provide the protocol", "the the adapter and the DProtocol signature if the signatures", "Designed to compare the the adapter and the DProtocol signature", "`adapter` is our first argument in the constructor. It's used", "IJSONResource\") protocol = Attribute(\"DProtocol instance\") def compare(): \"\"\" Designed to", "the signature on a incoming request against a candidate DProtocol", "provides functionality for comparison of the signature on a incoming", "the adapter and the DProtocol signature if the signatures is", "is designed to be provided by classes which are implements", "= Attribute(\"DProtocol instance\") def compare(): \"\"\" Designed to compare the", "The `adapter` is our first argument in the constructor. It's", "IJSONResourceSubscriber, or inherit from DProtocolSubscriber. If subclass does not provide", "implementation of IJSONResource\") protocol = Attribute(\"DProtocol instance\") def compare(): \"\"\"", "by classes which are implements IJSONResourceSubscriber, or inherit from DProtocolSubscriber.", "signature on a incoming request against a candidate DProtocol implementation", "DProtocol implementation registered as IJSONResource The `adapter` is our first", "argument in the constructor. It's used from the adapter pattern", "adapter = Attribute(\"The implementer have to provide implementation of IJSONResource\")", "a candidate DProtocol implementation registered as IJSONResource The `adapter` is", "to provide implementation of IJSONResource\") protocol = Attribute(\"DProtocol instance\") def", "if the signatures is equal \"\"\" class IJSONResourceSubscriber(Interface): \"\"\" \"\"\"", "and have to be from type IJSONResource The `protocol` attribute", "signature if the signatures is equal \"\"\" class IJSONResourceSubscriber(Interface): \"\"\"", "def compare(): \"\"\" Designed to compare the the adapter and", "= Attribute(\"The implementer have to provide implementation of IJSONResource\") protocol", "class IBaseResourceSubscriber(Interface): \"\"\" IBaseResourceSubscriber provides functionality for comparison of the", "will raise AttributeError. \"\"\" adapter = Attribute(\"The implementer have to", "'dimd' from zope.interface import Interface, Attribute class IBaseResourceSubscriber(Interface): \"\"\" IBaseResourceSubscriber", "subclass does not provide the protocol argument will raise AttributeError.", "zope.interface import Interface, Attribute class IBaseResourceSubscriber(Interface): \"\"\" IBaseResourceSubscriber provides functionality" ]
[ "columns correspond to the two feet and the rows are", "\"configuration\"]] possible_configurations = { \"030\", \"033\", \"040\", \"066\", \"085\", \"090\",", "= {\"LeftFoot\": (None, None), \"RightFoot\": (None, None)} for foot in", "missing_configurations: not_evaluated.append( \" \".join([gait_test, patient, *missing_configurations, foot]) ) if len(missing_configurations)", "Returns ------- d A dictionary where the keys are equal", "gait_test) ][[gait_parameter, \"configuration\"]] possible_configurations = { \"030\", \"033\", \"040\", \"066\",", "pd from scipy.stats import f_oneway from typing import Dict, Tuple,", "significant_results[gait_parameter].count().sum(), ] columns = [\"n_patients\", \"n_patients_significant\", \"n_feet_significant\"] anova_overview = pd.concat(", "anova using each column as a different measurement.\"\"\" parameter =", "* 2, [\"LeftFoot\", \"RightFoot\"]] ), data=[ [ anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1], ]", ".dropna(axis=0, how=\"all\") ) def _calculate_anova(data: pd.DataFrame) -> Tuple: \"\"\"Calculate one-way", "set(patient_data[\"foot\"]): missing_condition = None foot_data = patient_data[ (patient_data[\"foot\"] == foot)", "anova_dict[patient][\"RightFoot\"][1], ] ], ) anova_df = pd.concat([anova_df, row]) return anova_df,", "`dataset`. The values are dataframes, where the columns correspond to", "float ) -> pd.DataFrame: anova_overview = pd.DataFrame() significant_results = {}", "\"configuration\"][0] data_ = [ data[data[\"configuration\"] == configuration][parameter].T.to_numpy() for configuration in", "[] for patient, patient_data in dataset.items(): anova_dict[patient] = {\"LeftFoot\": (None,", "dataset A dictionary, where the keys are descriptions for different", "len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(), ] columns = [\"n_patients\", \"n_patients_significant\", \"n_feet_significant\"] anova_overview =", "[ len(all_results[gait_parameter]), len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(), ] columns = [\"n_patients\", \"n_patients_significant\", \"n_feet_significant\"]", "\"slow\" / \"fast\". The second level describes the DBS configureation,", "len(missing_configurations) > (len(possible_configurations) - 2): print( \"Not evaluating this foot,", "possible_configurations = { \"030\", \"033\", \"040\", \"066\", \"085\", \"090\", \"100\",", "data=[ [ anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1], ] ], ) anova_df = pd.concat([anova_df,", "missing_configurations = possible_configurations - actual_configurations if missing_configurations: not_evaluated.append( \" \".join([gait_test,", "for this specific `gait_test` \"\"\" anova_dict = {} anova_df =", ") def _calculate_anova(data: pd.DataFrame) -> Tuple: \"\"\"Calculate one-way anova using", "= patient_data[ (patient_data[\"foot\"] == foot) & (patient_data[\"test\"] == gait_test) ][[gait_parameter,", "== foot) & (patient_data[\"test\"] == gait_test) ][[gait_parameter, \"configuration\"]] possible_configurations =", "(None, None)} for foot in set(patient_data[\"foot\"]): missing_condition = None foot_data", "columns gait_parameter Used to select the thrid level of the", ") -> pd.DataFrame: anova_overview = pd.DataFrame() significant_results = {} for", "gait parameter. Parameters ---------- dataset A dictionary, where the keys", "Dict, gait_test: str, gait_parameter: str ) -> Tuple[pd.DataFrame, Set]: \"\"\"Calculat", "measurement.\"\"\" parameter = [column for column in data.columns if column", "[column for column in data.columns if column != \"configuration\"][0] data_", "select the first level of the columns gait_parameter Used to", "the DBS configureation, e.g. \"130\", \"100\", \"OFF\". The third level", "str, gait_parameter: str ) -> Tuple[pd.DataFrame, Set]: \"\"\"Calculat a one-way", "{} anova_df = pd.DataFrame() not_evaluated = [] for patient, patient_data", "\"030\", \"033\", \"040\", \"066\", \"085\", \"090\", \"100\", \"130\", \"OFF\", }", "\"\"\"Calculate one-way anova using each column as a different measurement.\"\"\"", "values that are above p_value_limit with `None`\"\"\" return ( df.loc(axis=1)[f\"p-value\"]", "configuration][parameter].T.to_numpy() for configuration in set(data[\"configuration\"]) ] return f_oneway(*data_) def anova(", "foot_data = patient_data[ (patient_data[\"foot\"] == foot) & (patient_data[\"test\"] == gait_test)", "return f_oneway(*data_) def anova( dataset: Dict, gait_test: str, gait_parameter: str", "= { \"030\", \"033\", \"040\", \"066\", \"085\", \"090\", \"100\", \"130\",", "replaces values that are above p_value_limit with `None`\"\"\" return (", "with `None`\"\"\" return ( df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"] < p_value_limit) .dropna(axis=0, how=\"all\")", "== configuration][parameter].T.to_numpy() for configuration in set(data[\"configuration\"]) ] return f_oneway(*data_) def", "to the two feet and the rows are different gait", "not_evaluated.append( \" \".join([gait_test, patient, *missing_configurations, foot]) ) if len(missing_configurations) >", "\"\"\"Return a df, which replaces values that are above p_value_limit", "(patient_data[\"foot\"] == foot) & (patient_data[\"test\"] == gait_test) ][[gait_parameter, \"configuration\"]] possible_configurations", "Parameters ---------- dataset A dictionary, where the keys are descriptions", "= [ data[data[\"configuration\"] == configuration][parameter].T.to_numpy() for configuration in set(data[\"configuration\"]) ]", "numpy as np import pandas as pd from scipy.stats import", "/ \"fast\". The second level describes the DBS configureation, e.g.", "2, [\"LeftFoot\", \"RightFoot\"]] ), data=[ [ anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1], ] ],", "anova_df, set(not_evaluated) def conclude_results( all_results: pd.DataFrame, p_value_limit: float ) ->", "float): \"\"\"Return a df, which replaces values that are above", "the OFF state for this specific `gait_test` \"\"\" anova_dict =", "anova_df = pd.concat([anova_df, row]) return anova_df, set(not_evaluated) def conclude_results( all_results:", "parameters. The values are anova p-values between all DBS configurations", "\"130\", \"OFF\", } actual_configurations = set(foot_data[\"configuration\"]) missing_configurations = possible_configurations -", "(len(possible_configurations) - 2): print( \"Not evaluating this foot, because to", "in dataset.items(): anova_dict[patient] = {\"LeftFoot\": (None, None), \"RightFoot\": (None, None)}", "set(foot_data_valid.columns)) anova_dict[patient][foot] = _calculate_anova(foot_data) row = pd.DataFrame( index=[patient], columns=pd.MultiIndex.from_arrays( [[\"p-value\"]", "`None`\"\"\" return ( df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"] < p_value_limit) .dropna(axis=0, how=\"all\") )", "gait_parameter Used to select the thrid level of the columns", "above p_value_limit with `None`\"\"\" return ( df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"] < p_value_limit)", "] ], ) anova_df = pd.concat([anova_df, row]) return anova_df, set(not_evaluated)", "& (patient_data[\"test\"] == gait_test) ][[gait_parameter, \"configuration\"]] possible_configurations = { \"030\",", "pd.DataFrame, p_value_limit: float): \"\"\"Return a df, which replaces values that", "{\"LeftFoot\": (None, None), \"RightFoot\": (None, None)} for foot in set(patient_data[\"foot\"]):", "argument `dataset`. The values are dataframes, where the columns correspond", "Used to select the first level of the columns gait_parameter", "= [\"n_patients\", \"n_patients_significant\", \"n_feet_significant\"] anova_overview = pd.concat( [ anova_overview, pd.DataFrame(data=[data],", "None foot_data = patient_data[ (patient_data[\"foot\"] == foot) & (patient_data[\"test\"] ==", "specific `gait_test` \"\"\" anova_dict = {} anova_df = pd.DataFrame() not_evaluated", "= pd.DataFrame( index=[patient], columns=pd.MultiIndex.from_arrays( [[\"p-value\"] * 2, [\"LeftFoot\", \"RightFoot\"]] ),", "columns. The first level describes the test paradigm, e.g. \"slow\"", "---------- dataset A dictionary, where the keys are descriptions for", "of the columns Returns ------- d A dictionary where the", "anova_df = pd.DataFrame() not_evaluated = [] for patient, patient_data in", "where the columns correspond to the two feet and the", "DBS configureation, e.g. \"130\", \"100\", \"OFF\". The third level is", "import f_oneway from typing import Dict, Tuple, Set def extract_significant_p(df:", "column as a different measurement.\"\"\" parameter = [column for column", "dictionary, where the keys are descriptions for different subjects. The", "= set(foot_data[\"configuration\"]) missing_configurations = possible_configurations - actual_configurations if missing_configurations: not_evaluated.append(", "different gait parameters. The values are anova p-values between all", "anova_dict[patient][foot] = _calculate_anova(foot_data) row = pd.DataFrame( index=[patient], columns=pd.MultiIndex.from_arrays( [[\"p-value\"] *", "\"n_patients_significant\", \"n_feet_significant\"] anova_overview = pd.concat( [ anova_overview, pd.DataFrame(data=[data], columns=columns, index=[gait_parameter]),", "{ \"030\", \"033\", \"040\", \"066\", \"085\", \"090\", \"100\", \"130\", \"OFF\",", "as pd from scipy.stats import f_oneway from typing import Dict,", "one-way anova using each column as a different measurement.\"\"\" parameter", "column in data.columns if column != \"configuration\"][0] data_ = [", "each column as a different measurement.\"\"\" parameter = [column for", ".where(df[f\"p-value\"] < p_value_limit) .dropna(axis=0, how=\"all\") ) def _calculate_anova(data: pd.DataFrame) ->", "set(not_evaluated) def conclude_results( all_results: pd.DataFrame, p_value_limit: float ) -> pd.DataFrame:", "a one-way anova for a single gait test and gait", "actual_configurations = set(foot_data[\"configuration\"]) missing_configurations = possible_configurations - actual_configurations if missing_configurations:", "in data.columns if column != \"configuration\"][0] data_ = [ data[data[\"configuration\"]", "a different measurement.\"\"\" parameter = [column for column in data.columns", "to select the first level of the columns gait_parameter Used", "the first level of the columns gait_parameter Used to select", "conclude_results( all_results: pd.DataFrame, p_value_limit: float ) -> pd.DataFrame: anova_overview =", "for column in data.columns if column != \"configuration\"][0] data_ =", "anova_overview = pd.DataFrame() significant_results = {} for gait_parameter in all_results.keys():", ") anova_df = pd.concat([anova_df, row]) return anova_df, set(not_evaluated) def conclude_results(", "first level describes the test paradigm, e.g. \"slow\" / \"fast\".", "in all_results.keys(): significant_results[gait_parameter] = extract_significant_p( all_results[gait_parameter], p_value_limit=p_value_limit ) data =", "= pd.concat([anova_df, row]) return anova_df, set(not_evaluated) def conclude_results( all_results: pd.DataFrame,", "_calculate_anova(data: pd.DataFrame) -> Tuple: \"\"\"Calculate one-way anova using each column", "select the thrid level of the columns Returns ------- d", "OFF state for this specific `gait_test` \"\"\" anova_dict = {}", "stride length. gait_test Used to select the first level of", "pd.DataFrame( index=[patient], columns=pd.MultiIndex.from_arrays( [[\"p-value\"] * 2, [\"LeftFoot\", \"RightFoot\"]] ), data=[", "row]) return anova_df, set(not_evaluated) def conclude_results( all_results: pd.DataFrame, p_value_limit: float", "and the OFF state for this specific `gait_test` \"\"\" anova_dict", "test paradigm, e.g. \"slow\" / \"fast\". The second level describes", "are equal to the passed argument `dataset`. The values are", "for patient, patient_data in dataset.items(): anova_dict[patient] = {\"LeftFoot\": (None, None),", "( df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"] < p_value_limit) .dropna(axis=0, how=\"all\") ) def _calculate_anova(data:", "= pd.concat( [ anova_overview, pd.DataFrame(data=[data], columns=columns, index=[gait_parameter]), ] ) return", "\" \".join([gait_test, patient, *missing_configurations, foot]) ) if len(missing_configurations) > (len(possible_configurations)", "the columns Returns ------- d A dictionary where the keys", "for different subjects. The values are dataframes, which have a", "where the keys are descriptions for different subjects. The values", "the two feet and the rows are different gait parameters.", "The second level describes the DBS configureation, e.g. \"130\", \"100\",", "None)} for foot in set(patient_data[\"foot\"]): missing_condition = None foot_data =", "anova_dict = {} anova_df = pd.DataFrame() not_evaluated = [] for", "first level of the columns gait_parameter Used to select the", "The values are dataframes, where the columns correspond to the", "foot in set(patient_data[\"foot\"]): missing_condition = None foot_data = patient_data[ (patient_data[\"foot\"]", ") if len(missing_configurations) > (len(possible_configurations) - 2): print( \"Not evaluating", "dataset.items(): anova_dict[patient] = {\"LeftFoot\": (None, None), \"RightFoot\": (None, None)} for", "-> Tuple: \"\"\"Calculate one-way anova using each column as a", "anova p-values between all DBS configurations and the OFF state", "# print(set(foot_data.columns) - set(foot_data_valid.columns)) anova_dict[patient][foot] = _calculate_anova(foot_data) row = pd.DataFrame(", "= possible_configurations - actual_configurations if missing_configurations: not_evaluated.append( \" \".join([gait_test, patient,", "(None, None), \"RightFoot\": (None, None)} for foot in set(patient_data[\"foot\"]): missing_condition", "state for this specific `gait_test` \"\"\" anova_dict = {} anova_df", "patient_data[ (patient_data[\"foot\"] == foot) & (patient_data[\"test\"] == gait_test) ][[gait_parameter, \"configuration\"]]", "are dataframes, where the columns correspond to the two feet", "len(all_results[gait_parameter]), len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(), ] columns = [\"n_patients\", \"n_patients_significant\", \"n_feet_significant\"] anova_overview", "print( \"Not evaluating this foot, because to few configurations available.\"", "because to few configurations available.\" ) continue # print(set(foot_data.columns) -", "significant_results = {} for gait_parameter in all_results.keys(): significant_results[gait_parameter] = extract_significant_p(", "= [column for column in data.columns if column != \"configuration\"][0]", "p_value_limit) .dropna(axis=0, how=\"all\") ) def _calculate_anova(data: pd.DataFrame) -> Tuple: \"\"\"Calculate", "as np import pandas as pd from scipy.stats import f_oneway", "def _calculate_anova(data: pd.DataFrame) -> Tuple: \"\"\"Calculate one-way anova using each", "Dict, Tuple, Set def extract_significant_p(df: pd.DataFrame, p_value_limit: float): \"\"\"Return a", "few configurations available.\" ) continue # print(set(foot_data.columns) - set(foot_data_valid.columns)) anova_dict[patient][foot]", "\"Not evaluating this foot, because to few configurations available.\" )", "f_oneway(*data_) def anova( dataset: Dict, gait_test: str, gait_parameter: str )", "anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1], ] ], ) anova_df = pd.concat([anova_df, row]) return", "} actual_configurations = set(foot_data[\"configuration\"]) missing_configurations = possible_configurations - actual_configurations if", "to select the thrid level of the columns Returns -------", "Set def extract_significant_p(df: pd.DataFrame, p_value_limit: float): \"\"\"Return a df, which", "feet and the rows are different gait parameters. The values", "continue # print(set(foot_data.columns) - set(foot_data_valid.columns)) anova_dict[patient][foot] = _calculate_anova(foot_data) row =", "gait parameter, e.g. stride length. gait_test Used to select the", "*missing_configurations, foot]) ) if len(missing_configurations) > (len(possible_configurations) - 2): print(", "a single gait test and gait parameter. Parameters ---------- dataset", "<reponame>dpedrosac/DBSgait<gh_stars>1-10 import numpy as np import pandas as pd from", "dataset: Dict, gait_test: str, gait_parameter: str ) -> Tuple[pd.DataFrame, Set]:", "values are dataframes, which have a pd.MultiIndex as columns. The", "\"OFF\", } actual_configurations = set(foot_data[\"configuration\"]) missing_configurations = possible_configurations - actual_configurations", "data.columns if column != \"configuration\"][0] data_ = [ data[data[\"configuration\"] ==", "2): print( \"Not evaluating this foot, because to few configurations", "import Dict, Tuple, Set def extract_significant_p(df: pd.DataFrame, p_value_limit: float): \"\"\"Return", "e.g. stride length. gait_test Used to select the first level", "- set(foot_data_valid.columns)) anova_dict[patient][foot] = _calculate_anova(foot_data) row = pd.DataFrame( index=[patient], columns=pd.MultiIndex.from_arrays(", "pd.DataFrame() significant_results = {} for gait_parameter in all_results.keys(): significant_results[gait_parameter] =", "subjects. The values are dataframes, which have a pd.MultiIndex as", "pd.MultiIndex as columns. The first level describes the test paradigm,", "p-values between all DBS configurations and the OFF state for", "describes the test paradigm, e.g. \"slow\" / \"fast\". The second", "\".join([gait_test, patient, *missing_configurations, foot]) ) if len(missing_configurations) > (len(possible_configurations) -", "The values are dataframes, which have a pd.MultiIndex as columns.", ") -> Tuple[pd.DataFrame, Set]: \"\"\"Calculat a one-way anova for a", "how=\"all\") ) def _calculate_anova(data: pd.DataFrame) -> Tuple: \"\"\"Calculate one-way anova", "a pd.MultiIndex as columns. The first level describes the test", "< p_value_limit) .dropna(axis=0, how=\"all\") ) def _calculate_anova(data: pd.DataFrame) -> Tuple:", "gait_test: str, gait_parameter: str ) -> Tuple[pd.DataFrame, Set]: \"\"\"Calculat a", "> (len(possible_configurations) - 2): print( \"Not evaluating this foot, because", "[ anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1], ] ], ) anova_df = pd.concat([anova_df, row])", "for a single gait test and gait parameter. Parameters ----------", "test and gait parameter. Parameters ---------- dataset A dictionary, where", "A dictionary where the keys are equal to the passed", "one-way anova for a single gait test and gait parameter.", "Tuple: \"\"\"Calculate one-way anova using each column as a different", "def conclude_results( all_results: pd.DataFrame, p_value_limit: float ) -> pd.DataFrame: anova_overview", "configurations and the OFF state for this specific `gait_test` \"\"\"", "\"040\", \"066\", \"085\", \"090\", \"100\", \"130\", \"OFF\", } actual_configurations =", "!= \"configuration\"][0] data_ = [ data[data[\"configuration\"] == configuration][parameter].T.to_numpy() for configuration", "-> Tuple[pd.DataFrame, Set]: \"\"\"Calculat a one-way anova for a single", "d A dictionary where the keys are equal to the", "Tuple[pd.DataFrame, Set]: \"\"\"Calculat a one-way anova for a single gait", "if len(missing_configurations) > (len(possible_configurations) - 2): print( \"Not evaluating this", "The values are anova p-values between all DBS configurations and", "= pd.DataFrame() not_evaluated = [] for patient, patient_data in dataset.items():", "two feet and the rows are different gait parameters. The", "The first level describes the test paradigm, e.g. \"slow\" /", "p_value_limit with `None`\"\"\" return ( df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"] < p_value_limit) .dropna(axis=0,", "pd.DataFrame, p_value_limit: float ) -> pd.DataFrame: anova_overview = pd.DataFrame() significant_results", "in set(patient_data[\"foot\"]): missing_condition = None foot_data = patient_data[ (patient_data[\"foot\"] ==", "missing_condition = None foot_data = patient_data[ (patient_data[\"foot\"] == foot) &", "dataframes, where the columns correspond to the two feet and", "are dataframes, which have a pd.MultiIndex as columns. The first", "p_value_limit: float ) -> pd.DataFrame: anova_overview = pd.DataFrame() significant_results =", "the gait parameter, e.g. stride length. gait_test Used to select", "_calculate_anova(foot_data) row = pd.DataFrame( index=[patient], columns=pd.MultiIndex.from_arrays( [[\"p-value\"] * 2, [\"LeftFoot\",", "all_results[gait_parameter], p_value_limit=p_value_limit ) data = [ len(all_results[gait_parameter]), len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(), ]", "pandas as pd from scipy.stats import f_oneway from typing import", "column != \"configuration\"][0] data_ = [ data[data[\"configuration\"] == configuration][parameter].T.to_numpy() for", "patient_data in dataset.items(): anova_dict[patient] = {\"LeftFoot\": (None, None), \"RightFoot\": (None,", "configureation, e.g. \"130\", \"100\", \"OFF\". The third level is the", "gait test and gait parameter. Parameters ---------- dataset A dictionary,", "extract_significant_p( all_results[gait_parameter], p_value_limit=p_value_limit ) data = [ len(all_results[gait_parameter]), len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(),", "different measurement.\"\"\" parameter = [column for column in data.columns if", "anova( dataset: Dict, gait_test: str, gait_parameter: str ) -> Tuple[pd.DataFrame,", "the thrid level of the columns Returns ------- d A", "if missing_configurations: not_evaluated.append( \" \".join([gait_test, patient, *missing_configurations, foot]) ) if", "anova_overview = pd.concat( [ anova_overview, pd.DataFrame(data=[data], columns=columns, index=[gait_parameter]), ] )", "anova_dict[patient] = {\"LeftFoot\": (None, None), \"RightFoot\": (None, None)} for foot", "all_results.keys(): significant_results[gait_parameter] = extract_significant_p( all_results[gait_parameter], p_value_limit=p_value_limit ) data = [", "{} for gait_parameter in all_results.keys(): significant_results[gait_parameter] = extract_significant_p( all_results[gait_parameter], p_value_limit=p_value_limit", "\"066\", \"085\", \"090\", \"100\", \"130\", \"OFF\", } actual_configurations = set(foot_data[\"configuration\"])", "patient, patient_data in dataset.items(): anova_dict[patient] = {\"LeftFoot\": (None, None), \"RightFoot\":", "\"fast\". The second level describes the DBS configureation, e.g. \"130\",", "level is the gait parameter, e.g. stride length. gait_test Used", "\"130\", \"100\", \"OFF\". The third level is the gait parameter,", "gait parameters. The values are anova p-values between all DBS", "\"RightFoot\": (None, None)} for foot in set(patient_data[\"foot\"]): missing_condition = None", "have a pd.MultiIndex as columns. The first level describes the", "\"085\", \"090\", \"100\", \"130\", \"OFF\", } actual_configurations = set(foot_data[\"configuration\"]) missing_configurations", "= [ len(all_results[gait_parameter]), len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(), ] columns = [\"n_patients\", \"n_patients_significant\",", "is the gait parameter, e.g. stride length. gait_test Used to", "foot]) ) if len(missing_configurations) > (len(possible_configurations) - 2): print( \"Not", "this foot, because to few configurations available.\" ) continue #", "gait_test Used to select the first level of the columns", "possible_configurations - actual_configurations if missing_configurations: not_evaluated.append( \" \".join([gait_test, patient, *missing_configurations,", "------- d A dictionary where the keys are equal to", "the keys are descriptions for different subjects. The values are", "df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"] < p_value_limit) .dropna(axis=0, how=\"all\") ) def _calculate_anova(data: pd.DataFrame)", "keys are descriptions for different subjects. The values are dataframes,", "are different gait parameters. The values are anova p-values between", "print(set(foot_data.columns) - set(foot_data_valid.columns)) anova_dict[patient][foot] = _calculate_anova(foot_data) row = pd.DataFrame( index=[patient],", "as columns. The first level describes the test paradigm, e.g.", "the columns correspond to the two feet and the rows", "scipy.stats import f_oneway from typing import Dict, Tuple, Set def", "pd.DataFrame) -> Tuple: \"\"\"Calculate one-way anova using each column as", "The third level is the gait parameter, e.g. stride length.", "the columns gait_parameter Used to select the thrid level of", "single gait test and gait parameter. Parameters ---------- dataset A", "which replaces values that are above p_value_limit with `None`\"\"\" return", "parameter. Parameters ---------- dataset A dictionary, where the keys are", "data_ = [ data[data[\"configuration\"] == configuration][parameter].T.to_numpy() for configuration in set(data[\"configuration\"])", ") continue # print(set(foot_data.columns) - set(foot_data_valid.columns)) anova_dict[patient][foot] = _calculate_anova(foot_data) row", "are anova p-values between all DBS configurations and the OFF", "] return f_oneway(*data_) def anova( dataset: Dict, gait_test: str, gait_parameter:", "describes the DBS configureation, e.g. \"130\", \"100\", \"OFF\". The third", "\"100\", \"130\", \"OFF\", } actual_configurations = set(foot_data[\"configuration\"]) missing_configurations = possible_configurations", "different subjects. The values are dataframes, which have a pd.MultiIndex", "= None foot_data = patient_data[ (patient_data[\"foot\"] == foot) & (patient_data[\"test\"]", "evaluating this foot, because to few configurations available.\" ) continue", "-> pd.DataFrame: anova_overview = pd.DataFrame() significant_results = {} for gait_parameter", "level of the columns Returns ------- d A dictionary where", "row = pd.DataFrame( index=[patient], columns=pd.MultiIndex.from_arrays( [[\"p-value\"] * 2, [\"LeftFoot\", \"RightFoot\"]]", "level describes the DBS configureation, e.g. \"130\", \"100\", \"OFF\". The", "extract_significant_p(df: pd.DataFrame, p_value_limit: float): \"\"\"Return a df, which replaces values", "\"RightFoot\"]] ), data=[ [ anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1], ] ], ) anova_df", "for configuration in set(data[\"configuration\"]) ] return f_oneway(*data_) def anova( dataset:", "as a different measurement.\"\"\" parameter = [column for column in", "p_value_limit=p_value_limit ) data = [ len(all_results[gait_parameter]), len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(), ] columns", "available.\" ) continue # print(set(foot_data.columns) - set(foot_data_valid.columns)) anova_dict[patient][foot] = _calculate_anova(foot_data)", "from scipy.stats import f_oneway from typing import Dict, Tuple, Set", "dictionary where the keys are equal to the passed argument", "length. gait_test Used to select the first level of the", "actual_configurations if missing_configurations: not_evaluated.append( \" \".join([gait_test, patient, *missing_configurations, foot]) )", "typing import Dict, Tuple, Set def extract_significant_p(df: pd.DataFrame, p_value_limit: float):", "this specific `gait_test` \"\"\" anova_dict = {} anova_df = pd.DataFrame()", "index=[patient], columns=pd.MultiIndex.from_arrays( [[\"p-value\"] * 2, [\"LeftFoot\", \"RightFoot\"]] ), data=[ [", "\"100\", \"OFF\". The third level is the gait parameter, e.g.", "are above p_value_limit with `None`\"\"\" return ( df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"] <", "second level describes the DBS configureation, e.g. \"130\", \"100\", \"OFF\".", "correspond to the two feet and the rows are different", "Used to select the thrid level of the columns Returns", "level of the columns gait_parameter Used to select the thrid", "= [] for patient, patient_data in dataset.items(): anova_dict[patient] = {\"LeftFoot\":", "- 2): print( \"Not evaluating this foot, because to few", "[[\"p-value\"] * 2, [\"LeftFoot\", \"RightFoot\"]] ), data=[ [ anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1],", "= extract_significant_p( all_results[gait_parameter], p_value_limit=p_value_limit ) data = [ len(all_results[gait_parameter]), len(significant_results[gait_parameter]),", "][[gait_parameter, \"configuration\"]] possible_configurations = { \"030\", \"033\", \"040\", \"066\", \"085\",", "None), \"RightFoot\": (None, None)} for foot in set(patient_data[\"foot\"]): missing_condition =", "e.g. \"130\", \"100\", \"OFF\". The third level is the gait", "descriptions for different subjects. The values are dataframes, which have", "df, which replaces values that are above p_value_limit with `None`\"\"\"", "in set(data[\"configuration\"]) ] return f_oneway(*data_) def anova( dataset: Dict, gait_test:", "parameter, e.g. stride length. gait_test Used to select the first", "import pandas as pd from scipy.stats import f_oneway from typing", "keys are equal to the passed argument `dataset`. The values", "to the passed argument `dataset`. The values are dataframes, where", "= _calculate_anova(foot_data) row = pd.DataFrame( index=[patient], columns=pd.MultiIndex.from_arrays( [[\"p-value\"] * 2,", "pd.concat([anova_df, row]) return anova_df, set(not_evaluated) def conclude_results( all_results: pd.DataFrame, p_value_limit:", "if column != \"configuration\"][0] data_ = [ data[data[\"configuration\"] == configuration][parameter].T.to_numpy()", "and the rows are different gait parameters. The values are", "[\"LeftFoot\", \"RightFoot\"]] ), data=[ [ anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1], ] ], )", "DBS configurations and the OFF state for this specific `gait_test`", "the passed argument `dataset`. The values are dataframes, where the", "gait_parameter: str ) -> Tuple[pd.DataFrame, Set]: \"\"\"Calculat a one-way anova", "between all DBS configurations and the OFF state for this", "Tuple, Set def extract_significant_p(df: pd.DataFrame, p_value_limit: float): \"\"\"Return a df,", "patient, *missing_configurations, foot]) ) if len(missing_configurations) > (len(possible_configurations) - 2):", "significant_results[gait_parameter] = extract_significant_p( all_results[gait_parameter], p_value_limit=p_value_limit ) data = [ len(all_results[gait_parameter]),", "[\"n_patients\", \"n_patients_significant\", \"n_feet_significant\"] anova_overview = pd.concat( [ anova_overview, pd.DataFrame(data=[data], columns=columns,", "the test paradigm, e.g. \"slow\" / \"fast\". The second level", "foot) & (patient_data[\"test\"] == gait_test) ][[gait_parameter, \"configuration\"]] possible_configurations = {", "columns = [\"n_patients\", \"n_patients_significant\", \"n_feet_significant\"] anova_overview = pd.concat( [ anova_overview,", "== gait_test) ][[gait_parameter, \"configuration\"]] possible_configurations = { \"030\", \"033\", \"040\",", "configuration in set(data[\"configuration\"]) ] return f_oneway(*data_) def anova( dataset: Dict,", "], ) anova_df = pd.concat([anova_df, row]) return anova_df, set(not_evaluated) def", "that are above p_value_limit with `None`\"\"\" return ( df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"]", "using each column as a different measurement.\"\"\" parameter = [column", "return anova_df, set(not_evaluated) def conclude_results( all_results: pd.DataFrame, p_value_limit: float )", "- actual_configurations if missing_configurations: not_evaluated.append( \" \".join([gait_test, patient, *missing_configurations, foot])", "set(foot_data[\"configuration\"]) missing_configurations = possible_configurations - actual_configurations if missing_configurations: not_evaluated.append( \"", "are descriptions for different subjects. The values are dataframes, which", "import numpy as np import pandas as pd from scipy.stats", "\"033\", \"040\", \"066\", \"085\", \"090\", \"100\", \"130\", \"OFF\", } actual_configurations", "of the columns gait_parameter Used to select the thrid level", "values are dataframes, where the columns correspond to the two", "third level is the gait parameter, e.g. stride length. gait_test", "columns=pd.MultiIndex.from_arrays( [[\"p-value\"] * 2, [\"LeftFoot\", \"RightFoot\"]] ), data=[ [ anova_dict[patient][\"LeftFoot\"][1],", "return ( df.loc(axis=1)[f\"p-value\"] .where(df[f\"p-value\"] < p_value_limit) .dropna(axis=0, how=\"all\") ) def", "pd.concat( [ anova_overview, pd.DataFrame(data=[data], columns=columns, index=[gait_parameter]), ] ) return anova_overview", "paradigm, e.g. \"slow\" / \"fast\". The second level describes the", "set(data[\"configuration\"]) ] return f_oneway(*data_) def anova( dataset: Dict, gait_test: str,", "pd.DataFrame() not_evaluated = [] for patient, patient_data in dataset.items(): anova_dict[patient]", "\"\"\" anova_dict = {} anova_df = pd.DataFrame() not_evaluated = []", "] columns = [\"n_patients\", \"n_patients_significant\", \"n_feet_significant\"] anova_overview = pd.concat( [", "pd.DataFrame: anova_overview = pd.DataFrame() significant_results = {} for gait_parameter in", "str ) -> Tuple[pd.DataFrame, Set]: \"\"\"Calculat a one-way anova for", "data[data[\"configuration\"] == configuration][parameter].T.to_numpy() for configuration in set(data[\"configuration\"]) ] return f_oneway(*data_)", "all_results: pd.DataFrame, p_value_limit: float ) -> pd.DataFrame: anova_overview = pd.DataFrame()", "for gait_parameter in all_results.keys(): significant_results[gait_parameter] = extract_significant_p( all_results[gait_parameter], p_value_limit=p_value_limit )", "which have a pd.MultiIndex as columns. The first level describes", "parameter = [column for column in data.columns if column !=", "and gait parameter. Parameters ---------- dataset A dictionary, where the", "\"\"\"Calculat a one-way anova for a single gait test and", "p_value_limit: float): \"\"\"Return a df, which replaces values that are", "a df, which replaces values that are above p_value_limit with", "\"090\", \"100\", \"130\", \"OFF\", } actual_configurations = set(foot_data[\"configuration\"]) missing_configurations =", "configurations available.\" ) continue # print(set(foot_data.columns) - set(foot_data_valid.columns)) anova_dict[patient][foot] =", "from typing import Dict, Tuple, Set def extract_significant_p(df: pd.DataFrame, p_value_limit:", "to few configurations available.\" ) continue # print(set(foot_data.columns) - set(foot_data_valid.columns))", "all DBS configurations and the OFF state for this specific", "= pd.DataFrame() significant_results = {} for gait_parameter in all_results.keys(): significant_results[gait_parameter]", "where the keys are equal to the passed argument `dataset`.", "A dictionary, where the keys are descriptions for different subjects.", "(patient_data[\"test\"] == gait_test) ][[gait_parameter, \"configuration\"]] possible_configurations = { \"030\", \"033\",", "f_oneway from typing import Dict, Tuple, Set def extract_significant_p(df: pd.DataFrame,", "foot, because to few configurations available.\" ) continue # print(set(foot_data.columns)", "def anova( dataset: Dict, gait_test: str, gait_parameter: str ) ->", "e.g. \"slow\" / \"fast\". The second level describes the DBS", "values are anova p-values between all DBS configurations and the", "data = [ len(all_results[gait_parameter]), len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(), ] columns = [\"n_patients\",", "\"OFF\". The third level is the gait parameter, e.g. stride", "rows are different gait parameters. The values are anova p-values", "def extract_significant_p(df: pd.DataFrame, p_value_limit: float): \"\"\"Return a df, which replaces", "= {} for gait_parameter in all_results.keys(): significant_results[gait_parameter] = extract_significant_p( all_results[gait_parameter],", "\"n_feet_significant\"] anova_overview = pd.concat( [ anova_overview, pd.DataFrame(data=[data], columns=columns, index=[gait_parameter]), ]", "`gait_test` \"\"\" anova_dict = {} anova_df = pd.DataFrame() not_evaluated =", "[ data[data[\"configuration\"] == configuration][parameter].T.to_numpy() for configuration in set(data[\"configuration\"]) ] return", "level describes the test paradigm, e.g. \"slow\" / \"fast\". The", "for foot in set(patient_data[\"foot\"]): missing_condition = None foot_data = patient_data[", ") data = [ len(all_results[gait_parameter]), len(significant_results[gait_parameter]), significant_results[gait_parameter].count().sum(), ] columns =", "not_evaluated = [] for patient, patient_data in dataset.items(): anova_dict[patient] =", "columns Returns ------- d A dictionary where the keys are", "anova for a single gait test and gait parameter. Parameters", "gait_parameter in all_results.keys(): significant_results[gait_parameter] = extract_significant_p( all_results[gait_parameter], p_value_limit=p_value_limit ) data", "= {} anova_df = pd.DataFrame() not_evaluated = [] for patient,", "dataframes, which have a pd.MultiIndex as columns. The first level", "the rows are different gait parameters. The values are anova", "the keys are equal to the passed argument `dataset`. The", "), data=[ [ anova_dict[patient][\"LeftFoot\"][1], anova_dict[patient][\"RightFoot\"][1], ] ], ) anova_df =", "Set]: \"\"\"Calculat a one-way anova for a single gait test", "thrid level of the columns Returns ------- d A dictionary", "equal to the passed argument `dataset`. The values are dataframes,", "passed argument `dataset`. The values are dataframes, where the columns", "np import pandas as pd from scipy.stats import f_oneway from" ]
[ "coordinates for the Tk root window x = (ws/2) -", "= cv2.VideoCapture(dev_port) if not camera.isOpened(): non_working_ports.append(dev_port) # print(\"Port %s is", "# print(\"Port %s for camera ( %s x %s) is", "( %s x %s) is present but does not reads.\"", "the testing. camera = cv2.VideoCapture(dev_port) if not camera.isOpened(): non_working_ports.append(dev_port) #", "is_raspberrypi(): try: with io.open('/sys/firmware/devicetree/base/model', 'r') as m: if 'raspberry pi'", "x %s) is present but does not reads.\" %(dev_port,h,w)) available_ports.append(dev_port)", "\"\"\" Test the ports and returns a tuple with the", "(hs/2) - (h/2) return(w,h,x,y) def handle_focus_in(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black') def", "if message == \"\": return else: button.configure(text=message) def list_ports(): \"\"\"", "%s is not working.\" %dev_port) else: is_reading, img = camera.read()", "camera.get(4) if is_reading: # print(\"Port %s is working and reads", "images (%s x %s)\" %(dev_port,h,w)) working_ports.append(dev_port) else: # print(\"Port %s", "Exception: pass return False def get_platform(): return platform.system() def get_gui_coordinates(root,", "\"\"\" non_working_ports = [] dev_port = 0 working_ports = []", "< 6: # if there are more than 5 non", "as m: if 'raspberry pi' in m.read().lower(): return(m) except Exception:", "return False def get_platform(): return platform.system() def get_gui_coordinates(root, w, h):", "ws = root.winfo_screenwidth() # width of the screen hs =", "from tkinter.filedialog import askdirectory from serial.tools import list_ports # From", "are working. \"\"\" non_working_ports = [] dev_port = 0 working_ports", "print(\"Port %s is not working.\" %dev_port) else: is_reading, img =", "import askdirectory from serial.tools import list_ports # From https://raspberrypi.stackexchange.com/a/118473 def", "with the available ports and the ones that are working.", "ports stop the testing. camera = cv2.VideoCapture(dev_port) if not camera.isOpened():", "for the Tk root window x = (ws/2) - (w/2)", "io.open('/sys/firmware/devicetree/base/model', 'r') as m: if 'raspberry pi' in m.read().lower(): return(m)", "the screen hs = root.winfo_screenheight() # height of the screen", "of the screen # calculate x and y coordinates for", "of the screen hs = root.winfo_screenheight() # height of the", "camera.read() w = camera.get(3) h = camera.get(4) if is_reading: #", "# From https://raspberrypi.stackexchange.com/a/118473 def is_raspberrypi(): try: with io.open('/sys/firmware/devicetree/base/model', 'r') as", "root window x = (ws/2) - (w/2) y = (hs/2)", "# get screen width and height ws = root.winfo_screenwidth() #", "\"\": return else: button.configure(text=message) def list_ports(): \"\"\" Test the ports", "w, h): # get screen width and height ws =", "not camera.isOpened(): non_working_ports.append(dev_port) # print(\"Port %s is not working.\" %dev_port)", "non_working_ports.append(dev_port) # print(\"Port %s is not working.\" %dev_port) else: is_reading,", "present but does not reads.\" %(dev_port,h,w)) available_ports.append(dev_port) dev_port +=1 return", "Tk root window x = (ws/2) - (w/2) y =", "import serial import cv2 import tkinter as tk from tkinter.filedialog", "camera.isOpened(): non_working_ports.append(dev_port) # print(\"Port %s is not working.\" %dev_port) else:", "== \"\": return else: button.configure(text=message) def list_ports(): \"\"\" Test the", "for camera ( %s x %s) is present but does", "else: is_reading, img = camera.read() w = camera.get(3) h =", "# calculate x and y coordinates for the Tk root", "more than 5 non working ports stop the testing. camera", "# print(\"Port %s is not working.\" %dev_port) else: is_reading, img", "try: with io.open('/sys/firmware/devicetree/base/model', 'r') as m: if 'raspberry pi' in", "%(dev_port,h,w)) working_ports.append(dev_port) else: # print(\"Port %s for camera ( %s", "(ws/2) - (w/2) y = (hs/2) - (h/2) return(w,h,x,y) def", "if is_reading: # print(\"Port %s is working and reads images", "the available ports and the ones that are working. \"\"\"", "askdirectory from serial.tools import list_ports # From https://raspberrypi.stackexchange.com/a/118473 def is_raspberrypi():", "except Exception: pass return False def get_platform(): return platform.system() def", "full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black') def handle_focus_out(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0, \"Example:", "ports and the ones that are working. \"\"\" non_working_ports =", "is_reading: # print(\"Port %s is working and reads images (%s", "# width of the screen hs = root.winfo_screenheight() # height", "import os import platform import time import csv import serial", "if there are more than 5 non working ports stop", "x and y coordinates for the Tk root window x", "def list_ports(): \"\"\" Test the ports and returns a tuple", "the ports and returns a tuple with the available ports", "and the ones that are working. \"\"\" non_working_ports = []", "calculate x and y coordinates for the Tk root window", "working ports stop the testing. camera = cv2.VideoCapture(dev_port) if not", "platform.system() def get_gui_coordinates(root, w, h): # get screen width and", "import list_ports # From https://raspberrypi.stackexchange.com/a/118473 def is_raspberrypi(): try: with io.open('/sys/firmware/devicetree/base/model',", "# height of the screen # calculate x and y", "full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0, \"Example: <NAME>\") def hover(button, enter, message):", "working.\" %dev_port) else: is_reading, img = camera.read() w = camera.get(3)", "y = (hs/2) - (h/2) return(w,h,x,y) def handle_focus_in(button): full_name_entry.delete(0, tk.END)", "hs = root.winfo_screenheight() # height of the screen # calculate", "working_ports = [] available_ports = [] while len(non_working_ports) < 6:", "if not camera.isOpened(): non_working_ports.append(dev_port) # print(\"Port %s is not working.\"", "screen # calculate x and y coordinates for the Tk", "print(\"Port %s is working and reads images (%s x %s)\"", "return(m) except Exception: pass return False def get_platform(): return platform.system()", "handle_focus_in(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black') def handle_focus_out(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0,", "w = camera.get(3) h = camera.get(4) if is_reading: # print(\"Port", "(%s x %s)\" %(dev_port,h,w)) working_ports.append(dev_port) else: # print(\"Port %s for", "pi' in m.read().lower(): return(m) except Exception: pass return False def", "serial import cv2 import tkinter as tk from tkinter.filedialog import", "tkinter.filedialog import askdirectory from serial.tools import list_ports # From https://raspberrypi.stackexchange.com/a/118473", "than 5 non working ports stop the testing. camera =", "import platform import time import csv import serial import cv2", "= [] dev_port = 0 working_ports = [] available_ports =", "is working and reads images (%s x %s)\" %(dev_port,h,w)) working_ports.append(dev_port)", "message): if message == \"\": return else: button.configure(text=message) def list_ports():", "# if there are more than 5 non working ports", "screen hs = root.winfo_screenheight() # height of the screen #", "with io.open('/sys/firmware/devicetree/base/model', 'r') as m: if 'raspberry pi' in m.read().lower():", "width and height ws = root.winfo_screenwidth() # width of the", "def get_platform(): return platform.system() def get_gui_coordinates(root, w, h): # get", "%s)\" %(dev_port,h,w)) working_ports.append(dev_port) else: # print(\"Port %s for camera (", "%dev_port) else: is_reading, img = camera.read() w = camera.get(3) h", "the Tk root window x = (ws/2) - (w/2) y", "full_name_entry.config(fg='black') def handle_focus_out(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0, \"Example: <NAME>\") def", "while len(non_working_ports) < 6: # if there are more than", "x = (ws/2) - (w/2) y = (hs/2) - (h/2)", "and reads images (%s x %s)\" %(dev_port,h,w)) working_ports.append(dev_port) else: #", "camera = cv2.VideoCapture(dev_port) if not camera.isOpened(): non_working_ports.append(dev_port) # print(\"Port %s", "button.configure(text=message) def list_ports(): \"\"\" Test the ports and returns a", "available_ports = [] while len(non_working_ports) < 6: # if there", "(w/2) y = (hs/2) - (h/2) return(w,h,x,y) def handle_focus_in(button): full_name_entry.delete(0,", "- (w/2) y = (hs/2) - (h/2) return(w,h,x,y) def handle_focus_in(button):", "screen width and height ws = root.winfo_screenwidth() # width of", "tk from tkinter.filedialog import askdirectory from serial.tools import list_ports #", "and returns a tuple with the available ports and the", "get_platform(): return platform.system() def get_gui_coordinates(root, w, h): # get screen", "is not working.\" %dev_port) else: is_reading, img = camera.read() w", "reads images (%s x %s)\" %(dev_port,h,w)) working_ports.append(dev_port) else: # print(\"Port", "tkinter as tk from tkinter.filedialog import askdirectory from serial.tools import", "y coordinates for the Tk root window x = (ws/2)", "message == \"\": return else: button.configure(text=message) def list_ports(): \"\"\" Test", "non working ports stop the testing. camera = cv2.VideoCapture(dev_port) if", "= camera.get(4) if is_reading: # print(\"Port %s is working and", "def handle_focus_out(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0, \"Example: <NAME>\") def hover(button,", "h): # get screen width and height ws = root.winfo_screenwidth()", "camera ( %s x %s) is present but does not", "= camera.get(3) h = camera.get(4) if is_reading: # print(\"Port %s", "m.read().lower(): return(m) except Exception: pass return False def get_platform(): return", "import csv import serial import cv2 import tkinter as tk", "%s is working and reads images (%s x %s)\" %(dev_port,h,w))", "returns a tuple with the available ports and the ones", "return(w,h,x,y) def handle_focus_in(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black') def handle_focus_out(button): full_name_entry.delete(0, tk.END)", "len(non_working_ports) < 6: # if there are more than 5", "(h/2) return(w,h,x,y) def handle_focus_in(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black') def handle_focus_out(button): full_name_entry.delete(0,", "tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0, \"Example: <NAME>\") def hover(button, enter, message): if", "# print(\"Port %s is working and reads images (%s x", "def is_raspberrypi(): try: with io.open('/sys/firmware/devicetree/base/model', 'r') as m: if 'raspberry", "Test the ports and returns a tuple with the available", "is present but does not reads.\" %(dev_port,h,w)) available_ports.append(dev_port) dev_port +=1", "hover(button, enter, message): if message == \"\": return else: button.configure(text=message)", "- (h/2) return(w,h,x,y) def handle_focus_in(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black') def handle_focus_out(button):", "0 working_ports = [] available_ports = [] while len(non_working_ports) <", "import cv2 import tkinter as tk from tkinter.filedialog import askdirectory", "[] available_ports = [] while len(non_working_ports) < 6: # if", "window x = (ws/2) - (w/2) y = (hs/2) -", "[] while len(non_working_ports) < 6: # if there are more", "<NAME>\") def hover(button, enter, message): if message == \"\": return", "def get_gui_coordinates(root, w, h): # get screen width and height", "= (ws/2) - (w/2) y = (hs/2) - (h/2) return(w,h,x,y)", "def hover(button, enter, message): if message == \"\": return else:", "return platform.system() def get_gui_coordinates(root, w, h): # get screen width", "6: # if there are more than 5 non working", "= [] while len(non_working_ports) < 6: # if there are", "csv import serial import cv2 import tkinter as tk from", "False def get_platform(): return platform.system() def get_gui_coordinates(root, w, h): #", "'raspberry pi' in m.read().lower(): return(m) except Exception: pass return False", "ones that are working. \"\"\" non_working_ports = [] dev_port =", "import tkinter as tk from tkinter.filedialog import askdirectory from serial.tools", "stop the testing. camera = cv2.VideoCapture(dev_port) if not camera.isOpened(): non_working_ports.append(dev_port)", "height of the screen # calculate x and y coordinates", "cv2.VideoCapture(dev_port) if not camera.isOpened(): non_working_ports.append(dev_port) # print(\"Port %s is not", "print(\"Port %s for camera ( %s x %s) is present", "import time import csv import serial import cv2 import tkinter", "cv2 import tkinter as tk from tkinter.filedialog import askdirectory from", "if 'raspberry pi' in m.read().lower(): return(m) except Exception: pass return", "https://raspberrypi.stackexchange.com/a/118473 def is_raspberrypi(): try: with io.open('/sys/firmware/devicetree/base/model', 'r') as m: if", "'r') as m: if 'raspberry pi' in m.read().lower(): return(m) except", "= root.winfo_screenheight() # height of the screen # calculate x", "non_working_ports = [] dev_port = 0 working_ports = [] available_ports", "is_reading, img = camera.read() w = camera.get(3) h = camera.get(4)", "else: button.configure(text=message) def list_ports(): \"\"\" Test the ports and returns", "h = camera.get(4) if is_reading: # print(\"Port %s is working", "root.winfo_screenheight() # height of the screen # calculate x and", "else: # print(\"Port %s for camera ( %s x %s)", "img = camera.read() w = camera.get(3) h = camera.get(4) if", "available ports and the ones that are working. \"\"\" non_working_ports", "working_ports.append(dev_port) else: # print(\"Port %s for camera ( %s x", "enter, message): if message == \"\": return else: button.configure(text=message) def", "= 0 working_ports = [] available_ports = [] while len(non_working_ports)", "list_ports(): \"\"\" Test the ports and returns a tuple with", "testing. camera = cv2.VideoCapture(dev_port) if not camera.isOpened(): non_working_ports.append(dev_port) # print(\"Port", "working and reads images (%s x %s)\" %(dev_port,h,w)) working_ports.append(dev_port) else:", "\"Example: <NAME>\") def hover(button, enter, message): if message == \"\":", "and y coordinates for the Tk root window x =", "dev_port = 0 working_ports = [] available_ports = [] while", "there are more than 5 non working ports stop the", "%s for camera ( %s x %s) is present but", "get_gui_coordinates(root, w, h): # get screen width and height ws", "os import platform import time import csv import serial import", "m: if 'raspberry pi' in m.read().lower(): return(m) except Exception: pass", "serial.tools import list_ports # From https://raspberrypi.stackexchange.com/a/118473 def is_raspberrypi(): try: with", "full_name_entry.config(fg='grey') full_name_entry.insert(0, \"Example: <NAME>\") def hover(button, enter, message): if message", "that are working. \"\"\" non_working_ports = [] dev_port = 0", "From https://raspberrypi.stackexchange.com/a/118473 def is_raspberrypi(): try: with io.open('/sys/firmware/devicetree/base/model', 'r') as m:", "x %s)\" %(dev_port,h,w)) working_ports.append(dev_port) else: # print(\"Port %s for camera", "<gh_stars>0 import os import platform import time import csv import", "%s) is present but does not reads.\" %(dev_port,h,w)) available_ports.append(dev_port) dev_port", "from serial.tools import list_ports # From https://raspberrypi.stackexchange.com/a/118473 def is_raspberrypi(): try:", "full_name_entry.insert(0, \"Example: <NAME>\") def hover(button, enter, message): if message ==", "5 non working ports stop the testing. camera = cv2.VideoCapture(dev_port)", "platform import time import csv import serial import cv2 import", "and height ws = root.winfo_screenwidth() # width of the screen", "as tk from tkinter.filedialog import askdirectory from serial.tools import list_ports", "not working.\" %dev_port) else: is_reading, img = camera.read() w =", "list_ports # From https://raspberrypi.stackexchange.com/a/118473 def is_raspberrypi(): try: with io.open('/sys/firmware/devicetree/base/model', 'r')", "the screen # calculate x and y coordinates for the", "def handle_focus_in(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black') def handle_focus_out(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey')", "height ws = root.winfo_screenwidth() # width of the screen hs", "tk.END) full_name_entry.config(fg='black') def handle_focus_out(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0, \"Example: <NAME>\")", "a tuple with the available ports and the ones that", "= [] available_ports = [] while len(non_working_ports) < 6: #", "are more than 5 non working ports stop the testing.", "%s x %s) is present but does not reads.\" %(dev_port,h,w))", "get screen width and height ws = root.winfo_screenwidth() # width", "the ones that are working. \"\"\" non_working_ports = [] dev_port", "in m.read().lower(): return(m) except Exception: pass return False def get_platform():", "camera.get(3) h = camera.get(4) if is_reading: # print(\"Port %s is", "but does not reads.\" %(dev_port,h,w)) available_ports.append(dev_port) dev_port +=1 return available_ports,working_ports,non_working_ports", "= root.winfo_screenwidth() # width of the screen hs = root.winfo_screenheight()", "working. \"\"\" non_working_ports = [] dev_port = 0 working_ports =", "tuple with the available ports and the ones that are", "handle_focus_out(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0, \"Example: <NAME>\") def hover(button, enter,", "= (hs/2) - (h/2) return(w,h,x,y) def handle_focus_in(button): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black')", "root.winfo_screenwidth() # width of the screen hs = root.winfo_screenheight() #", "width of the screen hs = root.winfo_screenheight() # height of", "time import csv import serial import cv2 import tkinter as", "pass return False def get_platform(): return platform.system() def get_gui_coordinates(root, w,", "return else: button.configure(text=message) def list_ports(): \"\"\" Test the ports and", "= camera.read() w = camera.get(3) h = camera.get(4) if is_reading:", "[] dev_port = 0 working_ports = [] available_ports = []", "ports and returns a tuple with the available ports and" ]
[ "self.model.load_config(config, budget=budget, **kwargs) evaluation_result = self.model.evaluate( self.x_train, self.y_train, self.x_valid, self.y_valid,", "x_train self.y_train = y_train self.x_valid = x_valid self.y_valid = y_valid", "EvaluationResultAggregator from a2e.utility import inf_nan_to_float_max class ModelWorker(Worker): def __init__( self,", "compute(self, config, budget, working_directory, **kwargs): iteration, stage, actual_num_config = kwargs['config_id']", "super().__init__(run_id, nameserver=nameserver, nameserver_port=nameserver_port, logger=logger, host=host, id=id, timeout=timeout) self.model = model", "self.model = model self.evaluation_result_aggregator = evaluation_result_aggregator self.x_train = x_train self.y_train", "working_directory, **kwargs): iteration, stage, actual_num_config = kwargs['config_id'] self.model.load_config(config, budget=budget, **kwargs)", "timeout=timeout) self.model = model self.evaluation_result_aggregator = evaluation_result_aggregator self.x_train = x_train", "self.y_train, self.x_valid, self.y_valid, budget, ) evaluation_result.add_info('iteration', iteration) evaluation_result.add_info('stage', stage) evaluation_result.add_info('actual_num_config',", "<filename>a2e/optimizer/hpbandster/_model_worker.py from hpbandster.core.worker import Worker from a2e.model import AbstractModel from", "def compute(self, config, budget, working_directory, **kwargs): iteration, stage, actual_num_config =", "import inf_nan_to_float_max class ModelWorker(Worker): def __init__( self, model: AbstractModel, evaluation_result_aggregator:", "logger=logger, host=host, id=id, timeout=timeout) self.model = model self.evaluation_result_aggregator = evaluation_result_aggregator", "ModelWorker(Worker): def __init__( self, model: AbstractModel, evaluation_result_aggregator: EvaluationResultAggregator, x_train, y_train,", "config, budget, working_directory, **kwargs): iteration, stage, actual_num_config = kwargs['config_id'] self.model.load_config(config,", "self.x_train, self.y_train, self.x_valid, self.y_valid, budget, ) evaluation_result.add_info('iteration', iteration) evaluation_result.add_info('stage', stage)", ") evaluation_result.add_info('iteration', iteration) evaluation_result.add_info('stage', stage) evaluation_result.add_info('actual_num_config', actual_num_config) self.evaluation_result_aggregator.add_evaluation_result(evaluation_result) return {", "id=None, timeout=None, ): super().__init__(run_id, nameserver=nameserver, nameserver_port=nameserver_port, logger=logger, host=host, id=id, timeout=timeout)", "y_train self.x_valid = x_valid self.y_valid = y_valid def compute(self, config,", "= y_valid def compute(self, config, budget, working_directory, **kwargs): iteration, stage,", "budget, ) evaluation_result.add_info('iteration', iteration) evaluation_result.add_info('stage', stage) evaluation_result.add_info('actual_num_config', actual_num_config) self.evaluation_result_aggregator.add_evaluation_result(evaluation_result) return", "self.x_train = x_train self.y_train = y_train self.x_valid = x_valid self.y_valid", "import AbstractModel from a2e.optimizer import EvaluationResultAggregator from a2e.utility import inf_nan_to_float_max", "kwargs['config_id'] self.model.load_config(config, budget=budget, **kwargs) evaluation_result = self.model.evaluate( self.x_train, self.y_train, self.x_valid,", "logger=None, host=None, id=None, timeout=None, ): super().__init__(run_id, nameserver=nameserver, nameserver_port=nameserver_port, logger=logger, host=host,", "AbstractModel from a2e.optimizer import EvaluationResultAggregator from a2e.utility import inf_nan_to_float_max class", "y_valid, run_id, nameserver=None, nameserver_port=None, logger=None, host=None, id=None, timeout=None, ): super().__init__(run_id,", "from a2e.utility import inf_nan_to_float_max class ModelWorker(Worker): def __init__( self, model:", "model self.evaluation_result_aggregator = evaluation_result_aggregator self.x_train = x_train self.y_train = y_train", "evaluation_result.add_info('actual_num_config', actual_num_config) self.evaluation_result_aggregator.add_evaluation_result(evaluation_result) return { 'loss': inf_nan_to_float_max(evaluation_result.cost), 'info': evaluation_result.info, }", "self.x_valid, self.y_valid, budget, ) evaluation_result.add_info('iteration', iteration) evaluation_result.add_info('stage', stage) evaluation_result.add_info('actual_num_config', actual_num_config)", "self.y_valid = y_valid def compute(self, config, budget, working_directory, **kwargs): iteration,", "actual_num_config = kwargs['config_id'] self.model.load_config(config, budget=budget, **kwargs) evaluation_result = self.model.evaluate( self.x_train,", "self.evaluation_result_aggregator = evaluation_result_aggregator self.x_train = x_train self.y_train = y_train self.x_valid", "y_valid def compute(self, config, budget, working_directory, **kwargs): iteration, stage, actual_num_config", "= self.model.evaluate( self.x_train, self.y_train, self.x_valid, self.y_valid, budget, ) evaluation_result.add_info('iteration', iteration)", "model: AbstractModel, evaluation_result_aggregator: EvaluationResultAggregator, x_train, y_train, x_valid, y_valid, run_id, nameserver=None,", "timeout=None, ): super().__init__(run_id, nameserver=nameserver, nameserver_port=nameserver_port, logger=logger, host=host, id=id, timeout=timeout) self.model", "budget=budget, **kwargs) evaluation_result = self.model.evaluate( self.x_train, self.y_train, self.x_valid, self.y_valid, budget,", "= y_train self.x_valid = x_valid self.y_valid = y_valid def compute(self,", "x_train, y_train, x_valid, y_valid, run_id, nameserver=None, nameserver_port=None, logger=None, host=None, id=None,", "evaluation_result_aggregator: EvaluationResultAggregator, x_train, y_train, x_valid, y_valid, run_id, nameserver=None, nameserver_port=None, logger=None,", "hpbandster.core.worker import Worker from a2e.model import AbstractModel from a2e.optimizer import", "iteration) evaluation_result.add_info('stage', stage) evaluation_result.add_info('actual_num_config', actual_num_config) self.evaluation_result_aggregator.add_evaluation_result(evaluation_result) return { 'loss': inf_nan_to_float_max(evaluation_result.cost),", "def __init__( self, model: AbstractModel, evaluation_result_aggregator: EvaluationResultAggregator, x_train, y_train, x_valid,", "**kwargs): iteration, stage, actual_num_config = kwargs['config_id'] self.model.load_config(config, budget=budget, **kwargs) evaluation_result", "class ModelWorker(Worker): def __init__( self, model: AbstractModel, evaluation_result_aggregator: EvaluationResultAggregator, x_train,", "from a2e.optimizer import EvaluationResultAggregator from a2e.utility import inf_nan_to_float_max class ModelWorker(Worker):", "): super().__init__(run_id, nameserver=nameserver, nameserver_port=nameserver_port, logger=logger, host=host, id=id, timeout=timeout) self.model =", "from a2e.model import AbstractModel from a2e.optimizer import EvaluationResultAggregator from a2e.utility", "nameserver_port=None, logger=None, host=None, id=None, timeout=None, ): super().__init__(run_id, nameserver=nameserver, nameserver_port=nameserver_port, logger=logger,", "host=None, id=None, timeout=None, ): super().__init__(run_id, nameserver=nameserver, nameserver_port=nameserver_port, logger=logger, host=host, id=id,", "self.y_valid, budget, ) evaluation_result.add_info('iteration', iteration) evaluation_result.add_info('stage', stage) evaluation_result.add_info('actual_num_config', actual_num_config) self.evaluation_result_aggregator.add_evaluation_result(evaluation_result)", "nameserver=None, nameserver_port=None, logger=None, host=None, id=None, timeout=None, ): super().__init__(run_id, nameserver=nameserver, nameserver_port=nameserver_port,", "a2e.utility import inf_nan_to_float_max class ModelWorker(Worker): def __init__( self, model: AbstractModel,", "= x_valid self.y_valid = y_valid def compute(self, config, budget, working_directory,", "y_train, x_valid, y_valid, run_id, nameserver=None, nameserver_port=None, logger=None, host=None, id=None, timeout=None,", "evaluation_result.add_info('stage', stage) evaluation_result.add_info('actual_num_config', actual_num_config) self.evaluation_result_aggregator.add_evaluation_result(evaluation_result) return { 'loss': inf_nan_to_float_max(evaluation_result.cost), 'info':", "Worker from a2e.model import AbstractModel from a2e.optimizer import EvaluationResultAggregator from", "= x_train self.y_train = y_train self.x_valid = x_valid self.y_valid =", "x_valid, y_valid, run_id, nameserver=None, nameserver_port=None, logger=None, host=None, id=None, timeout=None, ):", "evaluation_result_aggregator self.x_train = x_train self.y_train = y_train self.x_valid = x_valid", "nameserver=nameserver, nameserver_port=nameserver_port, logger=logger, host=host, id=id, timeout=timeout) self.model = model self.evaluation_result_aggregator", "stage) evaluation_result.add_info('actual_num_config', actual_num_config) self.evaluation_result_aggregator.add_evaluation_result(evaluation_result) return { 'loss': inf_nan_to_float_max(evaluation_result.cost), 'info': evaluation_result.info,", "= evaluation_result_aggregator self.x_train = x_train self.y_train = y_train self.x_valid =", "self.y_train = y_train self.x_valid = x_valid self.y_valid = y_valid def", "AbstractModel, evaluation_result_aggregator: EvaluationResultAggregator, x_train, y_train, x_valid, y_valid, run_id, nameserver=None, nameserver_port=None,", "run_id, nameserver=None, nameserver_port=None, logger=None, host=None, id=None, timeout=None, ): super().__init__(run_id, nameserver=nameserver,", "inf_nan_to_float_max class ModelWorker(Worker): def __init__( self, model: AbstractModel, evaluation_result_aggregator: EvaluationResultAggregator,", "self.x_valid = x_valid self.y_valid = y_valid def compute(self, config, budget,", "EvaluationResultAggregator, x_train, y_train, x_valid, y_valid, run_id, nameserver=None, nameserver_port=None, logger=None, host=None,", "import EvaluationResultAggregator from a2e.utility import inf_nan_to_float_max class ModelWorker(Worker): def __init__(", "nameserver_port=nameserver_port, logger=logger, host=host, id=id, timeout=timeout) self.model = model self.evaluation_result_aggregator =", "a2e.model import AbstractModel from a2e.optimizer import EvaluationResultAggregator from a2e.utility import", "= kwargs['config_id'] self.model.load_config(config, budget=budget, **kwargs) evaluation_result = self.model.evaluate( self.x_train, self.y_train,", "budget, working_directory, **kwargs): iteration, stage, actual_num_config = kwargs['config_id'] self.model.load_config(config, budget=budget,", "host=host, id=id, timeout=timeout) self.model = model self.evaluation_result_aggregator = evaluation_result_aggregator self.x_train", "id=id, timeout=timeout) self.model = model self.evaluation_result_aggregator = evaluation_result_aggregator self.x_train =", "evaluation_result = self.model.evaluate( self.x_train, self.y_train, self.x_valid, self.y_valid, budget, ) evaluation_result.add_info('iteration',", "self.model.evaluate( self.x_train, self.y_train, self.x_valid, self.y_valid, budget, ) evaluation_result.add_info('iteration', iteration) evaluation_result.add_info('stage',", "evaluation_result.add_info('iteration', iteration) evaluation_result.add_info('stage', stage) evaluation_result.add_info('actual_num_config', actual_num_config) self.evaluation_result_aggregator.add_evaluation_result(evaluation_result) return { 'loss':", "from hpbandster.core.worker import Worker from a2e.model import AbstractModel from a2e.optimizer", "a2e.optimizer import EvaluationResultAggregator from a2e.utility import inf_nan_to_float_max class ModelWorker(Worker): def", "**kwargs) evaluation_result = self.model.evaluate( self.x_train, self.y_train, self.x_valid, self.y_valid, budget, )", "stage, actual_num_config = kwargs['config_id'] self.model.load_config(config, budget=budget, **kwargs) evaluation_result = self.model.evaluate(", "= model self.evaluation_result_aggregator = evaluation_result_aggregator self.x_train = x_train self.y_train =", "import Worker from a2e.model import AbstractModel from a2e.optimizer import EvaluationResultAggregator", "x_valid self.y_valid = y_valid def compute(self, config, budget, working_directory, **kwargs):", "iteration, stage, actual_num_config = kwargs['config_id'] self.model.load_config(config, budget=budget, **kwargs) evaluation_result =", "self, model: AbstractModel, evaluation_result_aggregator: EvaluationResultAggregator, x_train, y_train, x_valid, y_valid, run_id,", "__init__( self, model: AbstractModel, evaluation_result_aggregator: EvaluationResultAggregator, x_train, y_train, x_valid, y_valid," ]
[ "{'module': td3, 'agent': TD3}, 'trpo': {'module': trpo, 'agent': TRPO}, 'ddpg':", "from xagents.base import OffPolicy from xagents.ddpg.agent import DDPG from xagents.dqn.agent", "'acer': {'module': acer, 'agent': ACER}, 'dqn': {'module': dqn, 'agent': DQN},", "dqn, ppo, td3, trpo from xagents.a2c.agent import A2C from xagents.acer.agent", "a2c, 'agent': A2C}, 'acer': {'module': acer, 'agent': ACER}, 'dqn': {'module':", "tune_args from xagents.utils.common import register_models __author__ = 'schissmantics' __email__ =", "import DDPG from xagents.dqn.agent import DQN from xagents.ppo.agent import PPO", "'train': (train_args, 'fit', 'Train given an agent and environment'), 'play':", "import A2C from xagents.acer.agent import ACER from xagents.base import OffPolicy", "'', 'Tune hyperparameters given an agent, hyperparameter specs, and environment',", "trpo, 'agent': TRPO}, 'ddpg': {'module': ddpg, 'agent': DDPG}, } register_models(agents)", "from xagents.ppo.agent import PPO from xagents.td3.agent import TD3 from xagents.trpo.agent", "TRPO from xagents.utils.cli import play_args, train_args, tune_args from xagents.utils.common import", "register_models __author__ = 'schissmantics' __email__ = '<EMAIL>' __license__ = 'MIT'", "acer, ddpg, dqn, ppo, td3, trpo from xagents.a2c.agent import A2C", "DDPG from xagents.dqn.agent import DQN from xagents.ppo.agent import PPO from", "import register_models __author__ = 'schissmantics' __email__ = '<EMAIL>' __license__ =", "import a2c, acer, ddpg, dqn, ppo, td3, trpo from xagents.a2c.agent", "agents = { 'a2c': {'module': a2c, 'agent': A2C}, 'acer': {'module':", "import PPO from xagents.td3.agent import TD3 from xagents.trpo.agent import TRPO", "from xagents.dqn.agent import DQN from xagents.ppo.agent import PPO from xagents.td3.agent", "'trpo': {'module': trpo, 'agent': TRPO}, 'ddpg': {'module': ddpg, 'agent': DDPG},", "'Play a game given a trained agent and environment', ),", "an agent and environment'), 'play': ( play_args, 'play', 'Play a", "xagents.ppo.agent import PPO from xagents.td3.agent import TD3 from xagents.trpo.agent import", "import TD3 from xagents.trpo.agent import TRPO from xagents.utils.cli import play_args,", "train_args, tune_args from xagents.utils.common import register_models __author__ = 'schissmantics' __email__", "xagents.trpo.agent import TRPO from xagents.utils.cli import play_args, train_args, tune_args from", "from xagents.ddpg.agent import DDPG from xagents.dqn.agent import DQN from xagents.ppo.agent", "play_args, train_args, tune_args from xagents.utils.common import register_models __author__ = 'schissmantics'", "xagents.acer.agent import ACER from xagents.base import OffPolicy from xagents.ddpg.agent import", "DQN from xagents.ppo.agent import PPO from xagents.td3.agent import TD3 from", "environment', ), 'tune': ( tune_args, '', 'Tune hyperparameters given an", "from xagents.trpo.agent import TRPO from xagents.utils.cli import play_args, train_args, tune_args", "ppo, 'agent': PPO}, 'td3': {'module': td3, 'agent': TD3}, 'trpo': {'module':", "'dqn': {'module': dqn, 'agent': DQN}, 'ppo': {'module': ppo, 'agent': PPO},", "game given a trained agent and environment', ), 'tune': (", "xagents import a2c, acer, ddpg, dqn, ppo, td3, trpo from", "trpo from xagents.a2c.agent import A2C from xagents.acer.agent import ACER from", "A2C from xagents.acer.agent import ACER from xagents.base import OffPolicy from", "xagents.base import OffPolicy from xagents.ddpg.agent import DDPG from xagents.dqn.agent import", "OffPolicy from xagents.ddpg.agent import DDPG from xagents.dqn.agent import DQN from", "register_models(agents) commands = { 'train': (train_args, 'fit', 'Train given an", "tune_args, '', 'Tune hyperparameters given an agent, hyperparameter specs, and", "{'module': ppo, 'agent': PPO}, 'td3': {'module': td3, 'agent': TD3}, 'trpo':", "'td3': {'module': td3, 'agent': TD3}, 'trpo': {'module': trpo, 'agent': TRPO},", "and environment', ), 'tune': ( tune_args, '', 'Tune hyperparameters given", "TD3 from xagents.trpo.agent import TRPO from xagents.utils.cli import play_args, train_args,", "TRPO}, 'ddpg': {'module': ddpg, 'agent': DDPG}, } register_models(agents) commands =", "from xagents.td3.agent import TD3 from xagents.trpo.agent import TRPO from xagents.utils.cli", "td3, 'agent': TD3}, 'trpo': {'module': trpo, 'agent': TRPO}, 'ddpg': {'module':", "td3, trpo from xagents.a2c.agent import A2C from xagents.acer.agent import ACER", "agent and environment'), 'play': ( play_args, 'play', 'Play a game", "and environment'), 'play': ( play_args, 'play', 'Play a game given", "xagents.utils.cli import play_args, train_args, tune_args from xagents.utils.common import register_models __author__", "a trained agent and environment', ), 'tune': ( tune_args, '',", "A2C}, 'acer': {'module': acer, 'agent': ACER}, 'dqn': {'module': dqn, 'agent':", "import ACER from xagents.base import OffPolicy from xagents.ddpg.agent import DDPG", "{ 'train': (train_args, 'fit', 'Train given an agent and environment'),", "'fit', 'Train given an agent and environment'), 'play': ( play_args,", "xagents.a2c.agent import A2C from xagents.acer.agent import ACER from xagents.base import", "import OffPolicy from xagents.ddpg.agent import DDPG from xagents.dqn.agent import DQN", "import play_args, train_args, tune_args from xagents.utils.common import register_models __author__ =", "import DQN from xagents.ppo.agent import PPO from xagents.td3.agent import TD3", "'tune': ( tune_args, '', 'Tune hyperparameters given an agent, hyperparameter", "'MIT' __version__ = '1.0.1' agents = { 'a2c': {'module': a2c,", "'agent': PPO}, 'td3': {'module': td3, 'agent': TD3}, 'trpo': {'module': trpo,", "'Tune hyperparameters given an agent, hyperparameter specs, and environment', ),", "'<EMAIL>' __license__ = 'MIT' __version__ = '1.0.1' agents = {", "'1.0.1' agents = { 'a2c': {'module': a2c, 'agent': A2C}, 'acer':", "__version__ = '1.0.1' agents = { 'a2c': {'module': a2c, 'agent':", "DDPG}, } register_models(agents) commands = { 'train': (train_args, 'fit', 'Train", "trained agent and environment', ), 'tune': ( tune_args, '', 'Tune", "DQN}, 'ppo': {'module': ppo, 'agent': PPO}, 'td3': {'module': td3, 'agent':", "'agent': DQN}, 'ppo': {'module': ppo, 'agent': PPO}, 'td3': {'module': td3,", "from xagents.utils.common import register_models __author__ = 'schissmantics' __email__ = '<EMAIL>'", "environment'), 'play': ( play_args, 'play', 'Play a game given a", "from xagents.acer.agent import ACER from xagents.base import OffPolicy from xagents.ddpg.agent", "hyperparameters given an agent, hyperparameter specs, and environment', ), }", "'agent': ACER}, 'dqn': {'module': dqn, 'agent': DQN}, 'ppo': {'module': ppo,", "'agent': TD3}, 'trpo': {'module': trpo, 'agent': TRPO}, 'ddpg': {'module': ddpg,", "'agent': DDPG}, } register_models(agents) commands = { 'train': (train_args, 'fit',", "{'module': acer, 'agent': ACER}, 'dqn': {'module': dqn, 'agent': DQN}, 'ppo':", "xagents.utils.common import register_models __author__ = 'schissmantics' __email__ = '<EMAIL>' __license__", "xagents.dqn.agent import DQN from xagents.ppo.agent import PPO from xagents.td3.agent import", "= { 'train': (train_args, 'fit', 'Train given an agent and", "{'module': ddpg, 'agent': DDPG}, } register_models(agents) commands = { 'train':", "__email__ = '<EMAIL>' __license__ = 'MIT' __version__ = '1.0.1' agents", "'schissmantics' __email__ = '<EMAIL>' __license__ = 'MIT' __version__ = '1.0.1'", "__license__ = 'MIT' __version__ = '1.0.1' agents = { 'a2c':", "PPO from xagents.td3.agent import TD3 from xagents.trpo.agent import TRPO from", "a game given a trained agent and environment', ), 'tune':", "import TRPO from xagents.utils.cli import play_args, train_args, tune_args from xagents.utils.common", "from xagents import a2c, acer, ddpg, dqn, ppo, td3, trpo", "'ddpg': {'module': ddpg, 'agent': DDPG}, } register_models(agents) commands = {", "( tune_args, '', 'Tune hyperparameters given an agent, hyperparameter specs,", "'Train given an agent and environment'), 'play': ( play_args, 'play',", "xagents.ddpg.agent import DDPG from xagents.dqn.agent import DQN from xagents.ppo.agent import", "given an agent and environment'), 'play': ( play_args, 'play', 'Play", "from xagents.utils.cli import play_args, train_args, tune_args from xagents.utils.common import register_models", "'agent': A2C}, 'acer': {'module': acer, 'agent': ACER}, 'dqn': {'module': dqn,", "{ 'a2c': {'module': a2c, 'agent': A2C}, 'acer': {'module': acer, 'agent':", "PPO}, 'td3': {'module': td3, 'agent': TD3}, 'trpo': {'module': trpo, 'agent':", "play_args, 'play', 'Play a game given a trained agent and", "a2c, acer, ddpg, dqn, ppo, td3, trpo from xagents.a2c.agent import", "{'module': dqn, 'agent': DQN}, 'ppo': {'module': ppo, 'agent': PPO}, 'td3':", "'ppo': {'module': ppo, 'agent': PPO}, 'td3': {'module': td3, 'agent': TD3},", "ppo, td3, trpo from xagents.a2c.agent import A2C from xagents.acer.agent import", "'play': ( play_args, 'play', 'Play a game given a trained", "ddpg, 'agent': DDPG}, } register_models(agents) commands = { 'train': (train_args,", "ddpg, dqn, ppo, td3, trpo from xagents.a2c.agent import A2C from", "'a2c': {'module': a2c, 'agent': A2C}, 'acer': {'module': acer, 'agent': ACER},", "( play_args, 'play', 'Play a game given a trained agent", "__author__ = 'schissmantics' __email__ = '<EMAIL>' __license__ = 'MIT' __version__", "ACER}, 'dqn': {'module': dqn, 'agent': DQN}, 'ppo': {'module': ppo, 'agent':", "= '1.0.1' agents = { 'a2c': {'module': a2c, 'agent': A2C},", "from xagents.a2c.agent import A2C from xagents.acer.agent import ACER from xagents.base", "{'module': trpo, 'agent': TRPO}, 'ddpg': {'module': ddpg, 'agent': DDPG}, }", "dqn, 'agent': DQN}, 'ppo': {'module': ppo, 'agent': PPO}, 'td3': {'module':", "acer, 'agent': ACER}, 'dqn': {'module': dqn, 'agent': DQN}, 'ppo': {'module':", "agent and environment', ), 'tune': ( tune_args, '', 'Tune hyperparameters", "= '<EMAIL>' __license__ = 'MIT' __version__ = '1.0.1' agents =", "(train_args, 'fit', 'Train given an agent and environment'), 'play': (", "TD3}, 'trpo': {'module': trpo, 'agent': TRPO}, 'ddpg': {'module': ddpg, 'agent':", "ACER from xagents.base import OffPolicy from xagents.ddpg.agent import DDPG from", "given a trained agent and environment', ), 'tune': ( tune_args,", "= { 'a2c': {'module': a2c, 'agent': A2C}, 'acer': {'module': acer,", "xagents.td3.agent import TD3 from xagents.trpo.agent import TRPO from xagents.utils.cli import", "= 'MIT' __version__ = '1.0.1' agents = { 'a2c': {'module':", "commands = { 'train': (train_args, 'fit', 'Train given an agent", "= 'schissmantics' __email__ = '<EMAIL>' __license__ = 'MIT' __version__ =", "'agent': TRPO}, 'ddpg': {'module': ddpg, 'agent': DDPG}, } register_models(agents) commands", "), 'tune': ( tune_args, '', 'Tune hyperparameters given an agent,", "} register_models(agents) commands = { 'train': (train_args, 'fit', 'Train given", "{'module': a2c, 'agent': A2C}, 'acer': {'module': acer, 'agent': ACER}, 'dqn':", "'play', 'Play a game given a trained agent and environment'," ]
[]
[ "None: self.job_type = \"local_single\" if self.config.task_type is not None: self.job_type", "= \"'\"+str(config.fairseq[field][key])+\"'\" else: value = str(config.fairseq[field][key]) param = [ \"--\"", "else: return \"{} is running.\".format(self.job_id) def stderr(self): return self.result() def", "NotImplementedError def _normalize_cmd(self, cmd_list): cmd_list = list(cmd_list) yaml_index = cmd_list.index(\"[yaml]\")", "yaml_index = cmd_list.index(\"[yaml]\") cmd_list[yaml_index] = self.yaml_file return cmd_list class LocalJob(BaseJob):", "cmd_list.index(\"[yaml]\") cmd_list[yaml_index] = self.yaml_file return cmd_list class LocalJob(BaseJob): CMD_CONFIG =", "def __repr__(self): return self.job_id def __str__(self): return self.job_id def done(self):", "is not None: self.job_type = self.config.task_type else: self.job_type = job_type", "and its affiliates. # # This source code is licensed", "\" \".join(cmd_list)) if not self.dryrun: os.system(\" \".join(cmd_list)) return JobStatus(\"12345678\") class", "self.dryrun: os.system(\" \".join(cmd_list)) return JobStatus(\"12345678\") class JobStatus(object): def __init__(self, job_id):", "in the # LICENSE file in the root directory of", "import os from mmpt.utils import recursive_config class BaseJob(object): def __init__(self,", "else: if key == \"lr\": value = str(config.fairseq[field][key][0]) elif key", "== \"adam_betas\": value = \"'\"+str(config.fairseq[field][key])+\"'\" else: value = str(config.fairseq[field][key]) param", "under the MIT license found in the # LICENSE file", "32 for local testing?\") def submit(self): cmd_list = self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if", "job_id): self.job_id = job_id def __repr__(self): return self.job_id def __str__(self):", "def done(self): return False def running(self): return False def result(self):", "[ \"--\" + key.replace(\"_\", \"-\"), value ] cmd_list.extend(param) print(\"launching\", \"", "batch_size to 32 for local testing?\") def submit(self): cmd_list =", "config = load_config(config_file=self.yaml_file) for field in config.fairseq: for key in", "[\"--\" + key.replace(\"_\", \"-\")] else: if key == \"lr\": value", "\"--criterion\", \"mmloss\", \"--distributed-world-size\", \"2\" ], \"local_big\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\",", "__repr__(self): return self.job_id def __str__(self): return self.job_id def done(self): return", "_normalize_cmd(self, cmd_list): cmd_list = list(cmd_list) yaml_index = cmd_list.index(\"[yaml]\") cmd_list[yaml_index] =", "self.config.fairseq.dataset.batch_size > 32: print(\"decreasing batch_size to 32 for local testing?\")", "False def result(self): if self.done(): return \"{} is done.\".format(self.job_id) else:", "Copyright (c) Facebook, Inc. and its affiliates. # # This", "\"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"2\" ], \"local_big\": [", "elif key == \"adam_betas\": value = \"'\"+str(config.fairseq[field][key])+\"'\" else: value =", "LICENSE file in the root directory of this source tree.", "if self.job_type in [\"local_single\", \"local_small\"]: if self.config.fairseq.dataset.batch_size > 32: print(\"decreasing", "the root directory of this source tree. import os from", "\"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"4\" ], \"local_predict\": [\"python\",", "submit(self): cmd_list = self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if \"predict\" not in self.job_type: #", "yaml_file self.config = recursive_config(yaml_file) self.dryrun = dryrun def submit(self, **kwargs):", "else: self.job_type = job_type if self.job_type in [\"local_single\", \"local_small\"]: if", "\"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", ],", "in config.fairseq[field]: if key in [\"fp16\", \"reset_optimizer\", \"reset_dataloader\", \"reset_meters\"]: #", "its affiliates. # # This source code is licensed under", "= job_id def __repr__(self): return self.job_id def __str__(self): return self.job_id", "== \"lr\": value = str(config.fairseq[field][key][0]) elif key == \"adam_betas\": value", "self.job_id def done(self): return False def running(self): return False def", "source tree. import os from mmpt.utils import recursive_config class BaseJob(object):", "for key in config.fairseq[field]: if key in [\"fp16\", \"reset_optimizer\", \"reset_dataloader\",", "list of binary flag. param = [\"--\" + key.replace(\"_\", \"-\")]", "cmd_list[yaml_index] = self.yaml_file return cmd_list class LocalJob(BaseJob): CMD_CONFIG = {", "= \"local_single\" if self.config.task_type is not None: self.job_type = self.config.task_type", "False def running(self): return False def result(self): if self.done(): return", "= { \"local_single\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\",", "self.job_id = job_id def __repr__(self): return self.job_id def __str__(self): return", "= str(config.fairseq[field][key][0]) elif key == \"adam_betas\": value = \"'\"+str(config.fairseq[field][key])+\"'\" else:", "\"reset_dataloader\", \"reset_meters\"]: # a list of binary flag. param =", "\"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", ], \"local_small\": [ \"fairseq-train\",", "= [\"--\" + key.replace(\"_\", \"-\")] else: if key == \"lr\":", "\"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"2\" ], \"local_big\":", "value ] cmd_list.extend(param) print(\"launching\", \" \".join(cmd_list)) if not self.dryrun: os.system(\"", "key in [\"fp16\", \"reset_optimizer\", \"reset_dataloader\", \"reset_meters\"]: # a list of", "key.replace(\"_\", \"-\"), value ] cmd_list.extend(param) print(\"launching\", \" \".join(cmd_list)) if not", "\"local_small\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\",", "if self.config.task_type is not None: self.job_type = self.config.task_type else: self.job_type", "config.fairseq[field]: if key in [\"fp16\", \"reset_optimizer\", \"reset_dataloader\", \"reset_meters\"]: # a", "# LICENSE file in the root directory of this source", "CMD_CONFIG = { \"local_single\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\",", "append fairseq args. from mmpt.utils import load_config config = load_config(config_file=self.yaml_file)", "self.job_type: # append fairseq args. from mmpt.utils import load_config config", "the MIT license found in the # LICENSE file in", "in config.fairseq: for key in config.fairseq[field]: if key in [\"fp16\",", "is None: self.job_type = \"local_single\" if self.config.task_type is not None:", "found in the # LICENSE file in the root directory", "for local testing?\") def submit(self): cmd_list = self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if \"predict\"", "dryrun) if job_type is None: self.job_type = \"local_single\" if self.config.task_type", "def submit(self, **kwargs): raise NotImplementedError def _normalize_cmd(self, cmd_list): cmd_list =", "key == \"adam_betas\": value = \"'\"+str(config.fairseq[field][key])+\"'\" else: value = str(config.fairseq[field][key])", "this source tree. import os from mmpt.utils import recursive_config class", "return \"{} is done.\".format(self.job_id) else: return \"{} is running.\".format(self.job_id) def", "} def __init__(self, yaml_file, job_type=None, dryrun=False): super().__init__(yaml_file, dryrun) if job_type", "LocalJob(BaseJob): CMD_CONFIG = { \"local_single\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\",", "return cmd_list class LocalJob(BaseJob): CMD_CONFIG = { \"local_single\": [ \"fairseq-train\",", "\"mmloss\", \"--distributed-world-size\", \"2\" ], \"local_big\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\",", "license found in the # LICENSE file in the root", "= self.yaml_file return cmd_list class LocalJob(BaseJob): CMD_CONFIG = { \"local_single\":", "field in config.fairseq: for key in config.fairseq[field]: if key in", "[\"fp16\", \"reset_optimizer\", \"reset_dataloader\", \"reset_meters\"]: # a list of binary flag.", "] cmd_list.extend(param) print(\"launching\", \" \".join(cmd_list)) if not self.dryrun: os.system(\" \".join(cmd_list))", "job_id def __repr__(self): return self.job_id def __str__(self): return self.job_id def", "if key in [\"fp16\", \"reset_optimizer\", \"reset_dataloader\", \"reset_meters\"]: # a list", "not in self.job_type: # append fairseq args. from mmpt.utils import", "[\"python\", \"mmpt_cli/predict.py\", \"[yaml]\"], } def __init__(self, yaml_file, job_type=None, dryrun=False): super().__init__(yaml_file,", "= [ \"--\" + key.replace(\"_\", \"-\"), value ] cmd_list.extend(param) print(\"launching\",", "**kwargs): raise NotImplementedError def _normalize_cmd(self, cmd_list): cmd_list = list(cmd_list) yaml_index", "done(self): return False def running(self): return False def result(self): if", "\"local_single\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\",", "\"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", ], \"local_small\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\",", "self.job_type = \"local_single\" if self.config.task_type is not None: self.job_type =", "done.\".format(self.job_id) else: return \"{} is running.\".format(self.job_id) def stderr(self): return self.result()", "JobStatus(object): def __init__(self, job_id): self.job_id = job_id def __repr__(self): return", "cmd_list = list(cmd_list) yaml_index = cmd_list.index(\"[yaml]\") cmd_list[yaml_index] = self.yaml_file return", "running(self): return False def result(self): if self.done(): return \"{} is", "self.config.task_type else: self.job_type = job_type if self.job_type in [\"local_single\", \"local_small\"]:", "\"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"4\" ], \"local_predict\":", "load_config config = load_config(config_file=self.yaml_file) for field in config.fairseq: for key", "to 32 for local testing?\") def submit(self): cmd_list = self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type])", "+ key.replace(\"_\", \"-\"), value ] cmd_list.extend(param) print(\"launching\", \" \".join(cmd_list)) if", "import load_config config = load_config(config_file=self.yaml_file) for field in config.fairseq: for", "\"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\",", "], \"local_predict\": [\"python\", \"mmpt_cli/predict.py\", \"[yaml]\"], } def __init__(self, yaml_file, job_type=None,", "key.replace(\"_\", \"-\")] else: if key == \"lr\": value = str(config.fairseq[field][key][0])", "import recursive_config class BaseJob(object): def __init__(self, yaml_file, dryrun=False): self.yaml_file =", "args. from mmpt.utils import load_config config = load_config(config_file=self.yaml_file) for field", "print(\"launching\", \" \".join(cmd_list)) if not self.dryrun: os.system(\" \".join(cmd_list)) return JobStatus(\"12345678\")", "__init__(self, job_id): self.job_id = job_id def __repr__(self): return self.job_id def", "self.job_id def __str__(self): return self.job_id def done(self): return False def", "self.config = recursive_config(yaml_file) self.dryrun = dryrun def submit(self, **kwargs): raise", "submit(self, **kwargs): raise NotImplementedError def _normalize_cmd(self, cmd_list): cmd_list = list(cmd_list)", "job_type is None: self.job_type = \"local_single\" if self.config.task_type is not", "= dryrun def submit(self, **kwargs): raise NotImplementedError def _normalize_cmd(self, cmd_list):", "\"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"4\" ],", "dryrun=False): super().__init__(yaml_file, dryrun) if job_type is None: self.job_type = \"local_single\"", "None: self.job_type = self.config.task_type else: self.job_type = job_type if self.job_type", "= job_type if self.job_type in [\"local_single\", \"local_small\"]: if self.config.fairseq.dataset.batch_size >", "\"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\",", "\"--distributed-world-size\", \"2\" ], \"local_big\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\",", "[\"local_single\", \"local_small\"]: if self.config.fairseq.dataset.batch_size > 32: print(\"decreasing batch_size to 32", "\"--criterion\", \"mmloss\", \"--distributed-world-size\", \"4\" ], \"local_predict\": [\"python\", \"mmpt_cli/predict.py\", \"[yaml]\"], }", "\"[yaml]\"], } def __init__(self, yaml_file, job_type=None, dryrun=False): super().__init__(yaml_file, dryrun) if", "BaseJob(object): def __init__(self, yaml_file, dryrun=False): self.yaml_file = yaml_file self.config =", "self.job_type in [\"local_single\", \"local_small\"]: if self.config.fairseq.dataset.batch_size > 32: print(\"decreasing batch_size", "], \"local_small\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\",", "param = [ \"--\" + key.replace(\"_\", \"-\"), value ] cmd_list.extend(param)", "(c) Facebook, Inc. and its affiliates. # # This source", "\"reset_meters\"]: # a list of binary flag. param = [\"--\"", "binary flag. param = [\"--\" + key.replace(\"_\", \"-\")] else: if", "self.config.task_type is not None: self.job_type = self.config.task_type else: self.job_type =", "\"adam_betas\": value = \"'\"+str(config.fairseq[field][key])+\"'\" else: value = str(config.fairseq[field][key]) param =", "return JobStatus(\"12345678\") class JobStatus(object): def __init__(self, job_id): self.job_id = job_id", "def __init__(self, yaml_file, job_type=None, dryrun=False): super().__init__(yaml_file, dryrun) if job_type is", "if job_type is None: self.job_type = \"local_single\" if self.config.task_type is", "= str(config.fairseq[field][key]) param = [ \"--\" + key.replace(\"_\", \"-\"), value", "is licensed under the MIT license found in the #", "+ key.replace(\"_\", \"-\")] else: if key == \"lr\": value =", "cmd_list.extend(param) print(\"launching\", \" \".join(cmd_list)) if not self.dryrun: os.system(\" \".join(cmd_list)) return", "class JobStatus(object): def __init__(self, job_id): self.job_id = job_id def __repr__(self):", "the # LICENSE file in the root directory of this", "\"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", ], \"local_small\": [ \"fairseq-train\", \"[yaml]\",", "job_type=None, dryrun=False): super().__init__(yaml_file, dryrun) if job_type is None: self.job_type =", "\"--\" + key.replace(\"_\", \"-\"), value ] cmd_list.extend(param) print(\"launching\", \" \".join(cmd_list))", "__str__(self): return self.job_id def done(self): return False def running(self): return", "self.done(): return \"{} is done.\".format(self.job_id) else: return \"{} is running.\".format(self.job_id)", "= self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if \"predict\" not in self.job_type: # append fairseq", "\"{} is done.\".format(self.job_id) else: return \"{} is running.\".format(self.job_id) def stderr(self):", "\".join(cmd_list)) if not self.dryrun: os.system(\" \".join(cmd_list)) return JobStatus(\"12345678\") class JobStatus(object):", "config.fairseq: for key in config.fairseq[field]: if key in [\"fp16\", \"reset_optimizer\",", "JobStatus(\"12345678\") class JobStatus(object): def __init__(self, job_id): self.job_id = job_id def", "32: print(\"decreasing batch_size to 32 for local testing?\") def submit(self):", "flag. param = [\"--\" + key.replace(\"_\", \"-\")] else: if key", "in the root directory of this source tree. import os", "dryrun def submit(self, **kwargs): raise NotImplementedError def _normalize_cmd(self, cmd_list): cmd_list", "= cmd_list.index(\"[yaml]\") cmd_list[yaml_index] = self.yaml_file return cmd_list class LocalJob(BaseJob): CMD_CONFIG", "class LocalJob(BaseJob): CMD_CONFIG = { \"local_single\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\",", "not None: self.job_type = self.config.task_type else: self.job_type = job_type if", "> 32: print(\"decreasing batch_size to 32 for local testing?\") def", "fairseq args. from mmpt.utils import load_config config = load_config(config_file=self.yaml_file) for", "\"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", ], \"local_small\": [", "is done.\".format(self.job_id) else: return \"{} is running.\".format(self.job_id) def stderr(self): return", "if \"predict\" not in self.job_type: # append fairseq args. from", "# Copyright (c) Facebook, Inc. and its affiliates. # #", "\"reset_optimizer\", \"reset_dataloader\", \"reset_meters\"]: # a list of binary flag. param", "file in the root directory of this source tree. import", "\"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"4\" ], \"local_predict\": [\"python\", \"mmpt_cli/predict.py\",", "\"mmloss\", ], \"local_small\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\",", "dryrun=False): self.yaml_file = yaml_file self.config = recursive_config(yaml_file) self.dryrun = dryrun", "\"4\" ], \"local_predict\": [\"python\", \"mmpt_cli/predict.py\", \"[yaml]\"], } def __init__(self, yaml_file,", "value = str(config.fairseq[field][key]) param = [ \"--\" + key.replace(\"_\", \"-\"),", "param = [\"--\" + key.replace(\"_\", \"-\")] else: if key ==", "# append fairseq args. from mmpt.utils import load_config config =", "= yaml_file self.config = recursive_config(yaml_file) self.dryrun = dryrun def submit(self,", "This source code is licensed under the MIT license found", "\"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"2\"", "\"-\")] else: if key == \"lr\": value = str(config.fairseq[field][key][0]) elif", "\".join(cmd_list)) return JobStatus(\"12345678\") class JobStatus(object): def __init__(self, job_id): self.job_id =", "yaml_file, job_type=None, dryrun=False): super().__init__(yaml_file, dryrun) if job_type is None: self.job_type", "cmd_list class LocalJob(BaseJob): CMD_CONFIG = { \"local_single\": [ \"fairseq-train\", \"[yaml]\",", "__init__(self, yaml_file, job_type=None, dryrun=False): super().__init__(yaml_file, dryrun) if job_type is None:", "if self.done(): return \"{} is done.\".format(self.job_id) else: return \"{} is", "else: value = str(config.fairseq[field][key]) param = [ \"--\" + key.replace(\"_\",", "is running.\".format(self.job_id) def stderr(self): return self.result() def stdout(self): return self.result()", "# a list of binary flag. param = [\"--\" +", "recursive_config(yaml_file) self.dryrun = dryrun def submit(self, **kwargs): raise NotImplementedError def", "for field in config.fairseq: for key in config.fairseq[field]: if key", "return self.job_id def __str__(self): return self.job_id def done(self): return False", "if not self.dryrun: os.system(\" \".join(cmd_list)) return JobStatus(\"12345678\") class JobStatus(object): def", "job_type if self.job_type in [\"local_single\", \"local_small\"]: if self.config.fairseq.dataset.batch_size > 32:", "of binary flag. param = [\"--\" + key.replace(\"_\", \"-\")] else:", "code is licensed under the MIT license found in the", "if self.config.fairseq.dataset.batch_size > 32: print(\"decreasing batch_size to 32 for local", "directory of this source tree. import os from mmpt.utils import", "= list(cmd_list) yaml_index = cmd_list.index(\"[yaml]\") cmd_list[yaml_index] = self.yaml_file return cmd_list", "{ \"local_single\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\",", "\"local_single\" if self.config.task_type is not None: self.job_type = self.config.task_type else:", "return False def running(self): return False def result(self): if self.done():", "print(\"decreasing batch_size to 32 for local testing?\") def submit(self): cmd_list", "\"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"2\" ], \"local_big\": [ \"fairseq-train\", \"[yaml]\",", "\"local_predict\": [\"python\", \"mmpt_cli/predict.py\", \"[yaml]\"], } def __init__(self, yaml_file, job_type=None, dryrun=False):", "os from mmpt.utils import recursive_config class BaseJob(object): def __init__(self, yaml_file,", "str(config.fairseq[field][key]) param = [ \"--\" + key.replace(\"_\", \"-\"), value ]", "\"'\"+str(config.fairseq[field][key])+\"'\" else: value = str(config.fairseq[field][key]) param = [ \"--\" +", "source code is licensed under the MIT license found in", "not self.dryrun: os.system(\" \".join(cmd_list)) return JobStatus(\"12345678\") class JobStatus(object): def __init__(self,", "Facebook, Inc. and its affiliates. # # This source code", "mmpt.utils import recursive_config class BaseJob(object): def __init__(self, yaml_file, dryrun=False): self.yaml_file", "licensed under the MIT license found in the # LICENSE", "raise NotImplementedError def _normalize_cmd(self, cmd_list): cmd_list = list(cmd_list) yaml_index =", "= self.config.task_type else: self.job_type = job_type if self.job_type in [\"local_single\",", "], \"local_big\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\",", "\"local_small\"]: if self.config.fairseq.dataset.batch_size > 32: print(\"decreasing batch_size to 32 for", "self.job_type = self.config.task_type else: self.job_type = job_type if self.job_type in", "mmpt.utils import load_config config = load_config(config_file=self.yaml_file) for field in config.fairseq:", "from mmpt.utils import recursive_config class BaseJob(object): def __init__(self, yaml_file, dryrun=False):", "def __init__(self, yaml_file, dryrun=False): self.yaml_file = yaml_file self.config = recursive_config(yaml_file)", "\"--criterion\", \"mmloss\", ], \"local_small\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\",", "tree. import os from mmpt.utils import recursive_config class BaseJob(object): def", "# # This source code is licensed under the MIT", "in [\"local_single\", \"local_small\"]: if self.config.fairseq.dataset.batch_size > 32: print(\"decreasing batch_size to", "= load_config(config_file=self.yaml_file) for field in config.fairseq: for key in config.fairseq[field]:", "= recursive_config(yaml_file) self.dryrun = dryrun def submit(self, **kwargs): raise NotImplementedError", "self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if \"predict\" not in self.job_type: # append fairseq args.", "value = str(config.fairseq[field][key][0]) elif key == \"adam_betas\": value = \"'\"+str(config.fairseq[field][key])+\"'\"", "str(config.fairseq[field][key][0]) elif key == \"adam_betas\": value = \"'\"+str(config.fairseq[field][key])+\"'\" else: value", "def _normalize_cmd(self, cmd_list): cmd_list = list(cmd_list) yaml_index = cmd_list.index(\"[yaml]\") cmd_list[yaml_index]", "list(cmd_list) yaml_index = cmd_list.index(\"[yaml]\") cmd_list[yaml_index] = self.yaml_file return cmd_list class", "key == \"lr\": value = str(config.fairseq[field][key][0]) elif key == \"adam_betas\":", "from mmpt.utils import load_config config = load_config(config_file=self.yaml_file) for field in", "\"mmpt_cli/predict.py\", \"[yaml]\"], } def __init__(self, yaml_file, job_type=None, dryrun=False): super().__init__(yaml_file, dryrun)", "MIT license found in the # LICENSE file in the", "affiliates. # # This source code is licensed under the", "Inc. and its affiliates. # # This source code is", "__init__(self, yaml_file, dryrun=False): self.yaml_file = yaml_file self.config = recursive_config(yaml_file) self.dryrun", "yaml_file, dryrun=False): self.yaml_file = yaml_file self.config = recursive_config(yaml_file) self.dryrun =", "recursive_config class BaseJob(object): def __init__(self, yaml_file, dryrun=False): self.yaml_file = yaml_file", "self.yaml_file = yaml_file self.config = recursive_config(yaml_file) self.dryrun = dryrun def", "self.dryrun = dryrun def submit(self, **kwargs): raise NotImplementedError def _normalize_cmd(self,", "\"local_big\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\",", "\"--distributed-world-size\", \"4\" ], \"local_predict\": [\"python\", \"mmpt_cli/predict.py\", \"[yaml]\"], } def __init__(self,", "def running(self): return False def result(self): if self.done(): return \"{}", "def result(self): if self.done(): return \"{} is done.\".format(self.job_id) else: return", "def __init__(self, job_id): self.job_id = job_id def __repr__(self): return self.job_id", "self.yaml_file return cmd_list class LocalJob(BaseJob): CMD_CONFIG = { \"local_single\": [", "class BaseJob(object): def __init__(self, yaml_file, dryrun=False): self.yaml_file = yaml_file self.config", "# This source code is licensed under the MIT license", "\"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"4\" ], \"local_predict\": [\"python\", \"mmpt_cli/predict.py\", \"[yaml]\"],", "return False def result(self): if self.done(): return \"{} is done.\".format(self.job_id)", "\"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", ], \"local_small\":", "cmd_list = self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if \"predict\" not in self.job_type: # append", "\"predict\" not in self.job_type: # append fairseq args. from mmpt.utils", "value = \"'\"+str(config.fairseq[field][key])+\"'\" else: value = str(config.fairseq[field][key]) param = [", "\"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"2\" ], \"local_big\": [ \"fairseq-train\",", "root directory of this source tree. import os from mmpt.utils", "\"mmarch\", \"--criterion\", \"mmloss\", ], \"local_small\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\",", "key in config.fairseq[field]: if key in [\"fp16\", \"reset_optimizer\", \"reset_dataloader\", \"reset_meters\"]:", "in [\"fp16\", \"reset_optimizer\", \"reset_dataloader\", \"reset_meters\"]: # a list of binary", "a list of binary flag. param = [\"--\" + key.replace(\"_\",", "os.system(\" \".join(cmd_list)) return JobStatus(\"12345678\") class JobStatus(object): def __init__(self, job_id): self.job_id", "local testing?\") def submit(self): cmd_list = self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if \"predict\" not", "result(self): if self.done(): return \"{} is done.\".format(self.job_id) else: return \"{}", "\"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"4\"", "testing?\") def submit(self): cmd_list = self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if \"predict\" not in", "\"-\"), value ] cmd_list.extend(param) print(\"launching\", \" \".join(cmd_list)) if not self.dryrun:", "def __str__(self): return self.job_id def done(self): return False def running(self):", "def submit(self): cmd_list = self._normalize_cmd(LocalJob.CMD_CONFIG[self.job_type]) if \"predict\" not in self.job_type:", "\"lr\": value = str(config.fairseq[field][key][0]) elif key == \"adam_betas\": value =", "in self.job_type: # append fairseq args. from mmpt.utils import load_config", "\"mmloss\", \"--distributed-world-size\", \"4\" ], \"local_predict\": [\"python\", \"mmpt_cli/predict.py\", \"[yaml]\"], } def", "return \"{} is running.\".format(self.job_id) def stderr(self): return self.result() def stdout(self):", "super().__init__(yaml_file, dryrun) if job_type is None: self.job_type = \"local_single\" if", "[ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\",", "cmd_list): cmd_list = list(cmd_list) yaml_index = cmd_list.index(\"[yaml]\") cmd_list[yaml_index] = self.yaml_file", "if key == \"lr\": value = str(config.fairseq[field][key][0]) elif key ==", "\"{} is running.\".format(self.job_id) def stderr(self): return self.result() def stdout(self): return", "load_config(config_file=self.yaml_file) for field in config.fairseq: for key in config.fairseq[field]: if", "\"2\" ], \"local_big\": [ \"fairseq-train\", \"[yaml]\", \"--user-dir\", \"mmpt\", \"--task\", \"mmtask\",", "return self.job_id def done(self): return False def running(self): return False", "self.job_type = job_type if self.job_type in [\"local_single\", \"local_small\"]: if self.config.fairseq.dataset.batch_size", "of this source tree. import os from mmpt.utils import recursive_config", "\"mmpt\", \"--task\", \"mmtask\", \"--arch\", \"mmarch\", \"--criterion\", \"mmloss\", \"--distributed-world-size\", \"2\" ]," ]
[ "], initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, name=name, encoder=e, decoder=d, logDir=os.path.join(g.logDir, name), debug=1)", "version', 'show users', 'show time', 'show status', 'show inst/full', 'show", "stripChars='\\n', CIDfirst=False, debug=1) e = ASCIICmdEncoder(EOL='\\r', debug=1, CIDfirst=False) tcc =", "import ASCIIReplyDecoder name = 'tcc' def start(poller): stop() initCmds =", "initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, name=name, encoder=e, decoder=d, logDir=os.path.join(g.logDir, name), debug=1) hub.addActor(tcc)", "name=name, encoder=e, decoder=d, logDir=os.path.join(g.logDir, name), debug=1) hub.addActor(tcc) def stop(): n", "needsAuth=True, name=name, encoder=e, decoder=d, logDir=os.path.join(g.logDir, name), debug=1) hub.addActor(tcc) def stop():", "axisconfig', 'show focus', 'axis status', 'show scale', 'mir status') safeCmds", "'show inst/full', 'show object/full', 'show axisconfig', 'show focus', 'axis status',", "'show time', 'show status', 'show inst/full', 'show object/full', 'show axisconfig',", "'show users', 'show time', 'show status', 'show inst/full', 'show object/full',", "= ('show version', 'show users', 'show time', 'show status', 'show", "tron.Hub.Nub.TCCShellNub import TCCShellNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'tcc'", "from tron.Hub.Nub.TCCShellNub import TCCShellNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name =", "name = 'tcc' def start(poller): stop() initCmds = ('show version',", "import TCCShellNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'tcc' def", "tcc = TCCShellNub(poller, [ '/usr/bin/ssh', '-1', '-e', 'none', '-a', '-x',", "CIDfirst=False, debug=1) e = ASCIICmdEncoder(EOL='\\r', debug=1, CIDfirst=False) tcc = TCCShellNub(poller,", "debug=1) hub.addActor(tcc) def stop(): n = hub.findActor(name) if n: hub.dropActor(n)", "debug=1) e = ASCIICmdEncoder(EOL='\\r', debug=1, CIDfirst=False) tcc = TCCShellNub(poller, [", "from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'tcc' def start(poller): stop()", "status', 'show inst/full', 'show object/full', 'show axisconfig', 'show focus', 'axis", "inst/full', 'show object/full', 'show axisconfig', 'show focus', 'axis status', 'show", "tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.TCCShellNub", "TCCShellNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'tcc' def start(poller):", "'none', '-a', '-x', '-i', os.path.expanduser('~/.ssh/tron'), '-T', 'tccuser@tcc25m' ], initCmds=initCmds, safeCmds=safeCmds,", "import os.path from tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import", "'tcc' def start(poller): stop() initCmds = ('show version', 'show users',", "= ASCIICmdEncoder(EOL='\\r', debug=1, CIDfirst=False) tcc = TCCShellNub(poller, [ '/usr/bin/ssh', '-1',", "'show status', 'show inst/full', 'show object/full', 'show axisconfig', 'show focus',", "users', 'show time', 'show status', 'show inst/full', 'show object/full', 'show", "'show focus', 'axis status', 'show scale', 'mir status') safeCmds =", "ASCIICmdEncoder from tron.Hub.Nub.TCCShellNub import TCCShellNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name", "import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.TCCShellNub import", "('show version', 'show users', 'show time', 'show status', 'show inst/full',", "d = ASCIIReplyDecoder(EOL='\\r', stripChars='\\n', CIDfirst=False, debug=1) e = ASCIICmdEncoder(EOL='\\r', debug=1,", "from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.TCCShellNub import TCCShellNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder", "= r'(^show )|(status$)' d = ASCIIReplyDecoder(EOL='\\r', stripChars='\\n', CIDfirst=False, debug=1) e", "g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.TCCShellNub import TCCShellNub", "name), debug=1) hub.addActor(tcc) def stop(): n = hub.findActor(name) if n:", "= TCCShellNub(poller, [ '/usr/bin/ssh', '-1', '-e', 'none', '-a', '-x', '-i',", "'-e', 'none', '-a', '-x', '-i', os.path.expanduser('~/.ssh/tron'), '-T', 'tccuser@tcc25m' ], initCmds=initCmds,", "r'(^show )|(status$)' d = ASCIIReplyDecoder(EOL='\\r', stripChars='\\n', CIDfirst=False, debug=1) e =", "encoder=e, decoder=d, logDir=os.path.join(g.logDir, name), debug=1) hub.addActor(tcc) def stop(): n =", "time', 'show status', 'show inst/full', 'show object/full', 'show axisconfig', 'show", ")|(status$)' d = ASCIIReplyDecoder(EOL='\\r', stripChars='\\n', CIDfirst=False, debug=1) e = ASCIICmdEncoder(EOL='\\r',", "os.path from tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder", "= 'tcc' def start(poller): stop() initCmds = ('show version', 'show", "scale', 'mir status') safeCmds = r'(^show )|(status$)' d = ASCIIReplyDecoder(EOL='\\r',", "'show axisconfig', 'show focus', 'axis status', 'show scale', 'mir status')", "status', 'show scale', 'mir status') safeCmds = r'(^show )|(status$)' d", "hub.addActor(tcc) def stop(): n = hub.findActor(name) if n: hub.dropActor(n) del", "tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'tcc' def start(poller): stop() initCmds", "ASCIICmdEncoder(EOL='\\r', debug=1, CIDfirst=False) tcc = TCCShellNub(poller, [ '/usr/bin/ssh', '-1', '-e',", "stop() initCmds = ('show version', 'show users', 'show time', 'show", "decoder=d, logDir=os.path.join(g.logDir, name), debug=1) hub.addActor(tcc) def stop(): n = hub.findActor(name)", "from tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from", "object/full', 'show axisconfig', 'show focus', 'axis status', 'show scale', 'mir", "start(poller): stop() initCmds = ('show version', 'show users', 'show time',", "logDir=os.path.join(g.logDir, name), debug=1) hub.addActor(tcc) def stop(): n = hub.findActor(name) if", "initCmds = ('show version', 'show users', 'show time', 'show status',", "'show scale', 'mir status') safeCmds = r'(^show )|(status$)' d =", "ASCIIReplyDecoder(EOL='\\r', stripChars='\\n', CIDfirst=False, debug=1) e = ASCIICmdEncoder(EOL='\\r', debug=1, CIDfirst=False) tcc", "hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.TCCShellNub import TCCShellNub from", "focus', 'axis status', 'show scale', 'mir status') safeCmds = r'(^show", "import ASCIICmdEncoder from tron.Hub.Nub.TCCShellNub import TCCShellNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder", "debug=1, CIDfirst=False) tcc = TCCShellNub(poller, [ '/usr/bin/ssh', '-1', '-e', 'none',", "TCCShellNub(poller, [ '/usr/bin/ssh', '-1', '-e', 'none', '-a', '-x', '-i', os.path.expanduser('~/.ssh/tron'),", "'axis status', 'show scale', 'mir status') safeCmds = r'(^show )|(status$)'", "'-1', '-e', 'none', '-a', '-x', '-i', os.path.expanduser('~/.ssh/tron'), '-T', 'tccuser@tcc25m' ],", "'-a', '-x', '-i', os.path.expanduser('~/.ssh/tron'), '-T', 'tccuser@tcc25m' ], initCmds=initCmds, safeCmds=safeCmds, needsAuth=True,", "e = ASCIICmdEncoder(EOL='\\r', debug=1, CIDfirst=False) tcc = TCCShellNub(poller, [ '/usr/bin/ssh',", "safeCmds=safeCmds, needsAuth=True, name=name, encoder=e, decoder=d, logDir=os.path.join(g.logDir, name), debug=1) hub.addActor(tcc) def", "def start(poller): stop() initCmds = ('show version', 'show users', 'show", "def stop(): n = hub.findActor(name) if n: hub.dropActor(n) del n", "'show object/full', 'show axisconfig', 'show focus', 'axis status', 'show scale',", "status') safeCmds = r'(^show )|(status$)' d = ASCIIReplyDecoder(EOL='\\r', stripChars='\\n', CIDfirst=False,", "'tccuser@tcc25m' ], initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, name=name, encoder=e, decoder=d, logDir=os.path.join(g.logDir, name),", "tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.TCCShellNub import TCCShellNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import", "safeCmds = r'(^show )|(status$)' d = ASCIIReplyDecoder(EOL='\\r', stripChars='\\n', CIDfirst=False, debug=1)", "CIDfirst=False) tcc = TCCShellNub(poller, [ '/usr/bin/ssh', '-1', '-e', 'none', '-a',", "'-x', '-i', os.path.expanduser('~/.ssh/tron'), '-T', 'tccuser@tcc25m' ], initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, name=name,", "'/usr/bin/ssh', '-1', '-e', 'none', '-a', '-x', '-i', os.path.expanduser('~/.ssh/tron'), '-T', 'tccuser@tcc25m'", "ASCIIReplyDecoder name = 'tcc' def start(poller): stop() initCmds = ('show", "= ASCIIReplyDecoder(EOL='\\r', stripChars='\\n', CIDfirst=False, debug=1) e = ASCIICmdEncoder(EOL='\\r', debug=1, CIDfirst=False)", "'mir status') safeCmds = r'(^show )|(status$)' d = ASCIIReplyDecoder(EOL='\\r', stripChars='\\n',", "'-T', 'tccuser@tcc25m' ], initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, name=name, encoder=e, decoder=d, logDir=os.path.join(g.logDir,", "os.path.expanduser('~/.ssh/tron'), '-T', 'tccuser@tcc25m' ], initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, name=name, encoder=e, decoder=d,", "[ '/usr/bin/ssh', '-1', '-e', 'none', '-a', '-x', '-i', os.path.expanduser('~/.ssh/tron'), '-T',", "'-i', os.path.expanduser('~/.ssh/tron'), '-T', 'tccuser@tcc25m' ], initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, name=name, encoder=e," ]
[ "PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\") PtDb.init() print PtDb.init().getAll(\"select * from orders\") print PtDb.init().getOne(\"select", "}, 'default1':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'<PASSWORD>', 'charset':'utf8', },", "python # -*- coding=utf-8 -*- ''' Created on 2013-3-31 @author:", "'default':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'root', 'charset':'utf8', }, 'default1':{", "<gh_stars>1-10 #!/usr/bin/env python # -*- coding=utf-8 -*- ''' Created on", "__name__ == '__main__': PtDb.config = { 'sqlite':{ 'type':'sqlite', 'dbname':\"data1.db\" },", "-*- coding=utf-8 -*- ''' Created on 2013-3-31 @author: Joseph '''", "PtDb.config = { 'sqlite':{ 'type':'sqlite', 'dbname':\"data1.db\" }, 'default':{ 'type':'mysql', 'host':'localhost',", "@author: Joseph ''' import PtDb if __name__ == '__main__': PtDb.config", "-*- ''' Created on 2013-3-31 @author: Joseph ''' import PtDb", "# -*- coding=utf-8 -*- ''' Created on 2013-3-31 @author: Joseph", "'__main__': PtDb.config = { 'sqlite':{ 'type':'sqlite', 'dbname':\"data1.db\" }, 'default':{ 'type':'mysql',", "#!/usr/bin/env python # -*- coding=utf-8 -*- ''' Created on 2013-3-31", "= { 'sqlite':{ 'type':'sqlite', 'dbname':\"data1.db\" }, 'default':{ 'type':'mysql', 'host':'localhost', 'port':3306,", "'charset':'utf8', }, } PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\") PtDb.init() print PtDb.init().getAll(\"select * from", "PtDb if __name__ == '__main__': PtDb.config = { 'sqlite':{ 'type':'sqlite',", "== '__main__': PtDb.config = { 'sqlite':{ 'type':'sqlite', 'dbname':\"data1.db\" }, 'default':{", "'dbpass':'<PASSWORD>', 'charset':'utf8', }, } PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\") PtDb.init() print PtDb.init().getAll(\"select *", "'dbpass':'root', 'charset':'utf8', }, 'default1':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'<PASSWORD>',", "} PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\") PtDb.init() print PtDb.init().getAll(\"select * from orders\") print", "Created on 2013-3-31 @author: Joseph ''' import PtDb if __name__", "on 2013-3-31 @author: Joseph ''' import PtDb if __name__ ==", "}, } PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\") PtDb.init() print PtDb.init().getAll(\"select * from orders\")", "if __name__ == '__main__': PtDb.config = { 'sqlite':{ 'type':'sqlite', 'dbname':\"data1.db\"", "''' import PtDb if __name__ == '__main__': PtDb.config = {", "'dbuser':'root', 'dbpass':'root', 'charset':'utf8', }, 'default1':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root',", "{ 'sqlite':{ 'type':'sqlite', 'dbname':\"data1.db\" }, 'default':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev',", "'type':'sqlite', 'dbname':\"data1.db\" }, 'default':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'root',", "Joseph ''' import PtDb if __name__ == '__main__': PtDb.config =", "'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'<PASSWORD>', 'charset':'utf8', }, } PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\")", "PtDb.init('sqlite').open(\"test1.db\") PtDb.init() print PtDb.init().getAll(\"select * from orders\") print PtDb.init().getOne(\"select *", "PtDb.init().getAll(\"select * from orders\") print PtDb.init().getOne(\"select * from orders limit", "'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'<PASSWORD>', 'charset':'utf8', }, } PtDb.init('sqlite').open(\"test.db\")", "'charset':'utf8', }, 'default1':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'<PASSWORD>', 'charset':'utf8',", "2013-3-31 @author: Joseph ''' import PtDb if __name__ == '__main__':", "print PtDb.init().getAll(\"select * from orders\") print PtDb.init().getOne(\"select * from orders", "* from orders\") print PtDb.init().getOne(\"select * from orders limit 1\")", "'dbname':\"data1.db\" }, 'default':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'root', 'charset':'utf8',", "}, 'default':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'root', 'charset':'utf8', },", "'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'root', 'charset':'utf8', }, 'default1':{ 'type':'mysql', 'host':'localhost', 'port':3306,", "'dbuser':'root', 'dbpass':'<PASSWORD>', 'charset':'utf8', }, } PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\") PtDb.init() print PtDb.init().getAll(\"select", "coding=utf-8 -*- ''' Created on 2013-3-31 @author: Joseph ''' import", "''' Created on 2013-3-31 @author: Joseph ''' import PtDb if", "'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'root', 'charset':'utf8', }, 'default1':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev',", "'default1':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'<PASSWORD>', 'charset':'utf8', }, }", "'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'<PASSWORD>', 'charset':'utf8', }, } PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\") PtDb.init()", "PtDb.init() print PtDb.init().getAll(\"select * from orders\") print PtDb.init().getOne(\"select * from", "'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'<PASSWORD>', 'charset':'utf8', }, } PtDb.init('sqlite').open(\"test.db\") PtDb.init('sqlite').open(\"test1.db\") PtDb.init() print", "'sqlite':{ 'type':'sqlite', 'dbname':\"data1.db\" }, 'default':{ 'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root',", "import PtDb if __name__ == '__main__': PtDb.config = { 'sqlite':{", "'type':'mysql', 'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'root', 'charset':'utf8', }, 'default1':{ 'type':'mysql',", "'host':'localhost', 'port':3306, 'dbname':'game110_dev', 'dbuser':'root', 'dbpass':'root', 'charset':'utf8', }, 'default1':{ 'type':'mysql', 'host':'localhost'," ]
[ "files: file_path = os.path.join(folder_path, file) with open(file_path, 'w') as f:", "normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder = os.path.join(download_folder, download_prefix_no_slash) files_compared = 0 for dir_name,", "create_bucket_request.name]) if num_objects_to_delete >= 1000: confirm_prompt = 'WARNING: This command", "'--src-dir', root_bulk_put_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == []", "create_bucket_request.name) result = invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "== 1: # This is equivalent to a/ on the", "in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) @util.skip_while_rerecording def test_bulk_put_with_non_existent_folder(): fake_directory = 'tests/folder/not/exist' result", "you want to overwrite it?' in result.output assert set(parsed_result['skipped-objects']) ==", "= 'WARNING: This command will delete {} objects. Are you", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) ==", "def test_bulk_operation_table_output_query(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id =", "in our --include switches assert not os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2',", "'/a/Object_1' not in result.output assert 'Object_0' in result.output target_download_folder =", "directories on disk) for i in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if i %", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "filecmp.cmp(original_file, target_file, shallow=False) # Download a specific object with inclusions", "bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b/c/', '--delimiter', '/']) for object_name in", "def test_get_multipart(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id =", "is equivalent to a/ on the file system because we", "os.path.exists(target_file) assert filecmp.cmp(original_file, target_file, shallow=False) # Download a specific object", "Are you sure you wish to continue?'.format(num_objects_to_delete) else: confirm_prompt =", "'*.ps1', # Shouldn't match anything '--exclude', 'subfolder/subfolder2/xyz.jpg', '--exclude', 'subfolder/[spqr]lah.pdf' #", "'subfolder/subfolder2/xyz.jpg') ] # Check that we uploaded what we said", "'/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert 'thisisapath'", "assert '/a/Object_1' not in result.output assert 'Object_0' in result.output target_download_folder", "'5.bin'), os.path.join(large_file_verify_dir, '5.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'), os.path.join(large_file_verify_dir, '6.bin')) shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir)", "separators from the front to avoid unexpected results) object_name =", "--overwrite. There should be prompts result = invoke(['os', 'object', 'bulk-download',", "# Download a specific object with inclusions invoke([ 'os', 'object',", "vcr_fixture(request): with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield # Generate test data for different", "'--all']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with'", "# Bulk Get: create a new bucket and populate it", "util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_put_bucket_name = create_bucket_request.name", "create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result =", "'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request)", "paths on Windows. Using normpath converts these of # \"\\\"", "download_folder, '--prefix', 'bulk_put_prefix_test/']) actual_download_folder = os.path.join(download_folder, 'bulk_put_prefix_test') for dir_name, subdir_list,", "it. Assumes that nothing # comes after the JSON data", "0: # Put in one big file per subfolder util.create_large_file(file_path,", "'--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/*.png',", "import os import random import shutil import six import string", "shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording def test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_exclusion_test')", "= os.path.join('tests', 'temp', create_bucket_request.name) result = invoke([ 'os', 'object', 'bulk-download',", "bulk_get_bucket_name, '--dry-run', '--output', 'table', '--query', \"[?object=='Object_0'][object]\"]) assert 'action' not in", "for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder): for file in file_list:", "# Matches subfolder/blah.pdf '--include', '*/[ax]yz.jpg' # Matches subfolder/subfolder2/xyz.jpg ]) parsed_result", "downloaded_file_path = source_file_path.replace(source_folder, actual_download_folder) if downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash) in normalized_expected_uploaded_files: files_compared", "not in result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "exist'.format(fake_directory, fake_directory) in result.output @util.skip_while_rerecording def test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder = os.path.join('tests',", "objects. Are you sure you wish to continue?'.format(num_objects_to_delete) else: confirm_prompt", "MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path) else: with open(file_path, 'w') as f: f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield", "shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording def test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name =", "{} assert len(parsed_result['uploaded-objects']) == len(object_name_set) for object_name in object_name_set: assert", "get_count_of_files_in_folder_and_subfolders(directory): file_count = 0 for dir_name, subdir_list, file_list in os.walk(directory):", "files assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) # If", "inclusion_test_folder) assert os.path.exists(target_file) assert filecmp.cmp(original_file, target_file, shallow=False) # Download a", "the things and then deleting the buckets delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client,", "folder_path = os.path.join(inclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for file", "in six.iteritems(folders_to_files): folder_path = os.path.join(exclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path)", "download_folder=download_folder_base, download_prefix_no_slash='inclusion_test' ) # Download objects with inclusions to make", "assert '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf') in remaining_objects assert '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg') in remaining_objects", "= { 'a/b/c/d': [], 'a/b/c': [], 'a/b': [], '/a': [],", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder]) object_name_set = set() for", "# Check that we uploaded what we said we did", "files_compared = 0 for dir_name, subdir_list, file_list in os.walk(source_folder): for", "avoid unexpected results) object_name = '/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name) else: # At", "bulk_get_object_to_content = {} bulk_get_prefix_to_object = { 'a/b/c/d': [], 'a/b/c': [],", "'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', large_file_root_dir ])", "bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b']) for object_name in bulk_get_prefix_to_object['a/b']: file_path", "strings in the expected_uploaded_files array have a \"/\" in them,", "'--page-size', '3']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == 33 assert", "bulk_get_bucket_name, '--dry-run', '--output', 'table']) assert 'action' in result.output assert 'object'", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table', '--query',", "prefix=None, start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) for response", "rlah.pdf ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert", "== 3 result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "normalized_expected_uploaded_files: files_compared += 1 assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False)", "with open(file_path, 'w') as f: # For non-text extension types", "Normalize to # / in the paths (Windows can go", "in one big file per subfolder util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path) elif", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) #", "parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures'] ==", "as content_file: content = content_file.read() assert content == bulk_get_object_to_content[object_name] assert", "'testfile3.png')) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'test_file2.png'), os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png') ) assert", "'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder])", "assert filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'), os.path.join(large_file_verify_dir, '4.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'), os.path.join(large_file_verify_dir, '5.bin'))", "destination and they are equal) download_folder = 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os', 'object',", "create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000)) create_bucket_request.compartment_id = util.COMPARTMENT_ID", "'subfolder2', 'testfile4.png')) assert get_count_of_files_in_folder_and_subfolders(target_download_folder) == 2 assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png'))", "'*.jpg', '--exclude', 'subfolder/subfolder2/*.png', '--exclude', 'subfolder/blah.pdf', ]) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test',", "parse_json_response_from_mixed_output(result.output) assert len(parsed_result['skipped-objects']) == 0 shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_no_objects(vcr_fixture): download_folder", "'inclusion_test'), inclusion_test_folder) assert os.path.exists(target_file) assert filecmp.cmp(original_file, target_file, shallow=False) # Download", "the occasional file with a reasonable size so that we", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', large_file_verify_dir, '--multipart-download-threshold',", "than JSON in it. Assumes that nothing # comes after", "'subfolder', 'testfile3.png')) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'test_file2.png'), os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png') )", "request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None, start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True", "Try to upload with a part size of 10MiB (this", "% 5 == 2: object_name = 'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name) elif i", "be included because it's not slah.pdf, plah.pdf, qlah.pdf or rlah.pdf", "bucket_name=bulk_put_bucket_name, prefix='exclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) remaining_objects", "def parse_json_response_from_mixed_output(output): lines = output.split('\\n') json_str = '' object_begun =", "== oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\') assert 'thisisapath'", "= [] for response in list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name, response.data.objects))", "'2.bin'), os.path.join(large_file_verify_dir, '2.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'), os.path.join(large_file_verify_dir, '3.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir,", "the folders and files generated for bulk put @pytest.fixture(scope='module', autouse=True)", "names are taken from the file path of the thing", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) print(result.output) #", "len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We should skip over all objects", "mimetypes import guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET = 100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT = 20 CONTENT_STRING_LENGTH", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix',", "= 'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000)) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name)", "{} assert len(parsed_result['deleted-objects']) == num_objects_to_delete # Check that the bucket", "import pytest import oci import services.object_storage.src.oci_cli_object_storage as oci_cli_object_storage import os", "test_config_container.using_vcr_with_mock_responses(): return 'a' * length else: return ''.join(random.choice(string.ascii_lowercase) for i", "[] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client,", "'/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/') assert '/this/is/a/path'", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--dry-run']) parsed_result = json.loads(result.output)", "create_bucket_request.name, '--src-dir', large_file_root_dir ]) large_file_verify_dir = os.path.join('tests', 'temp', 'multipart_get_large_files_verify') invoke(['os',", "downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash) in normalized_expected_uploaded_files: files_compared += 1 assert os.path.exists(downloaded_file_path) assert", "= invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder,", "1000: confirm_prompt = 'WARNING: This command will delete at least", "def test_bulk_put_with_non_existent_folder(): fake_directory = 'tests/folder/not/exist' result = invoke(['os', 'object', 'bulk-upload',", "# Matches test_file1.txt, subfolder/hello.txt, subfolder/subfolder2/blag.txt '--include', 'subfolder/*.png', # Matches subfolder/testfile3.png,", "tear it all down afterwards # Bulk Put: create a", "for file in files: file_path = os.path.join(folder_path, file) with open(file_path,", "'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/subfolder2/*.png', '--exclude', 'subfolder/blah.pdf', ]) assert not", "len(expected_uploaded_files) for f in expected_uploaded_files: assert f in parsed_result['uploaded-objects'] download_folder_base", "'': ['test_file1.txt', 'test_file2.png'], 'subfolder': ['blah.pdf', 'hello.txt', 'testfile3.png'], 'subfolder/subfolder2': ['xyz.jpg', 'blag.txt',", "inclusions invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir',", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--overwrite'])", "download_prefix_no_slash) in normalized_expected_uploaded_files: files_compared += 1 assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path,", "items at various heirarchy levels (to be surfaced as different", "'WARNING: This command will delete {} objects. Are you sure", "'--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert", "test_delete_dry_run(vcr_fixture): # Dry-run against entire bucket result = invoke(['os', 'object',", "2016, 2019, Oracle and/or its affiliates. All rights reserved. import", "we're reporting back that we uploaded the right files assert", "skipped. There should be no prompts result = invoke(['os', 'object',", "deleting all the things and then deleting the buckets delete_bucket_and_all_items(object_storage_client,", "large files, then tear it all down afterwards # Bulk", "bulk_get_bucket_name, '--all', '--page-size', '20']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) ==", "= 5000 MID_SIZED_FILE_IN_MEBIBTYES = 20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 150 # Default", "== expected_objects # Dry-run against a folder and no subfolders", "be skipped. There should be prompts result = invoke(['os', 'object',", "the expected_uploaded_files array have a \"/\" in them, but this", "object_begun or line.startswith('{'): object_begun = True json_str += line return", "'--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure you want", "slash (we drop path separators from the front to avoid", "prompts result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "that the files match (everything in source appears in destination", "'test_file2.png'), os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png') ) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'subfolder', 'testfile3.png'),", "assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\') @util.skip_while_rerecording def test_get_all_objects_in_bucket(vcr_fixture): download_folder =", "= invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) assert 'There", "match (everything in source appears in destination and they are", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--part-size', '10' ])", "for object_name in bulk_get_prefix_to_object['a/b']: file_path = os.path.join(download_folder, object_name) with open(file_path,", "target_download_folder, '--output', 'table', ]) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) shutil.rmtree(target_download_folder) def invoke(commands, debug=False,", "from tests import test_config_container from mimetypes import guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET =", "all directories recursively shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording def test_normalize_object_name_path(): assert '/this/is/a/path' ==", "to # / in the paths (Windows can go both", "for euf in expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder = os.path.join(download_folder, download_prefix_no_slash) files_compared", "'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf = '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if not os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf) create_bucket_request =", "'20']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with'", "directories recursively shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording def test_normalize_object_name_path(): assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path')", "multipart uploaded) # - Try to upload with multipart disabled", "result = invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name,", "{} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder = 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os', 'object',", "== guess_type(downloaded_file_path) # Sanity check that we're reporting back that", "they are equal) download_folder = 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace',", "that we can verify results bulk_get_object_to_content = {} bulk_get_prefix_to_object =", "[] assert parsed_result['upload-failures'] == {} expected_uploaded_files = [ '{}{}'.format('inclusion_test/', 'test_file1.txt'),", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder]) num_objects_to_delete = get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder)", "target_download_folder = os.path.join('tests', 'temp', create_bucket_request.name) result = invoke([ 'os', 'object',", "'{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording def test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client):", "(when we breach the default of 128MiB) @util.skip_while_rerecording def test_bulk_put_default_options():", "'--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--force' ]) parsed_result =", "create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client,", "want to overwrite it?' in result.output assert set(parsed_result['skipped-objects']) == object_name_set", "overwrite it?' in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We", "mid-sized files to be multipart uploaded) # - Try to", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "assert 'Object_0' in result.output target_download_folder = os.path.join('tests', 'temp', create_bucket_request.name) result", "shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording def test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name", "util.NAMESPACE, '--bucket-name', create_bucket_request.name]) if num_objects_to_delete >= 1000: confirm_prompt = 'WARNING:", "util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', target_download_folder, '--output', 'table', ]) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name)", "that works target_download_folder = os.path.join(download_folder_base, 'get_with_include') invoke([ 'os', 'object', 'bulk-download',", "bulk_put_mid_sized_files, bulk_put_bucket_name # Create a test bucket create_bucket_request = oci.object_storage.models.CreateBucketDetails()", "'--multipart-download-threshold', '128']) assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) == 6 assert filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'), os.path.join(large_file_verify_dir,", "oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\') @util.skip_while_rerecording def test_get_all_objects_in_bucket(vcr_fixture):", "file, but for testing is probably OK f.write(generate_random_string(CONTENT_STRING_LENGTH)) result =", "obj in response.data.objects: object_storage_client.delete_object(util.NAMESPACE, bucket_name, obj.name) object_storage_client.delete_bucket(util.NAMESPACE, bucket_name) def get_number_of_objects_in_bucket(object_storage_client,", "= 'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name) elif i % 5 == 2: object_name", "expected_uploaded_files = [ '{}{}'.format('inclusion_test/', 'test_file1.txt'), '{}{}'.format('inclusion_test/', 'subfolder/hello.txt'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/',", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--overwrite']) parsed_result", "expected_uploaded_files array have a \"/\" in them, but this doesn't", "objects since we --overwrite result = invoke(['os', 'object', 'bulk-download', '--namespace',", "'--query', \"[?object=='Object_0'][object]\"]) assert 'action' not in result.output assert '/a/Object_1' not", "'--src-dir', root_bulk_put_folder]) # No failures or skips and we uploaded", "if not os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder) # Make some files for include/exclude", "result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all',", "'--prefix', 'a/b/c/', '--delimiter', '/']) for object_name in bulk_get_prefix_to_object['a/b/c']: file_path =", "'1.bin'), os.path.join(large_file_verify_dir, '1.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'), os.path.join(large_file_verify_dir, '2.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir,", "os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) for expected_file in expected_uploaded_files: target_file", "bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as content_file:", "still be included because it's not slah.pdf, plah.pdf, qlah.pdf or", "not exist'.format(fake_directory, fake_directory) in result.output @util.skip_while_rerecording def test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder =", "expected_uploaded_files: target_file = os.path.join(target_download_folder, expected_file) original_file = target_file.replace(os.path.join(target_download_folder, 'inclusion_test'), inclusion_test_folder)", "assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png')) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'test_file2.png'), os.path.join(target_download_folder,", "subfolder util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path) elif i != 0 and i", "shutil.rmtree(download_folder) @util.skip_while_rerecording def test_bulk_put_with_non_existent_folder(): fake_directory = 'tests/folder/not/exist' result = invoke(['os',", "'--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--object-prefix', 'bulk_put_prefix_test/']) # No failures or", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) parsed_result =", "'--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', 'subfolder/subfolder2/xyz.jpg' ]) assert", "in source appears in destination and they are equal) download_folder", "'--limit', '47']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == 47 assert", "'--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--dry-run']) parsed_result = json.loads(result.output) expected_objects =", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', large_file_verify_dir, '--multipart-download-threshold', '128']) assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir)", "a/b/<object>, a/b/c/<object> and a/b/c/d/<object> invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "'--part-size', '10' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == []", "download_folder]) object_name_set = set() for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder):", "create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client,", "assert len(remaining_objects) == 2 assert '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf') in remaining_objects assert", "full_path): return full_path.replace(os.sep, '/').replace(path_root + '/', '') def delete_bucket_and_all_items(object_storage_client, bucket_name):", "in result.output assert 'Object_0' in result.output target_download_folder = os.path.join('tests', 'temp',", "f: f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield # Tear down stuff by deleting all", "and i % OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT == 0: # Put in one", "with inclusions to make sure that works target_download_folder = os.path.join(download_folder_base,", "there should be no prompts result = invoke(['os', 'object', 'bulk-download',", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table']) assert 'action' in result.output", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', inclusion_test_folder, '--object-prefix', 'inclusion_test/', '--include',", "shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_multipart(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string())", "len(parsed_result['skipped-objects']) == 0 shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_no_objects(vcr_fixture): download_folder = 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name)", "'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder,", "a folder and all subfolders result = invoke(['os', 'object', 'bulk-delete',", "i % OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT == 0: # Put in one big", "'table', '--query', \"[?action=='Uploaded'].{file: file, \\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"]) assert 'file' in result.output", "root_bulk_put_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure you want", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) parsed_result =", "os.path.join(root_bulk_put_folder, subfolder) for i in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT + 1): file_path =", "over all objects since we say --no-overwrite. Additionally there should", "'subfolder/subfolder2/xyz.jpg')) # This is not in our --include switches assert", "stuff by deleting all the things and then deleting the", "'--overwrite' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert", "in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording def test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client): create_bucket_request =", "= invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/',", "'w') as f: # For non-text extension types this won't", "qlah.pdf or rlah.pdf ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] ==", "json import pytest import oci import services.object_storage.src.oci_cli_object_storage as oci_cli_object_storage import", "assert 'Are you sure you want to overwrite it?' in", "response in list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert len(remaining_objects) ==", "confirm_prompt in result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "download_prefix_no_slash): # Download uploaded files and check they are the", "assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == len(object_name_set) for object_name", "in file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, download_folder)", "(expanded to: {}) does not exist'.format(fake_directory, fake_directory) in result.output @util.skip_while_rerecording", "# The strings in the expected_uploaded_files array have a \"/\"", "'/', '') def delete_bucket_and_all_items(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None,", "num_objects_to_delete # Check that the bucket is now empty assert", "shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_no_objects(vcr_fixture): download_folder = 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download',", "os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'byz.jpg')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder',", "assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording def test_bulk_put_get_delete_with_exclusions(object_storage_client):", "== {} assert parsed_result['uploaded-objects'] == {} # Now we force", "with exclusions to make sure that works target_download_folder = os.path.join(download_folder_base,", "= oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='exclusion_test/', start=None, end=None, limit=1000,", "content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b']) + len(bulk_get_prefix_to_object['a/b/c']) + len(bulk_get_prefix_to_object['a/b/c/d']) ==", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'batman'])", "= 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir',", "create_bucket_request) large_file_root_dir = os.path.join('tests', 'temp', 'multipart_get_large_files') if not os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir)", "so that we can verify results bulk_get_object_to_content = {} bulk_get_prefix_to_object", "invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) assert 'There are", "{} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Pull everything down and", "should skip over all objects since there is no --overwrite.", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', '*.txt',", "'blah.pdf')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'byz.jpg')) assert not", "invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table',", "it's a good opportunity to test using the --all and", ") num_objects_in_bucket = 0 for response in list_object_responses: num_objects_in_bucket =", "filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'), os.path.join(large_file_verify_dir, '5.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'), os.path.join(large_file_verify_dir, '6.bin')) shutil.rmtree(large_file_root_dir)", "= [ '{}{}'.format('exclusion_test/', 'test_file2.png'), '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'),", "import services.object_storage.src.oci_cli_object_storage as oci_cli_object_storage import os import random import shutil", "'--bucket-name', bulk_get_bucket_name, '--all', '--page-size', '20']) parsed_result = json.loads(result.output) assert len(parsed_result['data'])", "Create a test bucket create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string())", "debug=False, ** args): if debug is True: commands = ['--debug']", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--content-type',", "we can force multipart util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path) else: with open(file_path,", "we uploaded the right files assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path)) in parsed_result['uploaded-objects']", "in result.output @util.skip_while_rerecording def test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_inclusion_test')", "have a \"/\" in them, but this doesn't match with", "'--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--no-multipart', '--overwrite' ]) parsed_result = parse_json_response_from_mixed_output(result.output)", "'subfolder', 'testfile3.png') ) # Delete objects with exclusions result =", "bulk_put_folder_leaf = '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if not os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf) create_bucket_request = oci.object_storage.models.CreateBucketDetails()", "to delete in {}'.format(create_bucket_request.name) in result.output delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def", "then tear it all down afterwards # Bulk Delete: uses", "os import random import shutil import six import string from", "start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) remaining_objects = []", "we create and their content so that we can verify", "assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder =", "in result.output assert 'The specified --src-dir {} (expanded to: {})", "'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png') ] # Check that we", "[], 'a/b': [], '/a': [], '': [] } bulk_get_bucket_name =", "= content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b']) + len(bulk_get_prefix_to_object['a/b/c'])", "oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID,", "= os.path.join(target_download_folder, expected_file) original_file = target_file.replace(os.path.join(target_download_folder, 'inclusion_test'), inclusion_test_folder) assert os.path.exists(target_file)", "continue?'.format(num_objects_to_delete) assert confirm_prompt in result.output result = invoke(['os', 'object', 'bulk-delete',", "and check they are the same invoke(['os', 'object', 'bulk-download', '--namespace',", "'/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\') assert", "= False for line in lines: if object_begun or line.startswith('{'):", "'--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects']", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "os.path.join(download_folder_base, 'get_with_include') invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='exclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name',", "create_bucket_request.name = 'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name)", "prefix=None, start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) num_objects_in_bucket =", "downloaded_file_path, shallow=False) assert guess_type(source_file_path) == guess_type(downloaded_file_path) # Sanity check that", "'--force']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert len(parsed_result['deleted-objects'])", "assert len(remaining_objects) == 3 assert '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png') in remaining_objects assert", "file system because we drop the leading slash (we drop", "uses multipart where appropriate (when we breach the default of", "overwrite it?' not in result.output assert set(parsed_result['skipped-objects']) == object_name_set assert", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', fake_directory]) assert 'UsageError' in result.output assert", "auto @util.skip_while_rerecording def test_bulk_put_auto_content_type(): result = invoke(['os', 'object', 'bulk-upload', '--namespace',", "file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, download_folder) assert", "get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_put_with_prefix(): result = invoke(['os', 'object',", "since we say --no-overwrite. Additionally there should be no prompts", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', large_file_root_dir ]) large_file_verify_dir =", ">= 1000: confirm_prompt = 'WARNING: This command will delete at", "[] assert parsed_result['upload-failures'] == {} expected_uploaded_files = [ '{}{}'.format('exclusion_test/', 'test_file2.png'),", "= 'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name) elif i % 5 == 1: #", "test_get_directory_and_subdirectories(vcr_fixture): download_folder = 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) # This should get us a/b/<object>,", "@util.skip_while_rerecording def test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(util.random_number_string())", "overwrite it?' in result.output assert set(parsed_result['skipped-objects']) == object_name_set assert parsed_result['upload-failures']", "test_get_directory_no_subdirectory(vcr_fixture): download_folder = 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, actual_download_folder) assert", "'subfolder/subfolder2/xyz.jpg', '--exclude', 'subfolder/[spqr]lah.pdf' # blah.pdf should still be included because", "i % 5 == 2: object_name = 'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name) elif", "'--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_result['skipped-objects'])", "--no-overwrite then everything should be skipped. There should be no", "]) assert os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) # Delete objects", "subfolder) for i in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT + 1): file_path = '{}/object_{}'.format(full_folder,", "= 150 # Default multipart is 128MiB # Holds the", "on the file system because we drop the leading slash", "file_list in os.walk(directory): file_count = file_count + len(file_list) return file_count", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--no-overwrite'])", "If we try and put it in the same bucket", "{} # Now we force it result = invoke(['os', 'object',", "os.path.join(inclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for file in files:", "for expected_file in expected_uploaded_files: target_file = os.path.join(target_download_folder, expected_file) original_file =", "download_folder = 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit',", "os.path.join(download_folder, object_name[1:]) else: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r')", "results) object_name = '/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name) else: # At the root", "'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all']) parsed_result = json.loads(result.output) assert", "part size of 10MiB (this will force the large and", "sure that works target_download_folder = os.path.join(download_folder_base, 'get_with_exclude') invoke([ 'os', 'object',", "'--include', 'subfolder/subfolder2/xyz.jpg' ]) assert os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) #", "dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder): for file in file_list: source_file_path", "'--include', 'subfolder/*.png', '--include', 'subfolder/blah.pdf', ]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')) # This is", "not in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We should", "content_file.read() assert content == bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c/d']: file_path", "assert set(parsed_result['deleted-objects']) == expected_objects # Dry-run against a folder and", "invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--force']) parsed_result =", "over no objects since we --overwrite result = invoke(['os', 'object',", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--output', 'table', '--query',", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', fake_directory]) assert 'UsageError'", "== 0: # Put in one big file per subfolder", "bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) # No failures or skips and we", "root_bulk_put_folder, '--no-multipart', '--overwrite' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] ==", "reporting back that we uploaded the right files assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder,", "lines: if object_begun or line.startswith('{'): object_begun = True json_str +=", "# We should skip over all objects since we say", "util.invoke_command(commands, ** args) def get_count_of_files_in_folder_and_subfolders(directory): file_count = 0 for dir_name,", "assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder = 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download',", "'--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--delimiter', '/', '--dry-run']) parsed_result = json.loads(result.output)", "'temp', 'os_bulk_upload_exclusion_test') if not os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder) # Make some files", "we say --no-overwrite. Additionally there should be no prompts result", "]) large_file_verify_dir = os.path.join('tests', 'temp', 'multipart_get_large_files_verify') invoke(['os', 'object', 'bulk-download', '--namespace',", "download_folder = 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result", "bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', download_prefix_no_slash + '/']) # The strings", "services.object_storage.src.oci_cli_object_storage as oci_cli_object_storage import os import random import shutil import", "download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) # Sanity check", "def test_get_files_skipped(): download_folder = 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "create_bucket_request.name, '--src-dir', root_bulk_put_folder]) num_objects_to_delete = get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Sanity check that", "Dry-run against entire bucket result = invoke(['os', 'object', 'bulk-delete', '--namespace',", "generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name, object_name, object_content) bulk_get_object_to_content[object_name] = object_content # makedirs", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', download_prefix_no_slash + '/']) #", "'multipart_get_large_files_verify') invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', large_file_verify_dir,", "are no objects to delete in {}'.format(create_bucket_request.name) in result.output delete_bucket_and_all_items(object_storage_client,", "for response in list_object_responses: for obj in response.data.objects: object_storage_client.delete_object(util.NAMESPACE, bucket_name,", ") # Delete objects with exclusions result = invoke([ 'os',", "subfolders result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "range(length)) # Pull JSON data out of output which may", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--output', 'table', '--query', \"[?action=='Uploaded'].{file:", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--no-overwrite']) parsed_result", "'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--no-multipart',", "'--download-dir', download_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure you", "== bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder, object_name)", "creates all subfolders recursively root_bulk_put_folder = 'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf = '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder)", "disabled @util.skip_while_rerecording def test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string())", "'--prefix', download_prefix_no_slash + '/']) # The strings in the expected_uploaded_files", "result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix',", "our matching/comparison works. For Linux/Unix/macOS this doesn't appear to have", "'blag.txt', 'byz.jpg', 'testfile4.png'] } for folder, files in six.iteritems(folders_to_files): folder_path", "to have an impact normalized_expected_uploaded_files = [] for euf in", "filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'), os.path.join(large_file_verify_dir, '2.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'), os.path.join(large_file_verify_dir, '3.bin')) assert", "testing is probably OK f.write(generate_random_string(CONTENT_STRING_LENGTH)) result = invoke([ 'os', 'object',", "'*.txt', '--include', 'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures']", "of output which may have stuff other than JSON in", "'--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--force' ])", "bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'batman']) assert 0 == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder)", "'--include', 'subfolder/*.png', # Matches subfolder/testfile3.png, subfolder/subfolder2/testfile4.png '--include', 'subfolder/[b]lah.pdf', # Matches", "remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording def test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails()", "'6.bin'), 1) # Creates a 1 MiB file for variety", "Matches subfolder/testfile3.png, subfolder/subfolder2/testfile4.png '--include', 'subfolder/[b]lah.pdf', # Matches subfolder/blah.pdf '--include', '*/[ax]yz.jpg'", "namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='inclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True )", "bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] ==", "'--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/*.png', '--include', 'subfolder/blah.pdf', ]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/',", "= '' object_begun = False for line in lines: if", "0 == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_multipart(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails()", "say to --no-overwrite then everything should be skipped. There should", "'--delimiter', '/']) for object_name in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder, object_name)", "= 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE,", "file_path = os.path.join(folder_path, file) with open(file_path, 'w') as f: #", "on disk) for i in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if i % 5", "'inclusion_test/', '--include', '*.txt', # Matches test_file1.txt, subfolder/hello.txt, subfolder/subfolder2/blag.txt '--include', 'subfolder/*.png',", "get_count_of_files_in_folder_and_subfolders(target_download_folder) == 2 assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png')) assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test',", "'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\') @util.skip_while_rerecording", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) parsed_result = parse_json_response_from_mixed_output(result.output)", "parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) ==", "f in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files,", "'--include', 'subfolder/blah.pdf', ]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')) # This is not in", "json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with' not in result.output", "not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'blah.pdf')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder',", "line return json.loads(json_str) # For the bulk operations, object names", "--limit parameters @util.skip_while_rerecording def test_list_all_objects_operations(vcr_fixture): result = invoke(['os', 'object', 'list',", "reporting back that we uploaded the right files assert get_object_name_from_path(root_bulk_put_folder,", "bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', 'bulk_put_prefix_test/']) actual_download_folder = os.path.join(download_folder, 'bulk_put_prefix_test') for", "== bulk_get_object_to_content[object_name] assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_and_subdirectories(vcr_fixture):", "bulk_put_bucket_name = create_bucket_request.name subfolders = ['', 'subfolder1', 'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3'] for", "test suite, it's a good opportunity to test using the", "os.path.join('tests', 'temp', 'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='inclusion_test' ) #", "a good opportunity to test using the --all and --limit", "object_name[1:]) else: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as", "exclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_exclusion_test') if not os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder) #", "object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID", "'exclusion_test', 'subfolder', 'subfolder2', 'byz.jpg')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2',", "== '': full_folder = root_bulk_put_folder else: full_folder = os.path.join(root_bulk_put_folder, subfolder)", "oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath',", "file_count = 0 for dir_name, subdir_list, file_list in os.walk(directory): file_count", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', target_download_folder, '--output', 'table',", "'subfolder/subfolder2/byz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording def test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client): create_bucket_request", "and no subfolders result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "object_name = 'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name) object_content = generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name, object_name,", "content_file: content = content_file.read() assert content == bulk_get_object_to_content[object_name] for object_name", "no --overwrite. There should be prompts result = invoke(['os', 'object',", "in the paths (Windows can go both ways) then chop", "not in result.output assert '/a/Object_1' not in result.output assert 'Object_0'", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf',", "There should be prompts result = invoke(['os', 'object', 'bulk-upload', '--namespace',", "assert parsed_result['delete-failures'] == {} assert set(parsed_result['deleted-objects']) == set(parsed_dry_run_result['deleted-objects']) list_objects_responses =", "we uploaded the right files assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects']", "chop the front bit off def get_object_name_from_path(path_root, full_path): return full_path.replace(os.sep,", "]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert set(parsed_result['deleted-objects'])", "upload with multipart disabled @util.skip_while_rerecording def test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails()", "remaining_objects = [] for response in list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name,", "= util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) invoke(['os', 'object',", "LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES)", "oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID,", "and verify that the files match (everything in source appears", "after the JSON data def parse_json_response_from_mixed_output(output): lines = output.split('\\n') json_str", "= 'tests/folder/not/exist' result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "os.path.join(large_file_verify_dir, '6.bin')) shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) # Since we've created", "= json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording def test_delete(object_storage_client): create_bucket_request", "the paths (Windows can go both ways) then chop the", "= None bulk_put_bucket_name = None @pytest.fixture def vcr_fixture(request): with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)):", "def test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id", "in lines: if object_begun or line.startswith('{'): object_begun = True json_str", "is no --overwrite. There should be prompts result = invoke(['os',", "'--bucket-name', bulk_put_bucket_name, '--src-dir', fake_directory]) assert 'UsageError' in result.output assert 'The", "six import string from tests import util from tests import", "in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder,", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder]) object_name_set = set() for dir_name,", "= create_bucket_request.name subfolders = ['', 'subfolder1', 'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3'] for subfolder", "for object_name in bulk_get_object_to_content: if object_name[0] == '/' or object_name[0]", "os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder) # Make some files for include/exclude folders_to_files =", "files assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path)) in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) @util.skip_while_rerecording def test_bulk_put_with_non_existent_folder():", "create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) large_file_root_dir", "we try and put it in the same bucket without", "'subfolder': ['blah.pdf', 'hello.txt', 'testfile3.png'], 'subfolder/subfolder2': ['xyz.jpg', 'blag.txt', 'byz.jpg', 'testfile4.png'] }", "len(parsed_result['deleted-objects']) == num_objects_to_delete # Check that the bucket is now", "if downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash) in normalized_expected_uploaded_files: files_compared += 1 assert os.path.exists(downloaded_file_path)", "[] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder", "# Bulk Put: create a folder structure containing small and", "root_bulk_put_folder, '--object-prefix', 'bulk_put_prefix_test/']) # No failures or skips and we", "assert set(parsed_result['deleted-objects']) == set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording def test_delete(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails()", "bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c/d']: file_path = os.path.join(download_folder, object_name) with", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder]) object_name_set =", "file_list in os.walk(root_bulk_put_folder): for file in file_list: source_file_path = os.path.join(dir_name,", "0 result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name])", "== 0: # Put in the occasional file with a", "@util.skip_while_rerecording def test_get_directory_and_subdirectories(vcr_fixture): download_folder = 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) # This should get", "All rights reserved. import filecmp import json import pytest import", "assert len(parsed_result['data']) == 47 assert 'next-start-with' in result.output result =", "'--src-dir', root_bulk_put_folder, '--object-prefix', 'bulk_put_prefix_test/']) # No failures or skips and", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--dry-run']) parsed_result", "{} expected_uploaded_files = [ '{}{}'.format('inclusion_test/', 'test_file1.txt'), '{}{}'.format('inclusion_test/', 'subfolder/hello.txt'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'),", "MiB file for variety invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "== {} assert set(parsed_result['deleted-objects']) == set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client,", "== num_objects_to_delete # Check that the bucket is now empty", "def get_count_of_files_in_folder_and_subfolders(directory): file_count = 0 for dir_name, subdir_list, file_list in", "assert len(parsed_dry_run_result['deleted-objects']) == 4 result = invoke([ 'os', 'object', 'bulk-delete',", "root_bulk_put_folder = None bulk_put_bucket_name = None @pytest.fixture def vcr_fixture(request): with", "= oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE,", "result.output assert '/a/Object_1' not in result.output assert 'Object_0' in result.output", "--src-dir {} (expanded to: {}) does not exist'.format(fake_directory, fake_directory) in", "== bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c/d']: file_path = os.path.join(download_folder, object_name)", "file in file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(source_folder,", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--dry-run'", "result.output assert 'Object_0' in result.output target_download_folder = os.path.join('tests', 'temp', create_bucket_request.name)", "folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for file in files: file_path", "obj.name, response.data.objects)) assert len(remaining_objects) == 3 assert '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png') in", "This should get us a/b/<object>, a/b/c/<object> and a/b/c/d/<object> invoke(['os', 'object',", "we --overwrite result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "== {} # Now we force it result = invoke(['os',", "'--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--content-type', 'auto', '--overwrite']) # No failures", "actual_download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) # Sanity check", "'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {}", "assert 'next-start-with' in result.output result = invoke(['os', 'object', 'list', '--namespace',", "in response.data.objects: object_storage_client.delete_object(util.NAMESPACE, bucket_name, obj.name) object_storage_client.delete_bucket(util.NAMESPACE, bucket_name) def get_number_of_objects_in_bucket(object_storage_client, bucket_name):", "to avoid unexpected results) object_name = '/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name) else: #", "uploaded everything parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert", "files, then tear it all down afterwards # Bulk Delete:", "and mid-sized files to be multipart uploaded) # - Try", "object_name = '/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name) else: # At the root of", "object_name in bulk_get_object_to_content: if object_name[0] == '/' or object_name[0] ==", "bulk_put_bucket_name, '--src-dir', exclusion_test_folder, '--object-prefix', 'exclusion_test/', '--exclude', '*.txt', '--exclude', '*.ps1', #", "util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke([ 'os', 'object', 'bulk-upload',", "source appears in destination and they are equal) download_folder =", "os.makedirs(bulk_put_folder_leaf) create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID", "bucket and populate it with some objects, then tear it", "'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) # This should get us a/b/<object>, a/b/c/<object> and a/b/c/d/<object>", "= json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_object_to_content.keys()) # Dry-run against a", "delete {} objects. Are you sure you wish to continue?'.format(num_objects_to_delete)", "leading slash (we drop path separators from the front to", "= invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder,", "for subfolder in subfolders: if subfolder == '': full_folder =", "2 assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png')) assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png'))", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) # No failures", "a/ on the file system because we drop the leading", "objects since there is no --overwrite. There should be prompts", "oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000)) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE,", "'--download-dir', download_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_result['skipped-objects']) == 0", "= content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b/c']) == get_count_of_files_in_folder_and_subfolders(download_folder)", "'--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "This is equivalent to a/ on the file system because", "# - Try to upload with multipart disabled @util.skip_while_rerecording def", "result.output # Bulk puts objects, uses multipart where appropriate (when", "]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures']", "parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == len(object_name_set) for object_name in", "elif i % 5 == 1: # This is equivalent", "but this doesn't match with paths on Windows. Using normpath", "force multipart util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path) else: with open(file_path, 'w') as", "util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) large_file_root_dir = os.path.join('tests', 'temp', 'multipart_get_large_files') if", "assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b/c']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording", "= file_count + len(file_list) return file_count def generate_random_string(length): if test_config_container.using_vcr_with_mock_responses():", "os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, actual_download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path,", "'--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 4 result", "if not os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir, '1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES)", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) # No", "'subfolder/blah.pdf', ]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')) # This is not in our", "util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) large_file_root_dir = os.path.join('tests', 'temp',", "util.create_large_file(os.path.join(large_file_root_dir, '6.bin'), 1) # Creates a 1 MiB file for", "bulk_get_bucket_name, '--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_object_to_content.keys()) #", "object_content) bulk_get_object_to_content[object_name] = object_content # makedirs creates all subfolders recursively", "= oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request)", "'{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') in remaining_objects shutil.rmtree(target_download_folder)", "import filecmp import json import pytest import oci import services.object_storage.src.oci_cli_object_storage", "** args) def get_count_of_files_in_folder_and_subfolders(directory): file_count = 0 for dir_name, subdir_list,", "'--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert", "in the same bucket without --overwrite then everything should be", "num_objects_in_bucket def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder, download_folder, download_prefix_no_slash): # Download uploaded files", "and files generated for bulk put @pytest.fixture(scope='module', autouse=True) def generate_test_data(object_storage_client):", "download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='exclusion_test'", "# Put in one big file per subfolder util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES)", "files for include/exclude folders_to_files = { '': ['test_file1.txt', 'test_file2.png'], 'subfolder':", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table']) assert 'action'", "At the root of the bucket object_name = 'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name)", "object_name = 'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name) elif i % 5 == 2:", "match anything '--exclude', 'subfolder/subfolder2/xyz.jpg', '--exclude', 'subfolder/[spqr]lah.pdf' # blah.pdf should still", "'--src-dir', root_bulk_put_folder, '--output', 'table', '--query', \"[?action=='Uploaded'].{file: file, \\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"]) assert", "in expected_uploaded_files: target_file = os.path.join(target_download_folder, expected_file) original_file = target_file.replace(os.path.join(target_download_folder, 'inclusion_test'),", "'/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\') assert", "get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_no_subdirectory(vcr_fixture): download_folder = 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os', 'object',", ") for response in list_object_responses: for obj in response.data.objects: object_storage_client.delete_object(util.NAMESPACE,", "OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET = 100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT = 20 CONTENT_STRING_LENGTH = 5000 MID_SIZED_FILE_IN_MEBIBTYES", "subfolder/subfolder2/testfile4.png '--include', 'subfolder/[b]lah.pdf', # Matches subfolder/blah.pdf '--include', '*/[ax]yz.jpg' # Matches", "'testfile4.png'] } for folder, files in six.iteritems(folders_to_files): folder_path = os.path.join(exclusion_test_folder,", "os.walk(root_bulk_put_folder): for file in file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path", "# # - Try to upload with a part size", "delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name) # Remove all directories recursively shutil.rmtree(root_bulk_put_folder)", "bulk_get_prefix_to_object = { 'a/b/c/d': [], 'a/b/c': [], 'a/b': [], '/a':", "that multipart params are applied: # # - Try to", "Create items at various heirarchy levels (to be surfaced as", "'--include', '*.txt', # Matches test_file1.txt, subfolder/hello.txt, subfolder/subfolder2/blag.txt '--include', 'subfolder/*.png', #", "be prompts result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "assert '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png') in remaining_objects", "its affiliates. All rights reserved. import filecmp import json import", "'--prefix', 'batman']) assert 0 == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_multipart(object_storage_client):", "= target_file.replace(os.path.join(target_download_folder, 'inclusion_test'), inclusion_test_folder) assert os.path.exists(target_file) assert filecmp.cmp(original_file, target_file, shallow=False)", "shallow=False) # Sanity check that we're reporting back that we", "namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='exclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True )", "fake_directory) in result.output @util.skip_while_rerecording def test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder = os.path.join('tests', 'temp',", "it all down afterwards # Bulk Put: create a folder", "bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif i % 5 == 3: object_name = 'a/b/c/Object_{}'.format(i)", "'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', inclusion_test_folder, '--object-prefix',", "create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--part-size', '10' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "'--include', '*.txt', '--include', 'subfolder/*.png', '--include', 'subfolder/blah.pdf', ]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')) #", "== 3: object_name = 'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name) elif i % 5", "occasional file with a reasonable size so that we can", "their content so that we can verify results bulk_get_object_to_content =", "shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_and_subdirectories(vcr_fixture): download_folder = 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) # This should", "= json.loads(result.output) assert len(parsed_result['data']) == 47 assert 'next-start-with' in result.output", "create_bucket_request) invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder])", "and --limit parameters @util.skip_while_rerecording def test_list_all_objects_operations(vcr_fixture): result = invoke(['os', 'object',", "want to overwrite it?' not in result.output assert len(parsed_result['skipped-objects']) ==", "object_name_set assert parsed_result['upload-failures'] == {} assert parsed_result['uploaded-objects'] == {} #", "'--download-dir', download_folder]) # Sanity check assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) #", "# comes after the JSON data def parse_json_response_from_mixed_output(output): lines =", "test_normalize_object_name_path(): assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/')", "util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_get_bucket_name = create_bucket_request.name", "same invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder,", "== get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_and_subdirectories(vcr_fixture): download_folder = 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) #", "= invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder,", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b']) for object_name in", "[], '/a': [], '': [] } bulk_get_bucket_name = None bulk_put_large_files", "util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke([ 'os', 'object',", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table']) assert", "'--object-prefix', 'exclusion_test/', '--exclude', '*.txt', '--exclude', '*.ps1', # Shouldn't match anything", "== {} assert len(parsed_result['deleted-objects']) == num_objects_to_delete # Check that the", "expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder = os.path.join(download_folder, download_prefix_no_slash) files_compared = 0 for", "we can verify results bulk_get_object_to_content = {} bulk_get_prefix_to_object = {", "data def parse_json_response_from_mixed_output(output): lines = output.split('\\n') json_str = '' object_begun", "for response in list_object_responses: num_objects_in_bucket = num_objects_in_bucket + len(response.data.objects) return", "should be skipped. There should be prompts result = invoke(['os',", "parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure you want to", "content == bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c/d']: file_path = os.path.join(download_folder,", "os.path.join(large_file_verify_dir, '3.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'), os.path.join(large_file_verify_dir, '4.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'),", "result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "== '\\\\': file_path = os.path.join(download_folder, object_name[1:]) else: file_path = os.path.join(download_folder,", "0 delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_operation_table_output_query(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name", "yield # Tear down stuff by deleting all the things", "fields='name', retrieve_all=True ) for response in list_object_responses: for obj in", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) print(result.output) # Ensure that content", "'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output)", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--delimiter', '/', '--dry-run']) parsed_result =", "all objects since we say --no-overwrite. Additionally there should be", "= parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert set(parsed_result['deleted-objects']) == set(parsed_dry_run_result['deleted-objects'])", "parsed_result['upload-failures'] == {} expected_uploaded_files = [ '{}{}'.format('exclusion_test/', 'test_file2.png'), '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'),", "no objects to delete in {}'.format(create_bucket_request.name) in result.output delete_bucket_and_all_items(object_storage_client, create_bucket_request.name)", "bulk_get_bucket_name, '--limit', '47']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == 47", "= os.path.join(root_bulk_put_folder, subfolder) for i in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT + 1): file_path", "assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert", "= content_file.read() assert content == bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c/d']:", "set(parsed_result['deleted-objects']) == set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name,", "create_bucket_request.name, '--force']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert", "shallow=False) # Download a specific object with inclusions invoke([ 'os',", "uploaded files and check they are the same invoke(['os', 'object',", "upload with a part size of 10MiB (this will force", "get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_and_subdirectories(vcr_fixture): download_folder = 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) # This", "path of the thing we uploaded. Normalize to # /", "{}'.format(create_bucket_request.name) in result.output delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_delete_dry_run(vcr_fixture): # Dry-run", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--dry-run']) parsed_result = json.loads(result.output) expected_objects", "the right files assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path)) in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) @util.skip_while_rerecording", "to overwrite it?' not in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content)", "def delete_bucket_and_all_items(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name,", "= util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_get_bucket_name =", "5 == 2: object_name = 'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name) elif i %", "'--src-dir', exclusion_test_folder, '--object-prefix', 'exclusion_test/', '--exclude', '*.txt', '--exclude', '*.ps1', # Shouldn't", "objects with inclusions result = invoke([ 'os', 'object', 'bulk-delete', '--namespace',", "create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000)) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID,", "and i % 10 == 0: # Put in the", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--no-overwrite']) parsed_result =", "'--output', 'table', ]) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) shutil.rmtree(target_download_folder) def invoke(commands, debug=False, **", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', target_download_folder, '--output', 'table', ])", "'auto', '--overwrite']) # No failures or skips and we uploaded", "= source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) #", "files to be multipart uploaded) # - Try to upload", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) assert 'There are no", "not in result.output assert set(parsed_result['skipped-objects']) == object_name_set assert parsed_result['upload-failures'] ==", "--include switches assert not os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) for", "We should skip over all objects since there is no", "is now empty assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) == 0 delete_bucket_and_all_items(object_storage_client, create_bucket_request.name)", "'--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you", "root_bulk_put_folder else: full_folder = os.path.join(root_bulk_put_folder, subfolder) for i in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', 'bulk_put_prefix_test/']) actual_download_folder =", "if not os.path.exists(folder_path): os.makedirs(folder_path) for file in files: file_path =", "== {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result = invoke([ 'os',", "'1.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'), os.path.join(large_file_verify_dir, '2.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'), os.path.join(large_file_verify_dir,", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '33', '--page-size', '3']) parsed_result = json.loads(result.output)", "over all objects since there is no --overwrite. There should", "'Are you sure you want to overwrite it?' in result.output", "Bulk puts objects with --content-type as auto @util.skip_while_rerecording def test_bulk_put_auto_content_type():", "'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 3", "bulk_get_prefix_to_object[''].append(object_name) object_content = generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name, object_name, object_content) bulk_get_object_to_content[object_name] =", "obj.name, response.data.objects)) assert len(remaining_objects) == 2 assert '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf') in", "{} assert set(parsed_result['deleted-objects']) == set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None,", "} bulk_get_bucket_name = None bulk_put_large_files = set() bulk_put_mid_sized_files = set()", "in {}'.format(create_bucket_request.name) in result.output delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_delete_dry_run(vcr_fixture): #", "os.makedirs(exclusion_test_folder) # Make some files for include/exclude folders_to_files = {", "def generate_test_data(object_storage_client): global bulk_get_object_to_content, bulk_get_bucket_name, root_bulk_put_folder, bulk_put_large_files, bulk_put_mid_sized_files, bulk_put_bucket_name #", "assert f in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests(", "bulk_get_prefix_to_object['a/b/c/d']) assert set(parsed_result['deleted-objects']) == expected_objects # Dry-run against a folder", "download_folder, '--prefix', download_prefix_no_slash + '/']) # The strings in the", "new bucket and populate it with some objects, then tear", "there is no --overwrite. There should be prompts result =", "want to overwrite it?' in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content)", "os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path,", "= invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--force']) parsed_result", "in result.output assert 'etag' not in result.output result = invoke(['os',", "bucket_name=bucket_name, prefix=None, start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) for", "file_count def generate_random_string(length): if test_config_container.using_vcr_with_mock_responses(): return 'a' * length else:", "'file' in result.output assert 'opc-content-md5' in result.output assert 'etag' not", "@pytest.fixture def vcr_fixture(request): with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield # Generate test data", "= 'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os',", "'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif i % 5 == 3: object_name =", "'--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder]) num_objects_to_delete = get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Sanity check", "return 'a' * length else: return ''.join(random.choice(string.ascii_lowercase) for i in", "for variety invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name,", "33 assert 'next-start-with' in result.output # Bulk puts objects, uses", "Bulk Delete: uses the folders and files generated for bulk", "os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) # Sanity check that we're", "@util.skip_while_rerecording def test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id", "download_folder = 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "in destination and they are equal) download_folder = 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os',", "@util.skip_while_rerecording def test_bulk_put_default_options(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "'--download-dir', download_folder, '--prefix', download_prefix_no_slash + '/']) # The strings in", "''.join(random.choice(string.ascii_lowercase) for i in range(length)) # Pull JSON data out", "# Dry-run against a folder and all subfolders result =", "result.output assert 'etag' not in result.output result = invoke(['os', 'object',", "!= 0 and i % 10 == 0: # Put", "Download uploaded files and check they are the same invoke(['os',", "in result.output assert 'object' in result.output assert '/a/Object_1' in result.output", "object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) # If we try and put it in", "as f: # For non-text extension types this won't create", "os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert files_compared == len(expected_uploaded_files) shutil.rmtree(actual_download_folder)", "'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all']) parsed_result = json.loads(result.output)", "'*.txt', '--include', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects'])", "'{}{}'.format('inclusion_test/', 'subfolder/hello.txt'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'),", "oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID,", "5 == 3: object_name = 'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name) elif i %", "'subfolder2', 'xyz.jpg')) for expected_file in expected_uploaded_files: target_file = os.path.join(target_download_folder, expected_file)", "impact normalized_expected_uploaded_files = [] for euf in expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder", "check assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) # We should skip over", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', fake_directory]) assert 'UsageError' in", "= os.path.join('tests', 'temp', 'os_bulk_upload_exclusion_test') if not os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder) # Make", "the root of the bucket object_name = 'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name) object_content", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--dry-run']) parsed_result =", "assert 'file' in result.output assert 'opc-content-md5' in result.output assert 'etag'", "should be skipped. There should be no prompts result =", "# Dry-run against entire bucket result = invoke(['os', 'object', 'bulk-delete',", "i) if i != 0 and i % OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT ==", "'a/b/', '--delimiter', '/', '--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) ==", "'--src-dir', root_bulk_put_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure you", "other than JSON in it. Assumes that nothing # comes", "different operations: # # Bulk Get: create a new bucket", "= invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '33',", "'--include', '*.txt', '--include', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert", "bulk_get_bucket_name, '--prefix', 'a/b/', '--delimiter', '/', '--dry-run']) parsed_result = json.loads(result.output) assert", "large_file_verify_dir, '--multipart-download-threshold', '128']) assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) == 6 assert filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'),", "LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES)", "assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) # Sanity check that", "'--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/*.png', '--include', 'subfolder/blah.pdf',", "'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder])", "bulk_get_prefix_to_object['a/b'].append(object_name) elif i % 5 == 1: # This is", "util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_put_bucket_name = create_bucket_request.name subfolders =", "bucket is now empty assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) == 0 delete_bucket_and_all_items(object_storage_client,", "2 assert '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf') in remaining_objects assert '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg') in", "with a reasonable size so that we can force multipart", "'*.txt', '--exclude', '*.ps1', # Shouldn't match anything '--exclude', 'subfolder/subfolder2/xyz.jpg', '--exclude',", "os.path.join('tests', 'temp', create_bucket_request.name) result = invoke([ 'os', 'object', 'bulk-download', '--namespace',", "you want to overwrite it?' in result.output assert len(parsed_result['skipped-objects']) ==", "== {} expected_uploaded_files = [ '{}{}'.format('exclusion_test/', 'test_file2.png'), '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/',", "json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_object_to_content.keys()) # Dry-run against a folder", "for i in range(length)) # Pull JSON data out of", "not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'byz.jpg')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test',", "bulk_put_bucket_name) # Remove all directories recursively shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording def test_normalize_object_name_path():", "assert 'next-start-with' not in result.output result = invoke(['os', 'object', 'list',", "good opportunity to test using the --all and --limit parameters", "os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(source_folder, actual_download_folder) if downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash) in", "= 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE,", "get_object_name_from_path(path_root, full_path): return full_path.replace(os.sep, '/').replace(path_root + '/', '') def delete_bucket_and_all_items(object_storage_client,", "'get_with_exclude') invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir',", "'exclusion_test', 'test_file2.png')) assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png')) assert filecmp.cmp( os.path.join(exclusion_test_folder,", "original_file = target_file.replace(os.path.join(target_download_folder, 'inclusion_test'), inclusion_test_folder) assert os.path.exists(target_file) assert filecmp.cmp(original_file, target_file,", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'batman']) assert 0", "parsed_result['uploaded-objects'] shutil.rmtree(download_folder) @util.skip_while_rerecording def test_bulk_put_with_non_existent_folder(): fake_directory = 'tests/folder/not/exist' result =", "parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert len(parsed_result['deleted-objects']) == num_objects_to_delete #", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all', '--page-size', '20']) parsed_result = json.loads(result.output) assert", "object with inclusions invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "list_object_responses: num_objects_in_bucket = num_objects_in_bucket + len(response.data.objects) return num_objects_in_bucket def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files,", "'--src-dir', fake_directory]) assert 'UsageError' in result.output assert 'The specified --src-dir", "# For the bulk operations, object names are taken from", "parsed_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_result['skipped-objects']) == 0 shutil.rmtree(download_folder) @util.skip_while_rerecording def", "True: commands = ['--debug'] + commands return util.invoke_command(commands, ** args)", "assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name)", "util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) large_file_root_dir = os.path.join('tests',", "filecmp.cmp( os.path.join(exclusion_test_folder, 'subfolder', 'testfile3.png'), os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png') ) #", "= ['', 'subfolder1', 'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3'] for subfolder in subfolders: if", "everything down and verify that the files match (everything in", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', fake_directory]) assert 'UsageError' in result.output", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) assert 'There are no objects to", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "root_bulk_put_folder, '--content-type', 'auto', '--overwrite']) # No failures or skips and", "with a part size of 10MiB (this will force the", "get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) == 0 delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_operation_table_output_query(object_storage_client): create_bucket_request", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude',", "multipart util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path) else: with open(file_path, 'w') as f:", "objects with inclusions to make sure that works target_download_folder =", "]) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'blah.pdf')) assert not os.path.exists(os.path.join(target_download_folder,", "def test_delete(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000)) create_bucket_request.compartment_id", "len(parsed_result['data']) == 47 assert 'next-start-with' in result.output result = invoke(['os',", "be no prompts result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include',", "bucket result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "object_begun = False for line in lines: if object_begun or", "test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID", "against a folder and no subfolders result = invoke(['os', 'object',", "= num_objects_in_bucket + len(response.data.objects) return num_objects_in_bucket def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder, download_folder,", "len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_put_with_prefix(): result =", "== get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder = 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_get_bucket_name = create_bucket_request.name #", "this doesn't match with paths on Windows. Using normpath converts", "all the things and then deleting the buckets delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name)", "bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--content-type', 'auto', '--overwrite']) # No failures or", "== oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/') assert '/this/is/a/path' ==", "f.write(generate_random_string(CONTENT_STRING_LENGTH)) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "assert len(bulk_get_prefix_to_object['a/b/c']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_files_skipped(): download_folder =", "namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None, start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True )", "== {} # If we say to --no-overwrite then everything", "to continue?'.format(num_objects_to_delete) assert confirm_prompt in result.output result = invoke(['os', 'object',", "'--object-prefix', 'inclusion_test/', '--include', '*.txt', # Matches test_file1.txt, subfolder/hello.txt, subfolder/subfolder2/blag.txt '--include',", "== get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Pull everything down and verify that the", "the front to avoid unexpected results) object_name = '/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name)", "'{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')", "object_name[0] == '\\\\': file_path = os.path.join(download_folder, object_name[1:]) else: file_path =", "# Dry-run against a folder and no subfolders result =", "in result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "that we uploaded what we said we did assert len(parsed_result['uploaded-objects'])", "For non-text extension types this won't create a valid file,", "sure you wish to continue?'.format(num_objects_to_delete) assert confirm_prompt in result.output result", "{} expected_uploaded_files = [ '{}{}'.format('exclusion_test/', 'test_file2.png'), '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'),", "@util.skip_while_rerecording def test_get_all_objects_in_bucket(vcr_fixture): download_folder = 'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result = invoke(['os', 'object',", "content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b']) + len(bulk_get_prefix_to_object['a/b/c']) +", "object_name in bulk_get_prefix_to_object['a/b']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r')", "= root_bulk_put_folder else: full_folder = os.path.join(root_bulk_put_folder, subfolder) for i in", "'--bucket-name', create_bucket_request.name, '--download-dir', large_file_verify_dir, '--multipart-download-threshold', '128']) assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) == 6", "in files: file_path = os.path.join(folder_path, file) with open(file_path, 'w') as", "= 'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif i % 5 == 3: object_name", "assert filecmp.cmp(original_file, target_file, shallow=False) # Download a specific object with", "0 and i % 10 == 0: # Put in", "download_folder, '--prefix', 'a/b']) for object_name in bulk_get_prefix_to_object['a/b']: file_path = os.path.join(download_folder,", "assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'byz.jpg')) assert not os.path.exists(os.path.join(target_download_folder,", "bulk_get_prefix_to_object['a/b']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as content_file:", "levels (to be surfaced as different directories on disk) for", "bulk_get_prefix_to_object['a/b/c'].append(object_name) elif i % 5 == 2: object_name = 'a/b/Object_{}'.format(i)", "various heirarchy levels (to be surfaced as different directories on", "assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) # Sanity check that we're reporting", "it result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "'--dry-run', '--output', 'table', '--query', \"[?object=='Object_0'][object]\"]) assert 'action' not in result.output", "delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) shutil.rmtree(target_download_folder) def invoke(commands, debug=False, ** args): if debug", "with paths on Windows. Using normpath converts these of #", "and so our matching/comparison works. For Linux/Unix/macOS this doesn't appear", "(to be surfaced as different directories on disk) for i", "= util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) large_file_root_dir =", "len(bulk_get_prefix_to_object['a/b/c/d']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_no_subdirectory(vcr_fixture): download_folder = 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name)", "is 128MiB # Holds the objects we create and their", "invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--delimiter',", "Tear down stuff by deleting all the things and then", "least {} objects. Are you sure you wish to continue?'.format(num_objects_to_delete)", "= invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all', '--page-size',", "'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) # Delete objects with inclusions result", "probably OK f.write(generate_random_string(CONTENT_STRING_LENGTH)) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace',", "bulk_put_large_files, bulk_put_mid_sized_files, bulk_put_bucket_name # Create a test bucket create_bucket_request =", "@util.skip_while_rerecording def test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_exclusion_test') if not", "object_begun = True json_str += line return json.loads(json_str) # For", "bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure", "thing we uploaded. Normalize to # / in the paths", "for obj in response.data.objects: object_storage_client.delete_object(util.NAMESPACE, bucket_name, obj.name) object_storage_client.delete_bucket(util.NAMESPACE, bucket_name) def", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', fake_directory]) assert", "test_get_files_skipped(): download_folder = 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "== {} expected_uploaded_files = [ '{}{}'.format('inclusion_test/', 'test_file1.txt'), '{}{}'.format('inclusion_test/', 'subfolder/hello.txt'), '{}{}'.format('inclusion_test/',", "surfaced as different directories on disk) for i in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET):", "ways) then chop the front bit off def get_object_name_from_path(path_root, full_path):", "os.path.join(large_file_verify_dir, '4.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'), os.path.join(large_file_verify_dir, '5.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'),", "actual_download_folder = os.path.join(download_folder, 'bulk_put_prefix_test') for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder):", "download_folder = 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', 'subfolder/subfolder2/xyz.jpg'", "+= 1 assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert files_compared", "parsed_result['uploaded-objects'] == {} # Now we force it result =", "assert filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'), os.path.join(large_file_verify_dir, '6.bin')) shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) #", "= os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path) assert", "'--src-dir', root_bulk_put_folder, '--content-type', 'auto', '--overwrite']) # No failures or skips", "multipart params are applied: # # - Try to upload", "# Put in the occasional file with a reasonable size", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b/c/', '--delimiter', '/'])", "Check that we uploaded what we said we did assert", "set() root_bulk_put_folder = None bulk_put_bucket_name = None @pytest.fixture def vcr_fixture(request):", "will delete {} objects. Are you sure you wish to", "result.output assert 'opc-content-md5' in result.output assert 'etag' not in result.output", "'test_file2.png'), '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png') ]", "1 assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert files_compared ==", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', large_file_verify_dir, '--multipart-download-threshold', '128']) assert", "expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='exclusion_test' ) # Download objects with exclusions", "in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording", "'4.bin'), os.path.join(large_file_verify_dir, '4.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'), os.path.join(large_file_verify_dir, '5.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir,", "'a' * length else: return ''.join(random.choice(string.ascii_lowercase) for i in range(length))", "= 20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 150 # Default multipart is 128MiB", "# Sanity check that we're reporting back that we uploaded", "for i in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if i % 5 == 4:", "'--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b/c/', '--delimiter', '/']) for object_name", "makedirs creates all subfolders recursively root_bulk_put_folder = 'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf =", "'': full_folder = root_bulk_put_folder else: full_folder = os.path.join(root_bulk_put_folder, subfolder) for", "bulk_get_bucket_name, '--all']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert", "recursively root_bulk_put_folder = 'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf = '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if not os.path.exists(bulk_put_folder_leaf):", "delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_operation_table_output_query(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name =", "data out of output which may have stuff other than", "things and then deleting the buckets delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name)", "% 10 == 0: # Put in the occasional file", "'--download-dir', download_folder, '--prefix', 'batman']) assert 0 == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording", "'--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b']) for object_name in bulk_get_prefix_to_object['a/b']:", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', exclusion_test_folder, '--object-prefix', 'exclusion_test/', '--exclude', '*.txt', '--exclude',", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--overwrite']) parsed_result =", "inclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_inclusion_test') if not os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder) #", "= 0 for response in list_object_responses: num_objects_in_bucket = num_objects_in_bucket +", "invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '47']) parsed_result", "'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output)", "exclusions result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "@util.skip_while_rerecording def test_get_no_objects(vcr_fixture): download_folder = 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace',", "'--exclude', 'subfolder/[spqr]lah.pdf' # blah.pdf should still be included because it's", "bulk_get_bucket_name, '--download-dir', download_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_result['skipped-objects']) ==", "as f: f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield # Tear down stuff by deleting", "'There are no objects to delete in {}'.format(create_bucket_request.name) in result.output", "objects. Are you sure you wish to continue?'.format(num_objects_to_delete) assert confirm_prompt", "= 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir',", "Holds the objects we create and their content so that", "+ '/', '') def delete_bucket_and_all_items(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client,", "uploaded. Normalize to # / in the paths (Windows can", "== 0 delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_operation_table_output_query(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails()", "root of the bucket object_name = 'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name) object_content =", "def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder, download_folder, download_prefix_no_slash): # Download uploaded files and", "'testfile4.png')) assert get_count_of_files_in_folder_and_subfolders(target_download_folder) == 2 assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png')) assert", "delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name) # Remove all directories recursively shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording def", "LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 150 # Default multipart is 128MiB # Holds", "we say to --no-overwrite then everything should be skipped. There", "bulk_put_bucket_name # Create a test bucket create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects'])", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', 'bulk_put_prefix_test/']) actual_download_folder = os.path.join(download_folder,", "in list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert len(remaining_objects) == 3", "]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 4 result =", "test_list_all_objects_operations(vcr_fixture): result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "'--prefix', 'bulk_put_prefix_test/']) actual_download_folder = os.path.join(download_folder, 'bulk_put_prefix_test') for dir_name, subdir_list, file_list", "file_count = file_count + len(file_list) return file_count def generate_random_string(length): if", "['blah.pdf', 'hello.txt', 'testfile3.png'], 'subfolder/subfolder2': ['xyz.jpg', 'blag.txt', 'byz.jpg', 'testfile4.png'] } for", "i % 5 == 1: # This is equivalent to", "util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath',", "= parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert len(parsed_result['deleted-objects']) == num_objects_to_delete", "bucket create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID", "= set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d']) assert set(parsed_result['deleted-objects']) == expected_objects # Dry-run", "file_count + len(file_list) return file_count def generate_random_string(length): if test_config_container.using_vcr_with_mock_responses(): return", "works target_download_folder = os.path.join(download_folder_base, 'get_with_include') invoke([ 'os', 'object', 'bulk-download', '--namespace',", "Ensure that content matches for object_name in bulk_get_object_to_content: if object_name[0]", "source_file_path)) # If we try and put it in the", "are the same invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) #", "results bulk_get_object_to_content = {} bulk_get_prefix_to_object = { 'a/b/c/d': [], 'a/b/c':", "[] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) #", "force it result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "types this won't create a valid file, but for testing", "bit off def get_object_name_from_path(path_root, full_path): return full_path.replace(os.sep, '/').replace(path_root + '/',", "download_folder, '--prefix', 'batman']) assert 0 == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def", "folders_to_files = { '': ['test_file1.txt', 'test_file2.png'], 'subfolder': ['blah.pdf', 'hello.txt', 'testfile3.png'],", "== 2 assert '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf') in remaining_objects assert '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg')", "= os.path.join(exclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for file in", "num_objects_in_bucket + len(response.data.objects) return num_objects_in_bucket def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder, download_folder, download_prefix_no_slash):", "== get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_no_subdirectory(vcr_fixture): download_folder = 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os',", "== bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b']) + len(bulk_get_prefix_to_object['a/b/c']) + len(bulk_get_prefix_to_object['a/b/c/d']) == get_count_of_files_in_folder_and_subfolders(download_folder)", "a \"/\" in them, but this doesn't match with paths", "expected_objects = set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d']) assert set(parsed_result['deleted-objects']) == expected_objects #", "@util.skip_while_rerecording def test_bulk_operation_table_output_query(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id", "this won't create a valid file, but for testing is", "create_bucket_request.name]) assert 'There are no objects to delete in {}'.format(create_bucket_request.name)", "set() for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder): for file in", "in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT + 1): file_path = '{}/object_{}'.format(full_folder, i) if i", "content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b/c']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def", "number of objects in this test suite, it's a good", "that the bucket is now empty assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) ==", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', 'bulk_put_prefix_test/'])", "OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with' not in result.output result = invoke(['os', 'object',", "bucket object_name = 'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name) object_content = generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name,", "'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude',", "'subfolder', 'subfolder2', 'byz.jpg')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'testfile4.png'))", "download_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure you want", "'next-start-with' in result.output result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE,", "+ len(bulk_get_prefix_to_object['a/b/c/d']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_no_subdirectory(vcr_fixture): download_folder =", "for bulk put @pytest.fixture(scope='module', autouse=True) def generate_test_data(object_storage_client): global bulk_get_object_to_content, bulk_get_bucket_name,", "back that we uploaded the right files assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path))", "file_path = os.path.join(download_folder, object_name[1:]) else: file_path = os.path.join(download_folder, object_name) with", "'*.jpg', '--exclude', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects'])", "it?' not in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We", "parsed_result['delete-failures'] == {} assert set(parsed_result['deleted-objects']) == set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects(", "to make sure that works target_download_folder = os.path.join(download_folder_base, 'get_with_include') invoke([", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) if num_objects_to_delete >= 1000: confirm_prompt =", "'subfolder', 'subfolder2', 'testfile4.png')) assert get_count_of_files_in_folder_and_subfolders(target_download_folder) == 2 assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test',", "delimiter=None, fields='name', retrieve_all=True ) num_objects_in_bucket = 0 for response in", "{} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_put_with_prefix():", "and populate it with some objects, then tear it all", "get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) > 0 result = invoke(['os', 'object', 'bulk-delete', '--namespace',", "len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) # We should skip over all objects", "root_bulk_put_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure you", "[ '{}{}'.format('inclusion_test/', 'test_file1.txt'), '{}{}'.format('inclusion_test/', 'subfolder/hello.txt'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/',", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are", "20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 150 # Default multipart is 128MiB #", "to overwrite it?' not in result.output assert set(parsed_result['skipped-objects']) == object_name_set", "'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png') ] # Check that we uploaded what", "assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert guess_type(source_file_path) == guess_type(downloaded_file_path)", "source_folder=inclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='inclusion_test' ) # Download objects with inclusions to", "file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path,", "against a folder and all subfolders result = invoke(['os', 'object',", "assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures'] == {} expected_uploaded_files =", "objects with --content-type as auto @util.skip_while_rerecording def test_bulk_put_auto_content_type(): result =", "'testfile4.png'] } for folder, files in six.iteritems(folders_to_files): folder_path = os.path.join(inclusion_test_folder,", "assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'testfile4.png')) assert get_count_of_files_in_folder_and_subfolders(target_download_folder) ==", "bucket without --overwrite then everything should be skipped. There should", "should be no prompts result = invoke(['os', 'object', 'bulk-download', '--namespace',", "or line.startswith('{'): object_begun = True json_str += line return json.loads(json_str)", "1: # This is equivalent to a/ on the file", "remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') in", "'\\\\') @util.skip_while_rerecording def test_get_all_objects_in_bucket(vcr_fixture): download_folder = 'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result = invoke(['os',", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--object-prefix', 'bulk_put_prefix_test/']) #", "'--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--output', 'table', '--query', \"[?action=='Uploaded'].{file: file, \\\"opc-content-md5\\\":", "bulk_get_bucket_name = None bulk_put_large_files = set() bulk_put_mid_sized_files = set() root_bulk_put_folder", "bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you", "if i % 5 == 4: object_name = 'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name)", "'33', '--page-size', '3']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == 33", "'--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--dry-run' ])", "bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/subfolder2/*.png', '--exclude',", "in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if i % 5 == 4: object_name =", "the large and mid-sized files to be multipart uploaded) #", "in the occasional file with a reasonable size so that", "generate_test_data(object_storage_client): global bulk_get_object_to_content, bulk_get_bucket_name, root_bulk_put_folder, bulk_put_large_files, bulk_put_mid_sized_files, bulk_put_bucket_name # Create", "= oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None, start=None, end=None, limit=1000,", "'--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/subfolder2/*.png', '--exclude', 'subfolder/blah.pdf', ]) assert", "bulk_put_mid_sized_files.add(file_path) else: with open(file_path, 'w') as f: f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield #", "'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') ] # Check", "['', 'subfolder1', 'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3'] for subfolder in subfolders: if subfolder", "normalized_expected_uploaded_files = [] for euf in expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder =", "result.output assert 'The specified --src-dir {} (expanded to: {}) does", "download_folder = 'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_files_skipped(): download_folder = 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os', 'object',", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder]) num_objects_to_delete =", "delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_delete_dry_run(vcr_fixture): # Dry-run against entire bucket", "== get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_put_with_prefix(): result = invoke(['os',", "oci_cli_object_storage import os import random import shutil import six import", "for testing is probably OK f.write(generate_random_string(CONTENT_STRING_LENGTH)) result = invoke([ 'os',", "invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all']) parsed_result =", "len(object_name_set) for object_name in object_name_set: assert object_name in parsed_result['uploaded-objects'] shutil.rmtree(download_folder)", "== set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording def test_delete(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name =", "This command will delete at least {} objects. Are you", "create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) large_file_root_dir = os.path.join('tests', 'temp', 'multipart_get_large_files') if not", "it with some objects, then tear it all down afterwards", "json.loads(json_str) # For the bulk operations, object names are taken", "+= line return json.loads(json_str) # For the bulk operations, object", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--content-type', 'auto', '--overwrite'])", "util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke([", "'3.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'), os.path.join(large_file_verify_dir, '4.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'), os.path.join(large_file_verify_dir,", "file for variety invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "reserved. import filecmp import json import pytest import oci import", "that we uploaded the right files assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in", "a part size of 10MiB (this will force the large", "the same bucket without --overwrite then everything should be skipped.", "json_str = '' object_begun = False for line in lines:", "from mimetypes import guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET = 100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT = 20", "parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording", "args): if debug is True: commands = ['--debug'] + commands", "'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\') @util.skip_while_rerecording def test_get_all_objects_in_bucket(vcr_fixture): download_folder = 'tests/temp/get_all_{}'.format(bulk_get_bucket_name)", "the objects we create and their content so that we", "that content matches for object_name in bulk_get_object_to_content: if object_name[0] ==", "global bulk_get_object_to_content, bulk_get_bucket_name, root_bulk_put_folder, bulk_put_large_files, bulk_put_mid_sized_files, bulk_put_bucket_name # Create a", "content = content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b/c']) ==", "expected_uploaded_files: assert f in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_exclusion_test')", "util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--output', 'table', '--query', \"[?action=='Uploaded'].{file: file,", "create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) invoke(['os',", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) # Sanity", "util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os',", "i in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if i % 5 == 4: object_name", "of objects in this test suite, it's a good opportunity", "'hello.txt', 'testfile3.png'], 'subfolder/subfolder2': ['xyz.jpg', 'blag.txt', 'byz.jpg', 'testfile4.png'] } for folder,", "force the large and mid-sized files to be multipart uploaded)", "it assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) > 0 result = invoke(['os', 'object',", "= oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='inclusion_test/', start=None, end=None, limit=1000,", "file_path = '{}/object_{}'.format(full_folder, i) if i != 0 and i", "switches assert not os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) for expected_file", "not in result.output assert 'Object_0' in result.output target_download_folder = os.path.join('tests',", "get_number_of_objects_in_bucket(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None,", "'subfolder1/subfolder2/subfolder3'] for subfolder in subfolders: if subfolder == '': full_folder", "def test_bulk_put_default_options(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording def", "recursively shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording def test_normalize_object_name_path(): assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert", "expected_file in expected_uploaded_files: target_file = os.path.join(target_download_folder, expected_file) original_file = target_file.replace(os.path.join(target_download_folder,", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'batman']) assert", "Put: create a folder structure containing small and large files,", "def test_bulk_put_with_prefix(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "'*/[ax]yz.jpg' # Matches subfolder/subfolder2/xyz.jpg ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects']", "in list_object_responses: for obj in response.data.objects: object_storage_client.delete_object(util.NAMESPACE, bucket_name, obj.name) object_storage_client.delete_bucket(util.NAMESPACE,", "= 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir',", "all objects since there is no --overwrite. There should be", "source_folder=exclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='exclusion_test' ) # Download objects with exclusions to", "delimiter=None, fields='name', retrieve_all=True ) for response in list_object_responses: for obj", "'--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are", "which may have stuff other than JSON in it. Assumes", "bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b/c']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_files_skipped(): download_folder", "we drop the leading slash (we drop path separators from", "filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'), os.path.join(large_file_verify_dir, '3.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'), os.path.join(large_file_verify_dir, '4.bin')) assert", "filecmp.cmp( os.path.join(exclusion_test_folder, 'test_file2.png'), os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png') ) assert filecmp.cmp( os.path.join(exclusion_test_folder,", "assert filecmp.cmp( os.path.join(exclusion_test_folder, 'test_file2.png'), os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png') ) assert filecmp.cmp(", "create_bucket_request.name) @util.skip_while_rerecording def test_bulk_operation_table_output_query(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageTableOutput_{}'.format(util.random_number_string())", "'subfolder/[b]lah.pdf', # Matches subfolder/blah.pdf '--include', '*/[ax]yz.jpg' # Matches subfolder/subfolder2/xyz.jpg ])", "'temp', 'multipart_get_large_files') if not os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir, '1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir,", "in subfolders: if subfolder == '': full_folder = root_bulk_put_folder else:", "source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, actual_download_folder) assert os.path.exists(downloaded_file_path)", "parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder, download_folder=download_folder_base,", "import string from tests import util from tests import test_config_container", "4 result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'), os.path.join(large_file_verify_dir, '6.bin')) shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) # Since", "to upload with multipart disabled @util.skip_while_rerecording def test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request =", "bulk_get_object_to_content[object_name] = object_content # makedirs creates all subfolders recursively root_bulk_put_folder", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b'])", "Delete: uses the folders and files generated for bulk put", "in result.output assert set(parsed_result['skipped-objects']) == object_name_set assert parsed_result['upload-failures'] == {}", "the thing we uploaded. Normalize to # / in the", "check they are the same invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "None @pytest.fixture def vcr_fixture(request): with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield # Generate test", "== get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_multipart(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name", "invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', inclusion_test_folder,", "result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) if", "non-text extension types this won't create a valid file, but", "bulk_put_large_files = set() bulk_put_mid_sized_files = set() root_bulk_put_folder = None bulk_put_bucket_name", "array have a \"/\" in them, but this doesn't match", "= oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000)) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client,", "command will delete at least {} objects. Are you sure", "source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) shutil.rmtree(download_folder) # Tests that multipart", "# Now we force it result = invoke(['os', 'object', 'bulk-upload',", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--content-type', 'auto',", "'--exclude', 'subfolder/blah.pdf', ]) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'blah.pdf')) assert", "is True: commands = ['--debug'] + commands return util.invoke_command(commands, **", "parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result = invoke([", "'--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/subfolder2/*.png',", "shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_no_subdirectory(vcr_fixture): download_folder = 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download',", "things in it assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) > 0 result =", "objects with exclusions to make sure that works target_download_folder =", "does not exist'.format(fake_directory, fake_directory) in result.output @util.skip_while_rerecording def test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder", "to: {}) does not exist'.format(fake_directory, fake_directory) in result.output @util.skip_while_rerecording def", "check that we're reporting back that we uploaded the right", "# Delete objects with exclusions result = invoke([ 'os', 'object',", "util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) invoke(['os', 'object', 'bulk-upload', '--namespace',", "you wish to continue?'.format(num_objects_to_delete) assert confirm_prompt in result.output result =", "result.output delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_delete_dry_run(vcr_fixture): # Dry-run against entire", "Get: create a new bucket and populate it with some", "reasonable number of objects in this test suite, it's a", "'--bucket-name', create_bucket_request.name, '--force']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {}", "invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/',", "start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) num_objects_in_bucket = 0", "assert set(parsed_result['skipped-objects']) == object_name_set assert parsed_result['upload-failures'] == {} assert parsed_result['uploaded-objects']", "# Default multipart is 128MiB # Holds the objects we", "The strings in the expected_uploaded_files array have a \"/\" in", "no subfolders result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "Bulk Put: create a folder structure containing small and large", "# At the root of the bucket object_name = 'Object_{}'.format(i)", "in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')", "that works target_download_folder = os.path.join(download_folder_base, 'get_with_exclude') invoke([ 'os', 'object', 'bulk-download',", "both ways) then chop the front bit off def get_object_name_from_path(path_root,", "= 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE,", "parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert len(parsed_result['deleted-objects']) ==", "else: full_folder = os.path.join(root_bulk_put_folder, subfolder) for i in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT +", "length else: return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) # Pull", "'--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', download_prefix_no_slash + '/']) # The", "in result.output delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_delete_dry_run(vcr_fixture): # Dry-run against", "the default of 128MiB) @util.skip_while_rerecording def test_bulk_put_default_options(): result = invoke(['os',", "equal) download_folder = 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Pull", "invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', exclusion_test_folder,", "assert guess_type(source_file_path) == guess_type(downloaded_file_path) # Sanity check that we're reporting", "will delete at least {} objects. Are you sure you", "= 20 CONTENT_STRING_LENGTH = 5000 MID_SIZED_FILE_IN_MEBIBTYES = 20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES =", "get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) == 6 assert filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'), os.path.join(large_file_verify_dir, '1.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir,", "same bucket without --overwrite then everything should be skipped. There", "of 10MiB (this will force the large and mid-sized files", "def vcr_fixture(request): with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield # Generate test data for", "create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--no-multipart', '--overwrite' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "# Tests that multipart params are applied: # # -", ") remaining_objects = [] for response in list_objects_responses: remaining_objects.extend(map(lambda obj:", "'--exclude', '*.txt', '--exclude', '*.ps1', # Shouldn't match anything '--exclude', 'subfolder/subfolder2/xyz.jpg',", "test_get_no_objects(vcr_fixture): download_folder = 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "== 4 result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "'--output', 'table', '--query', \"[?action=='Uploaded'].{file: file, \\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"]) assert 'file' in", "Tests that multipart params are applied: # # - Try", "'{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording def test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder", "Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', exclusion_test_folder, '--object-prefix', 'exclusion_test/',", "'table', '--query', \"[?object=='Object_0'][object]\"]) assert 'action' not in result.output assert '/a/Object_1'", "dir_name, subdir_list, file_list in os.walk(directory): file_count = file_count + len(file_list)", "# # Bulk Get: create a new bucket and populate", "shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_files_skipped(): download_folder = 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download',", "lines = output.split('\\n') json_str = '' object_begun = False for", "oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path',", "= os.path.join(download_folder_base, 'get_with_exclude') invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "'The specified --src-dir {} (expanded to: {}) does not exist'.format(fake_directory,", "create_bucket_request.compartment_id = util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object', 'bulk-delete',", "'Are you sure you want to overwrite it?' not in", "JSON in it. Assumes that nothing # comes after the", "subdir_list, file_list in os.walk(root_bulk_put_folder): for file in file_list: source_file_path =", "'subfolder', 'testfile3.png'), os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png') ) # Delete objects", "== [] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == len(object_name_set)", "the file path of the thing we uploaded. Normalize to", "bulk_get_prefix_to_object['a/b/c/d']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as content_file:", "the bulk operations, object names are taken from the file", "verify results bulk_get_object_to_content = {} bulk_get_prefix_to_object = { 'a/b/c/d': [],", "'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/') assert 'thisisapath'", "'128']) assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) == 6 assert filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'), os.path.join(large_file_verify_dir, '1.bin'))", "'--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--force' ]) parsed_result =", "os.path.join('tests', 'temp', 'os_bulk_upload_exclusion_test') if not os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder) # Make some", "source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path)", "against entire bucket result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object',", "assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We should skip over no", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "assert os.path.exists(target_file) assert filecmp.cmp(original_file, target_file, shallow=False) # Download a specific", "= invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', fake_directory])", "'{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png') ] # Check that we uploaded", "'--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) # Sanity check assert len(bulk_get_object_to_content) ==", "source_folder, download_folder, download_prefix_no_slash): # Download uploaded files and check they", "== bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b/c']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_files_skipped():", "assert set(parsed_result['deleted-objects']) == set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE,", "object_name in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) # Bulk puts objects with --content-type", "no prompts result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "6 assert filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'), os.path.join(large_file_verify_dir, '1.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'), os.path.join(large_file_verify_dir,", "'subfolder/*.png', '--include', 'subfolder/blah.pdf', ]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')) # This is not", "get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) # If we try", "= os.path.join('tests', 'temp', 'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='exclusion_test' )", "(we drop path separators from the front to avoid unexpected", "util.create_large_file(os.path.join(large_file_root_dir, '3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir,", "# No failures or skips and we uploaded everything parsed_result", "doesn't match with paths on Windows. Using normpath converts these", "in file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, actual_download_folder)", "'--bucket-name', bulk_get_bucket_name, '--all']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET", "{} assert parsed_result['uploaded-objects'] == {} # Now we force it", "bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--force' ]) parsed_result", "not os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir, '1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir,", "'--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording def", "[] for euf in expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder = os.path.join(download_folder, download_prefix_no_slash)", "right files assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) shutil.rmtree(download_folder)", "put it in the same bucket without --overwrite then everything", "util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) invoke(['os', 'object', 'bulk-upload',", "util.create_large_file(os.path.join(large_file_root_dir, '5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '6.bin'), 1) # Creates a 1", "six.iteritems(folders_to_files): folder_path = os.path.join(inclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for", "util.create_large_file(os.path.join(large_file_root_dir, '2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir,", "remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert len(remaining_objects) == 3 assert '{}{}'.format('inclusion_test/',", "'--dry-run', '--output', 'table']) assert 'action' in result.output assert 'object' in", "Matches subfolder/subfolder2/xyz.jpg ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == []", "# Delete objects with inclusions result = invoke([ 'os', 'object',", "% 5 == 1: # This is equivalent to a/", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) if num_objects_to_delete >= 1000:", "json_str += line return json.loads(json_str) # For the bulk operations,", "be surfaced as different directories on disk) for i in", "object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_get_bucket_name = create_bucket_request.name # Create items at various", "assert filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'), os.path.join(large_file_verify_dir, '5.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'), os.path.join(large_file_verify_dir, '6.bin'))", "remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert len(remaining_objects) == 2 assert '{}{}'.format('exclusion_test/',", "for response in list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert len(remaining_objects)", "util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder]) num_objects_to_delete = get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Sanity", "assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_and_subdirectories(vcr_fixture): download_folder =", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) # Sanity check assert len(bulk_get_object_to_content)", "= os.path.join(download_folder_base, 'get_with_include') invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "i in range(length)) # Pull JSON data out of output", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--part-size', '10' ]) parsed_result", "os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png')) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'test_file2.png'), os.path.join(target_download_folder, 'exclusion_test',", "different directories on disk) for i in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if i", "== get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_files_skipped(): download_folder = 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os',", "'subfolder/*.png', # Matches subfolder/testfile3.png, subfolder/subfolder2/testfile4.png '--include', 'subfolder/[b]lah.pdf', # Matches subfolder/blah.pdf", "0 for dir_name, subdir_list, file_list in os.walk(directory): file_count = file_count", "Try to upload with multipart disabled @util.skip_while_rerecording def test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request", "of 128MiB) @util.skip_while_rerecording def test_bulk_put_default_options(): result = invoke(['os', 'object', 'bulk-upload',", "'bulk_put_prefix_test') for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder): for file in", "[] for response in list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert", "== oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\') @util.skip_while_rerecording def test_get_all_objects_in_bucket(vcr_fixture): download_folder = 'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result", "'--download-dir', download_folder]) print(result.output) # Ensure that content matches for object_name", "assert 0 == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_multipart(object_storage_client): create_bucket_request =", "for include/exclude folders_to_files = { '': ['test_file1.txt', 'test_file2.png'], 'subfolder': ['blah.pdf',", "os.path.join('tests', 'temp', 'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='exclusion_test' ) #", "test_bulk_put_with_non_existent_folder(): fake_directory = 'tests/folder/not/exist' result = invoke(['os', 'object', 'bulk-upload', '--namespace',", "bulk_get_bucket_name = create_bucket_request.name # Create items at various heirarchy levels", "'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output)", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', 'subfolder/subfolder2/xyz.jpg' ])", "= True json_str += line return json.loads(json_str) # For the", "subfolder/hello.txt, subfolder/subfolder2/blag.txt '--include', 'subfolder/*.png', # Matches subfolder/testfile3.png, subfolder/subfolder2/testfile4.png '--include', 'subfolder/[b]lah.pdf',", "'--query', \"[?action=='Uploaded'].{file: file, \\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"]) assert 'file' in result.output assert", "response.data.objects)) assert len(remaining_objects) == 3 assert '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png') in remaining_objects", "== 2: object_name = 'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name) elif i % 5", "= os.path.join('tests', 'temp', 'multipart_get_large_files') if not os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir, '1.bin'),", "+ len(bulk_get_prefix_to_object['a/b/c']) + len(bulk_get_prefix_to_object['a/b/c/d']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_no_subdirectory(vcr_fixture):", "(everything in source appears in destination and they are equal)", "'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '47']) parsed_result =", "if num_objects_to_delete >= 1000: confirm_prompt = 'WARNING: This command will", "\\\"opc-content-md5\\\"}\"]) assert 'file' in result.output assert 'opc-content-md5' in result.output assert", "'--output', 'table', '--query', \"[?object=='Object_0'][object]\"]) assert 'action' not in result.output assert", "end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) for response in list_object_responses:", "bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', 'subfolder/subfolder2/xyz.jpg' ]) assert os.path.exists(os.path.join(target_download_folder,", "'subfolder/subfolder2/xyz.jpg' ]) assert os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) # Delete", "all subfolders recursively root_bulk_put_folder = 'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf = '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if", "'1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '4.bin'),", "create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_get_bucket_name", "os.path.join(download_folder, download_prefix_no_slash) files_compared = 0 for dir_name, subdir_list, file_list in", "== oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/') assert 'thisisapath' ==", "'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder,", "Shouldn't match anything '--exclude', 'subfolder/subfolder2/xyz.jpg', '--exclude', 'subfolder/[spqr]lah.pdf' # blah.pdf should", "result = invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name,", "works. For Linux/Unix/macOS this doesn't appear to have an impact", "where appropriate (when we breach the default of 128MiB) @util.skip_while_rerecording", "] # Check that we uploaded what we said we", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run']) parsed_result = json.loads(result.output) assert", "no objects since we --overwrite result = invoke(['os', 'object', 'bulk-download',", "in list_object_responses: num_objects_in_bucket = num_objects_in_bucket + len(response.data.objects) return num_objects_in_bucket def", "assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result = invoke([ 'os', 'object', 'bulk-upload',", "client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None, start=None, end=None, limit=1000, delimiter=None, fields='name',", "exclusions to make sure that works target_download_folder = os.path.join(download_folder_base, 'get_with_exclude')", "small and large files, then tear it all down afterwards", "object_name in bulk_get_prefix_to_object['a/b/c/d']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r')", "if i != 0 and i % OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT == 0:", "= create_bucket_request.name # Create items at various heirarchy levels (to", "random import shutil import six import string from tests import", "'--dry-run']) parsed_result = json.loads(result.output) expected_objects = set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d']) assert", "'--download-dir', large_file_verify_dir, '--multipart-download-threshold', '128']) assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) == 6 assert filecmp.cmp(os.path.join(large_file_root_dir,", "util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object', 'bulk-upload',", "'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name) elif i % 5 == 1: # This", "appropriate (when we breach the default of 128MiB) @util.skip_while_rerecording def", "root_bulk_put_folder, '--part-size', '10' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] ==", "verify that the files match (everything in source appears in", "len(bulk_get_prefix_to_object['a/b/c']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_files_skipped(): download_folder = 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name)", "folder structure containing small and large files, then tear it", "[] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == len(object_name_set) for", "'/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name) else: # At the root of the bucket", "import oci import services.object_storage.src.oci_cli_object_storage as oci_cli_object_storage import os import random", "we did assert len(parsed_result['uploaded-objects']) == len(expected_uploaded_files) for f in expected_uploaded_files:", "Pull everything down and verify that the files match (everything", "'5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '6.bin'), 1) # Creates a 1 MiB", "create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_get_bucket_name = create_bucket_request.name # Create items at", "os.path.join(download_folder, 'bulk_put_prefix_test') for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder): for file", "== '/' or object_name[0] == '\\\\': file_path = os.path.join(download_folder, object_name[1:])", "we force it result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "== 4: object_name = 'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif i % 5", "all subfolders result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "the right files assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path))", "content matches for object_name in bulk_get_object_to_content: if object_name[0] == '/'", "num_objects_in_bucket = 0 for response in list_object_responses: num_objects_in_bucket = num_objects_in_bucket", "our --include switches assert not os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg'))", "os.path.join(exclusion_test_folder, 'test_file2.png'), os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png') ) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'subfolder',", "remaining_objects assert '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording def", "= json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with' not in", "47 assert 'next-start-with' in result.output result = invoke(['os', 'object', 'list',", "response in list_object_responses: for obj in response.data.objects: object_storage_client.delete_object(util.NAMESPACE, bucket_name, obj.name)", "import guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET = 100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT = 20 CONTENT_STRING_LENGTH =", "tear it all down afterwards # Bulk Delete: uses the", "folder, files in six.iteritems(folders_to_files): folder_path = os.path.join(inclusion_test_folder, folder) if not", "os.path.join(large_file_verify_dir, '1.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'), os.path.join(large_file_verify_dir, '2.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'),", "'subfolder/hello.txt'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/',", "parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures'] == {} expected_uploaded_files = [", "'{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') ] #", "taken from the file path of the thing we uploaded.", "parsed_result['upload-failures'] == {} expected_uploaded_files = [ '{}{}'.format('inclusion_test/', 'test_file1.txt'), '{}{}'.format('inclusion_test/', 'subfolder/hello.txt'),", "shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) # Since we've created a reasonable", "and then deleting the buckets delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name) #", "bulk_put_mid_sized_files = set() root_bulk_put_folder = None bulk_put_bucket_name = None @pytest.fixture", "everything should be skipped. There should be prompts result =", "no prompts result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix',", "bulk operations, object names are taken from the file path", "shallow=False) assert guess_type(source_file_path) == guess_type(downloaded_file_path) # Sanity check that we're", "a test bucket create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id", "Bulk Get: create a new bucket and populate it with", "for i in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT + 1): file_path = '{}/object_{}'.format(full_folder, i)", "filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert guess_type(source_file_path) == guess_type(downloaded_file_path) # Sanity check", "= invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir',", "'') def delete_bucket_and_all_items(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE,", "'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000)) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE,", "with inclusions invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--delimiter', '/',", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '47']) parsed_result = json.loads(result.output) assert", "len(response.data.objects) return num_objects_in_bucket def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder, download_folder, download_prefix_no_slash): # Download", "'3.bin'), os.path.join(large_file_verify_dir, '3.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'), os.path.join(large_file_verify_dir, '4.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir,", "'exclusion_test', 'test_file2.png') ) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'subfolder', 'testfile3.png'), os.path.join(target_download_folder, 'exclusion_test',", "'subfolder/blah.pdf', ]) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'blah.pdf')) assert not", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', 'bulk_put_prefix_test/']) actual_download_folder", "Sanity check that the bucket has things in it assert", "line.startswith('{'): object_begun = True json_str += line return json.loads(json_str) #", "the front bit off def get_object_name_from_path(path_root, full_path): return full_path.replace(os.sep, '/').replace(path_root", "create and their content so that we can verify results", "test_config_container from mimetypes import guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET = 100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT =", "for dir_name, subdir_list, file_list in os.walk(directory): file_count = file_count +", "i != 0 and i % OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT == 0: #", "get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) shutil.rmtree(download_folder) # Tests that", "response.data.objects)) assert len(remaining_objects) == 2 assert '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf') in remaining_objects", "assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\')", "open(file_path, 'w') as f: # For non-text extension types this", "# This is equivalent to a/ on the file system", "right files assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path)) in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) @util.skip_while_rerecording def", "specific object with inclusions invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "{} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result = invoke([ 'os', 'object',", "delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_put_with_prefix(): result = invoke(['os', 'object', 'bulk-upload',", "size so that we can force multipart util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path)", "make sure that works target_download_folder = os.path.join(download_folder_base, 'get_with_include') invoke([ 'os',", "afterwards # Bulk Put: create a folder structure containing small", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--object-prefix', 'bulk_put_prefix_test/']) # No failures", "for object_name in object_name_set: assert object_name in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) #", "util.NAMESPACE, '--bucket-name', create_bucket_request.name]) assert 'There are no objects to delete", "'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request)", "download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='inclusion_test'", "def test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id =", "list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None, start=None, end=None,", "with open(file_path, 'w') as f: f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield # Tear down", "'{}{}'.format('exclusion_test/', 'test_file2.png'), '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png')", "== set(bulk_get_object_to_content.keys()) # Dry-run against a folder and all subfolders", "deleting the buckets delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name) # Remove all", "# \"\\\" on Windows and so our matching/comparison works. For", "else: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as content_file:", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table', '--query', \"[?object=='Object_0'][object]\"]) assert 'action'", "LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '6.bin'), 1) # Creates a 1 MiB file", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', exclusion_test_folder, '--object-prefix', 'exclusion_test/', '--exclude',", "of the bucket object_name = 'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name) object_content = generate_random_string(CONTENT_STRING_LENGTH)", "'next-start-with' in result.output # Bulk puts objects, uses multipart where", "len(bulk_get_object_to_content) # We should skip over no objects since we", "assert parsed_result['uploaded-objects'] == {} # If we say to --no-overwrite", "# makedirs creates all subfolders recursively root_bulk_put_folder = 'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf", "'subfolder/blah.pdf') in remaining_objects assert '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder)", "= invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir',", "bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--object-prefix', 'bulk_put_prefix_test/']) # No failures or skips", "in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording def test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder = os.path.join('tests',", "% OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT == 0: # Put in one big file", "= invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder])", "If we say to --no-overwrite then everything should be skipped.", "you wish to continue?'.format(num_objects_to_delete) else: confirm_prompt = 'WARNING: This command", "'subfolder', 'subfolder2', 'xyz.jpg')) for expected_file in expected_uploaded_files: target_file = os.path.join(target_download_folder,", "files in six.iteritems(folders_to_files): folder_path = os.path.join(exclusion_test_folder, folder) if not os.path.exists(folder_path):", "tests import util from tests import test_config_container from mimetypes import", "be no prompts result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "object_content # makedirs creates all subfolders recursively root_bulk_put_folder = 'tests/temp/bulk_put_{}'.format(util.random_number_string())", "parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures'] == {} expected_uploaded_files", "target_file.replace(os.path.join(target_download_folder, 'inclusion_test'), inclusion_test_folder) assert os.path.exists(target_file) assert filecmp.cmp(original_file, target_file, shallow=False) #", "parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 3 result = invoke([", "parsed_result = json.loads(result.output) assert len(parsed_result['data']) == 33 assert 'next-start-with' in", "without --overwrite then everything should be skipped. There should be", "that we're reporting back that we uploaded the right files", "object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) shutil.rmtree(download_folder) # Tests that multipart params are applied:", "--overwrite then everything should be skipped. There should be prompts", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b/c/', '--delimiter', '/']) for", "object_storage_client.delete_bucket(util.NAMESPACE, bucket_name) def get_number_of_objects_in_bucket(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None,", "back that we uploaded the right files assert get_object_name_from_path(root_bulk_put_folder, source_file_path)", "downloaded_file_path, shallow=False) # Sanity check that we're reporting back that", "invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run']) parsed_result =", "False for line in lines: if object_begun or line.startswith('{'): object_begun", "# coding: utf-8 # Copyright (c) 2016, 2019, Oracle and/or", "= invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir',", "if object_begun or line.startswith('{'): object_begun = True json_str += line", "assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Pull everything down and verify", "os.path.join('tests', 'temp', 'multipart_get_large_files') if not os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir, '1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES)", "f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield # Tear down stuff by deleting all the", "parsed_result['uploaded-objects'] == {} # If we say to --no-overwrite then", "remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording def test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder = os.path.join('tests', 'temp',", "in result.output assert '/a/Object_1' in result.output result = invoke(['os', 'object',", "2: object_name = 'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name) elif i % 5 ==", "assert 'next-start-with' in result.output # Bulk puts objects, uses multipart", "Download objects with exclusions to make sure that works target_download_folder", "content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder)", "matches for object_name in bulk_get_object_to_content: if object_name[0] == '/' or", "can go both ways) then chop the front bit off", "comes after the JSON data def parse_json_response_from_mixed_output(output): lines = output.split('\\n')", "0: # Put in the occasional file with a reasonable", "# Generate test data for different operations: # # Bulk", "us a/b/<object>, a/b/c/<object> and a/b/c/d/<object> invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "'--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table']) assert 'action' in result.output assert", "parse_json_response_from_mixed_output(output): lines = output.split('\\n') json_str = '' object_begun = False", "parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 4 result = invoke([ 'os', 'object',", "print(result.output) # Ensure that content matches for object_name in bulk_get_object_to_content:", "obj: obj.name, response.data.objects)) assert len(remaining_objects) == 2 assert '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf')", "target_download_folder, '--prefix', 'inclusion_test/', '--include', 'subfolder/subfolder2/xyz.jpg' ]) assert os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder',", "paths (Windows can go both ways) then chop the front", "create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "'3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '6.bin'),", "len(parsed_result['uploaded-objects']) == len(object_name_set) for object_name in object_name_set: assert object_name in", "'--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table', '--query', \"[?object=='Object_0'][object]\"]) assert 'action' not", "0 for dir_name, subdir_list, file_list in os.walk(source_folder): for file in", "assert filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'), os.path.join(large_file_verify_dir, '1.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'), os.path.join(large_file_verify_dir, '2.bin'))", "them, but this doesn't match with paths on Windows. Using", "= oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE,", "sure you want to overwrite it?' not in result.output assert", "os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'blah.pdf')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2',", "create a valid file, but for testing is probably OK", "'--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) # No failures or skips and", "bulk_get_prefix_to_object['/a'].append(object_name) else: # At the root of the bucket object_name", "bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder, object_name) with", "parse_json_response_from_mixed_output(result.output) assert 'Are you sure you want to overwrite it?'", "fields='name', retrieve_all=True ) num_objects_in_bucket = 0 for response in list_object_responses:", "specified --src-dir {} (expanded to: {}) does not exist'.format(fake_directory, fake_directory)", "'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request)", "and/or its affiliates. All rights reserved. import filecmp import json", "with --content-type as auto @util.skip_while_rerecording def test_bulk_put_auto_content_type(): result = invoke(['os',", "command will delete {} objects. Are you sure you wish", "# Remove all directories recursively shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording def test_normalize_object_name_path(): assert", "you sure you wish to continue?'.format(num_objects_to_delete) else: confirm_prompt = 'WARNING:", "drop the leading slash (we drop path separators from the", "= parse_json_response_from_mixed_output(result.output) assert len(parsed_result['skipped-objects']) == 0 shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_no_objects(vcr_fixture):", "There should be no prompts result = invoke(['os', 'object', 'bulk-upload',", "= {} bulk_get_prefix_to_object = { 'a/b/c/d': [], 'a/b/c': [], 'a/b':", "Windows and so our matching/comparison works. For Linux/Unix/macOS this doesn't", "in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We should skip", "bulk_get_bucket_name, '--download-dir', download_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you", "object names are taken from the file path of the", "get us a/b/<object>, a/b/c/<object> and a/b/c/d/<object> invoke(['os', 'object', 'bulk-download', '--namespace',", "uploaded the right files assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path)) in parsed_result['uploaded-objects'] shutil.rmtree(download_folder)", "assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png')) assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png')) assert", "for different operations: # # Bulk Get: create a new", "set() bulk_put_mid_sized_files = set() root_bulk_put_folder = None bulk_put_bucket_name = None", "json.loads(result.output) assert len(parsed_result['data']) == 33 assert 'next-start-with' in result.output #", "= 'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name) object_content = generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name, object_name, object_content)", "'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "bulk_put_bucket_name, '--src-dir', fake_directory]) assert 'UsageError' in result.output assert 'The specified", "'--overwrite']) # No failures or skips and we uploaded everything", "create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_put_bucket_name = create_bucket_request.name subfolders = ['', 'subfolder1',", "# / in the paths (Windows can go both ways)", "util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--part-size', '10' ]) parsed_result =", "{} # If we say to --no-overwrite then everything should", "download_folder = 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) # This should get us a/b/<object>, a/b/c/<object>", "pytest import oci import services.object_storage.src.oci_cli_object_storage as oci_cli_object_storage import os import", "filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'), os.path.join(large_file_verify_dir, '4.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'), os.path.join(large_file_verify_dir, '5.bin')) assert", "'xyz.jpg')) for expected_file in expected_uploaded_files: target_file = os.path.join(target_download_folder, expected_file) original_file", "oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\') @util.skip_while_rerecording def test_get_all_objects_in_bucket(vcr_fixture): download_folder = 'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result =", "create_bucket_request.name = 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name)", "filecmp import json import pytest import oci import services.object_storage.src.oci_cli_object_storage as", "For the bulk operations, object names are taken from the", "invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', large_file_root_dir", "== len(bulk_get_object_to_content) # We should skip over no objects since", "download_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_result['skipped-objects']) == 0 shutil.rmtree(download_folder)", "1) # Creates a 1 MiB file for variety invoke([", "expected_uploaded_files = [ '{}{}'.format('exclusion_test/', 'test_file2.png'), '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/',", ") # Download objects with exclusions to make sure that", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) parsed_result", "as different directories on disk) for i in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if", "== 2 assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png')) assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder',", "None bulk_put_large_files = set() bulk_put_mid_sized_files = set() root_bulk_put_folder = None", "download_prefix_no_slash='exclusion_test' ) # Download objects with exclusions to make sure", "'temp', 'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='inclusion_test' ) # Download", "'--include', '*/[ax]yz.jpg' # Matches subfolder/subfolder2/xyz.jpg ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "= None bulk_put_large_files = set() bulk_put_mid_sized_files = set() root_bulk_put_folder =", "can verify results bulk_get_object_to_content = {} bulk_get_prefix_to_object = { 'a/b/c/d':", "parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 4 result = invoke([", "should be no prompts result = invoke(['os', 'object', 'bulk-upload', '--namespace',", "(Windows can go both ways) then chop the front bit", "create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client,", "open(file_path, 'w') as f: f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield # Tear down stuff", "'subfolder', 'blah.pdf')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'byz.jpg')) assert", "reasonable size so that we can force multipart util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES)", "'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='exclusion_test' ) # Download objects", "be prompts result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "'--bucket-name', create_bucket_request.name, '--src-dir', large_file_root_dir ]) large_file_verify_dir = os.path.join('tests', 'temp', 'multipart_get_large_files_verify')", "--overwrite result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--overwrite']) parsed_result", "== {} assert len(parsed_result['uploaded-objects']) == len(object_name_set) for object_name in object_name_set:", "os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) # Delete objects with inclusions", "set(bulk_get_object_to_content.keys()) # Dry-run against a folder and all subfolders result", "with open(file_path, 'r') as content_file: content = content_file.read() assert content", "bucket_name=bucket_name, prefix=None, start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) num_objects_in_bucket", "afterwards # Bulk Delete: uses the folders and files generated", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--overwrite'])", "skipped. There should be prompts result = invoke(['os', 'object', 'bulk-upload',", "assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with' not in result.output result", "disk) for i in range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if i % 5 ==", "10 == 0: # Put in the occasional file with", "parsed_result = json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with' not", "128MiB) @util.skip_while_rerecording def test_bulk_put_default_options(): result = invoke(['os', 'object', 'bulk-upload', '--namespace',", "# If we say to --no-overwrite then everything should be", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table', '--query', \"[?object=='Object_0'][object]\"])", "obj.name) object_storage_client.delete_bucket(util.NAMESPACE, bucket_name) def get_number_of_objects_in_bucket(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client,", "subfolder/subfolder2/xyz.jpg ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert", "file) downloaded_file_path = source_file_path.replace(source_folder, actual_download_folder) if downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash) in normalized_expected_uploaded_files:", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--no-multipart', '--overwrite' ]) parsed_result", "can force multipart util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path) else: with open(file_path, 'w')", "= { '': ['test_file1.txt', 'test_file2.png'], 'subfolder': ['blah.pdf', 'hello.txt', 'testfile3.png'], 'subfolder/subfolder2':", "result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all'])", "'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name) elif i % 5 == 2: object_name =", "or skips and we uploaded everything parsed_result = parse_json_response_from_mixed_output(result.output) assert", "fake_directory = 'tests/folder/not/exist' result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "[ '{}{}'.format('exclusion_test/', 'test_file2.png'), '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/',", "with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield # Generate test data for different operations:", "objects, then tear it all down afterwards # Bulk Put:", "utf-8 # Copyright (c) 2016, 2019, Oracle and/or its affiliates.", "object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name, object_name, object_content) bulk_get_object_to_content[object_name] = object_content # makedirs creates", "operations, object names are taken from the file path of", "target_download_folder, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/subfolder2/*.png', '--exclude', 'subfolder/blah.pdf', ])", "bulk_get_bucket_name, '--download-dir', download_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure", "@util.skip_while_rerecording def test_bulk_put_auto_content_type(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "then chop the front bit off def get_object_name_from_path(path_root, full_path): return", "for object_name in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder, object_name) with open(file_path,", "def test_normalize_object_name_path(): assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path',", "'--src-dir', root_bulk_put_folder]) num_objects_to_delete = get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Sanity check that the", "3: object_name = 'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name) elif i % 5 ==", "'--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_result['skipped-objects']) == 0 shutil.rmtree(download_folder) @util.skip_while_rerecording", "result = invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "'--prefix', 'inclusion_test/', '--include', 'subfolder/subfolder2/xyz.jpg' ]) assert os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2',", "front bit off def get_object_name_from_path(path_root, full_path): return full_path.replace(os.sep, '/').replace(path_root +", "== [] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder)", "file in files: file_path = os.path.join(folder_path, file) with open(file_path, 'w')", "len(remaining_objects) == 2 assert '{}{}'.format('exclusion_test/', 'subfolder/blah.pdf') in remaining_objects assert '{}{}'.format('exclusion_test/',", "then everything should be skipped. There should be no prompts", "plah.pdf, qlah.pdf or rlah.pdf ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects']", "everything should be skipped. There should be no prompts result", "doesn't appear to have an impact normalized_expected_uploaded_files = [] for", "create_bucket_request.name = 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name)", "for file in file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path =", "'table']) assert 'action' in result.output assert 'object' in result.output assert", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are", "# Download objects with inclusions to make sure that works", "not os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) for expected_file in expected_uploaded_files:", "test_delete(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000)) create_bucket_request.compartment_id =", "@util.skip_while_rerecording def test_get_multipart(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id", "= invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all']) parsed_result", "end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) remaining_objects = [] for", "in remaining_objects assert '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording", "os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png') ) # Delete objects with exclusions", "'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object',", "won't create a valid file, but for testing is probably", "'--bucket-name', bulk_put_bucket_name, '--src-dir', inclusion_test_folder, '--object-prefix', 'inclusion_test/', '--include', '*.txt', # Matches", "assert not os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) for expected_file in", "# We should skip over no objects since we --overwrite", "create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result", "down afterwards # Bulk Put: create a folder structure containing", "= parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures'] == {}", "= '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if not os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf) create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name", "is probably OK f.write(generate_random_string(CONTENT_STRING_LENGTH)) result = invoke([ 'os', 'object', 'bulk-upload',", "target_file, shallow=False) # Download a specific object with inclusions invoke([", "# Bulk puts objects with --content-type as auto @util.skip_while_rerecording def", "util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke([ 'os',", "assert 'UsageError' in result.output assert 'The specified --src-dir {} (expanded", "Make some files for include/exclude folders_to_files = { '': ['test_file1.txt',", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--force'", "try and put it in the same bucket without --overwrite", "source_file_path.replace(source_folder, actual_download_folder) if downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash) in normalized_expected_uploaded_files: files_compared += 1", "so that we can force multipart util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path) else:", "for f in expected_uploaded_files: assert f in parsed_result['uploaded-objects'] download_folder_base =", "to be multipart uploaded) # - Try to upload with", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--output',", "bulk_get_bucket_name, '--prefix', 'a/b/', '--dry-run']) parsed_result = json.loads(result.output) expected_objects = set().union(bulk_get_prefix_to_object['a/b'],", "= 100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT = 20 CONTENT_STRING_LENGTH = 5000 MID_SIZED_FILE_IN_MEBIBTYES =", "in it assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) > 0 result = invoke(['os',", "commands = ['--debug'] + commands return util.invoke_command(commands, ** args) def", "delete at least {} objects. Are you sure you wish", "you sure you want to overwrite it?' in result.output assert", "and we uploaded everything parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] ==", "assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) shutil.rmtree(download_folder) # Tests", "expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')) # This is not in our --include switches", "bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/*.png', '--include',", "len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with' not in result.output result =", "object_name) with open(file_path, 'r') as content_file: content = content_file.read() assert", "== set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='exclusion_test/',", "os.path.join(exclusion_test_folder, 'subfolder', 'testfile3.png'), os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png') ) # Delete", "i % 10 == 0: # Put in the occasional", "we've created a reasonable number of objects in this test", "os.path.join(target_download_folder, expected_file) original_file = target_file.replace(os.path.join(target_download_folder, 'inclusion_test'), inclusion_test_folder) assert os.path.exists(target_file) assert", "'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', target_download_folder, '--output',", "and large files, then tear it all down afterwards #", "that the bucket has things in it assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name)", "'etag' not in result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace',", "subfolder/testfile3.png, subfolder/subfolder2/testfile4.png '--include', 'subfolder/[b]lah.pdf', # Matches subfolder/blah.pdf '--include', '*/[ax]yz.jpg' #", "folder, files in six.iteritems(folders_to_files): folder_path = os.path.join(exclusion_test_folder, folder) if not", "create_bucket_request.name) # Since we've created a reasonable number of objects", "anything '--exclude', 'subfolder/subfolder2/xyz.jpg', '--exclude', 'subfolder/[spqr]lah.pdf' # blah.pdf should still be", "Assumes that nothing # comes after the JSON data def", "some objects, then tear it all down afterwards # Bulk", "fake_directory]) assert 'UsageError' in result.output assert 'The specified --src-dir {}", "create_bucket_request.name = 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name)", "os.path.join(exclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for file in files:", "# Download objects with exclusions to make sure that works", "1): file_path = '{}/object_{}'.format(full_folder, i) if i != 0 and", "= invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix',", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) # No failures or skips", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--force']) parsed_result = parse_json_response_from_mixed_output(result.output)", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) assert 'There are no objects", "= 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir',", "def test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_inclusion_test') if not os.path.exists(inclusion_test_folder):", "For Linux/Unix/macOS this doesn't appear to have an impact normalized_expected_uploaded_files", "stuff other than JSON in it. Assumes that nothing #", "file in file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder,", "assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert files_compared == len(expected_uploaded_files)", "download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert guess_type(source_file_path) ==", "Since we've created a reasonable number of objects in this", "== {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder = 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os',", "'--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_object_to_content.keys()) # Dry-run", "yield # Generate test data for different operations: # #", "object_name[0] == '/' or object_name[0] == '\\\\': file_path = os.path.join(download_folder,", "target_download_folder = os.path.join(download_folder_base, 'get_with_include') invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "# This is not in our --include switches assert not", "os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png') ) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'subfolder', 'testfile3.png'), os.path.join(target_download_folder,", "in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) # Bulk puts objects with --content-type as", "elif i != 0 and i % 10 == 0:", "a specific object with inclusions invoke([ 'os', 'object', 'bulk-download', '--namespace',", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b/c/', '--delimiter',", "result.output result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "bulk put @pytest.fixture(scope='module', autouse=True) def generate_test_data(object_storage_client): global bulk_get_object_to_content, bulk_get_bucket_name, root_bulk_put_folder,", "assert set(parsed_result['deleted-objects']) == set(bulk_get_object_to_content.keys()) # Dry-run against a folder and", "test_get_all_objects_in_bucket(vcr_fixture): download_folder = 'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result = invoke(['os', 'object', 'bulk-download', '--namespace',", "Additionally there should be no prompts result = invoke(['os', 'object',", "create_bucket_request.name = 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name)", "= os.path.join(download_folder, object_name) with open(file_path, 'r') as content_file: content =", "len(bulk_get_prefix_to_object['a/b/c']) + len(bulk_get_prefix_to_object['a/b/c/d']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_no_subdirectory(vcr_fixture): download_folder", "util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', large_file_verify_dir, '--multipart-download-threshold', '128']) assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) ==", "'--src-dir', root_bulk_put_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure", "{} assert parsed_result['uploaded-objects'] == {} # If we say to", "confirm_prompt = 'WARNING: This command will delete {} objects. Are", "OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT = 20 CONTENT_STRING_LENGTH = 5000 MID_SIZED_FILE_IN_MEBIBTYES = 20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES", "= source_file_path.replace(root_bulk_put_folder, actual_download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) #", "!= 0 and i % OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT == 0: # Put", "list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert len(remaining_objects) == 3 assert", "create_bucket_request.name) > 0 result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client,", "put @pytest.fixture(scope='module', autouse=True) def generate_test_data(object_storage_client): global bulk_get_object_to_content, bulk_get_bucket_name, root_bulk_put_folder, bulk_put_large_files,", "delete in {}'.format(create_bucket_request.name) in result.output delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_delete_dry_run(vcr_fixture):", "3 assert '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png') in", "'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png') ] # Check", "Sanity check assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) # We should skip", "create_bucket_request) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "to continue?'.format(num_objects_to_delete) else: confirm_prompt = 'WARNING: This command will delete", "has things in it assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) > 0 result", "'os_bulk_upload_inclusion_test') if not os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder) # Make some files for", "oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result", "have stuff other than JSON in it. Assumes that nothing", "= set() root_bulk_put_folder = None bulk_put_bucket_name = None @pytest.fixture def", "'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path)) in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) @util.skip_while_rerecording def test_bulk_put_with_non_existent_folder(): fake_directory =", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--content-type', 'auto', '--overwrite']) #", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '33', '--page-size', '3']) parsed_result =", "test_bulk_put_default_options(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') ]", "= os.path.join('tests', 'temp', 'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='inclusion_test' )", "'--bucket-name', create_bucket_request.name]) if num_objects_to_delete >= 1000: confirm_prompt = 'WARNING: This", "assert confirm_prompt in result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace',", "util.create_large_file(os.path.join(large_file_root_dir, '1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir,", "[] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result", "** args): if debug is True: commands = ['--debug'] +", "'--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures']", "'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--part-size',", "'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') ] # Check that we uploaded what", "'test_file2.png')) assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png')) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'test_file2.png'),", "Pull JSON data out of output which may have stuff", "uploaded what we said we did assert len(parsed_result['uploaded-objects']) == len(expected_uploaded_files)", "an impact normalized_expected_uploaded_files = [] for euf in expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf))", "download_folder = 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "os.path.join('tests', 'temp', 'multipart_get_large_files_verify') invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name,", "invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder,", "on Windows. Using normpath converts these of # \"\\\" on", "delete_bucket_and_all_items(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None,", "assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_put_with_prefix(): result", "files in six.iteritems(folders_to_files): folder_path = os.path.join(inclusion_test_folder, folder) if not os.path.exists(folder_path):", "a reasonable number of objects in this test suite, it's", "bulk_put_bucket_name, '--src-dir', inclusion_test_folder, '--object-prefix', 'inclusion_test/', '--include', '*.txt', # Matches test_file1.txt,", "objects with exclusions result = invoke([ 'os', 'object', 'bulk-delete', '--namespace',", "'a/b/c': [], 'a/b': [], '/a': [], '': [] } bulk_get_bucket_name", "No failures or skips and we uploaded everything parsed_result =", "'--include', '*.txt', '--include', 'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'exclusion_test/', '--exclude',", "test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_inclusion_test') if not os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder)", "create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace',", "len(remaining_objects) == 3 assert '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png') in remaining_objects assert '{}{}'.format('inclusion_test/',", "= os.path.join('tests', 'temp', 'os_bulk_upload_inclusion_test') if not os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder) # Make", "'--exclude', '*.ps1', # Shouldn't match anything '--exclude', 'subfolder/subfolder2/xyz.jpg', '--exclude', 'subfolder/[spqr]lah.pdf'", "we uploaded everything parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == []", "if object_name[0] == '/' or object_name[0] == '\\\\': file_path =", "valid file, but for testing is probably OK f.write(generate_random_string(CONTENT_STRING_LENGTH)) result", "parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures'] == {} assert", "--all and --limit parameters @util.skip_while_rerecording def test_list_all_objects_operations(vcr_fixture): result = invoke(['os',", "root_bulk_put_folder, bulk_put_large_files, bulk_put_mid_sized_files, bulk_put_bucket_name # Create a test bucket create_bucket_request", "Check that the bucket is now empty assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name)", "bulk_put_bucket_name = None @pytest.fixture def vcr_fixture(request): with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield #", "commands return util.invoke_command(commands, ** args) def get_count_of_files_in_folder_and_subfolders(directory): file_count = 0", "folder and all subfolders result = invoke(['os', 'object', 'bulk-delete', '--namespace',", "= set() for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder): for file", "object_storage_client.delete_object(util.NAMESPACE, bucket_name, obj.name) object_storage_client.delete_bucket(util.NAMESPACE, bucket_name) def get_number_of_objects_in_bucket(object_storage_client, bucket_name): list_object_responses =", "= set() bulk_put_mid_sized_files = set() root_bulk_put_folder = None bulk_put_bucket_name =", "= 'WARNING: This command will delete at least {} objects.", "assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\')", "os.path.join(large_file_verify_dir, '2.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'), os.path.join(large_file_verify_dir, '3.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'),", "assert len(parsed_dry_run_result['deleted-objects']) == 3 result = invoke([ 'os', 'object', 'bulk-delete',", "content_file: content = content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b'])", "root_bulk_put_folder]) # No failures or skips and we uploaded everything", "set(parsed_result['deleted-objects']) == expected_objects # Dry-run against a folder and no", "rights reserved. import filecmp import json import pytest import oci", "assert content == bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c/d']: file_path =", "'subfolder/subfolder2/xyz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording def test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder =", "drop path separators from the front to avoid unexpected results)", "assert parsed_result['uploaded-objects'] == {} # Now we force it result", "not os.path.exists(folder_path): os.makedirs(folder_path) for file in files: file_path = os.path.join(folder_path,", "object_name_set: assert object_name in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) # Bulk puts objects", "fields='name', retrieve_all=True ) remaining_objects = [] for response in list_objects_responses:", "os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder) # Make some files for include/exclude folders_to_files =", "as oci_cli_object_storage import os import random import shutil import six", "# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All", "'bulk_put_prefix_test/']) # No failures or skips and we uploaded everything", "'subfolder/[spqr]lah.pdf' # blah.pdf should still be included because it's not", "set(parsed_result['skipped-objects']) == object_name_set assert parsed_result['upload-failures'] == {} assert parsed_result['uploaded-objects'] ==", "assert 'There are no objects to delete in {}'.format(create_bucket_request.name) in", "return file_count def generate_random_string(length): if test_config_container.using_vcr_with_mock_responses(): return 'a' * length", "get_count_of_files_in_folder_and_subfolders(download_folder) # We should skip over all objects since there", "== oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\') @util.skip_while_rerecording def", "'--bucket-name', bulk_get_bucket_name, '--limit', '47']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) ==", ") # Download objects with inclusions to make sure that", "# Ensure that content matches for object_name in bulk_get_object_to_content: if", "create_bucket_request.name, '--download-dir', large_file_verify_dir, '--multipart-download-threshold', '128']) assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) == 6 assert", "os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf) create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id =", "inclusions result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "to --no-overwrite then everything should be skipped. There should be", "file, \\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"]) assert 'file' in result.output assert 'opc-content-md5' in", "Creates a 1 MiB file for variety invoke([ 'os', 'object',", "prefix='inclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) remaining_objects =", "matching/comparison works. For Linux/Unix/macOS this doesn't appear to have an", "assert parsed_result['upload-failures'] == {} assert parsed_result['uploaded-objects'] == {} # Now", "% 5 == 3: object_name = 'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name) elif i", "root_bulk_put_folder = 'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf = '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if not os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf)", "content == bulk_get_object_to_content[object_name] assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def", "set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='exclusion_test/', start=None,", "skips and we uploaded everything parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects']", "guess_type(downloaded_file_path) # Sanity check that we're reporting back that we", "filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) # Sanity check that we're reporting back", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', target_download_folder, '--output', 'table', ]) delete_bucket_and_all_items(object_storage_client,", "# Matches subfolder/subfolder2/xyz.jpg ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] ==", "'4.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '5.bin'), os.path.join(large_file_verify_dir, '5.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'), os.path.join(large_file_verify_dir,", "'--no-multipart', '--overwrite' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == []", "def get_object_name_from_path(path_root, full_path): return full_path.replace(os.sep, '/').replace(path_root + '/', '') def", "should skip over no objects since we --overwrite result =", "parsed_result['delete-failures'] == {} assert len(parsed_result['deleted-objects']) == num_objects_to_delete # Check that", "so our matching/comparison works. For Linux/Unix/macOS this doesn't appear to", "front to avoid unexpected results) object_name = '/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name) else:", "parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_object_to_content.keys()) # Dry-run against", "in result.output assert 'opc-content-md5' in result.output assert 'etag' not in", "in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) # If we try and put", "= os.path.join('tests', 'temp', 'multipart_get_large_files_verify') invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--force' ]) parsed_result", "six.iteritems(folders_to_files): folder_path = os.path.join(exclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for", "Matches subfolder/blah.pdf '--include', '*/[ax]yz.jpg' # Matches subfolder/subfolder2/xyz.jpg ]) parsed_result =", "util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_get_bucket_name = create_bucket_request.name # Create", "'a/b']) for object_name in bulk_get_prefix_to_object['a/b']: file_path = os.path.join(download_folder, object_name) with", "a folder and no subfolders result = invoke(['os', 'object', 'bulk-delete',", "os.path.join(large_file_verify_dir, '5.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'), os.path.join(large_file_verify_dir, '6.bin')) shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client,", "a valid file, but for testing is probably OK f.write(generate_random_string(CONTENT_STRING_LENGTH))", "assert len(parsed_result['skipped-objects']) == 0 shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_no_objects(vcr_fixture): download_folder =", "with inclusions result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "output.split('\\n') json_str = '' object_begun = False for line in", "= os.path.join(download_folder, download_prefix_no_slash) files_compared = 0 for dir_name, subdir_list, file_list", "opportunity to test using the --all and --limit parameters @util.skip_while_rerecording", "sure you want to overwrite it?' in result.output assert len(parsed_result['skipped-objects'])", "'exclusion_test', 'subfolder', 'testfile3.png') ) # Delete objects with exclusions result", "'exclusion_test/', '--exclude', '*.txt', '--exclude', '*.ps1', # Shouldn't match anything '--exclude',", "the JSON data def parse_json_response_from_mixed_output(output): lines = output.split('\\n') json_str =", "are equal) download_folder = 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "assert 'object' in result.output assert '/a/Object_1' in result.output result =", "create_bucket_request.name) @util.skip_while_rerecording def test_bulk_put_with_prefix(): result = invoke(['os', 'object', 'bulk-upload', '--namespace',", "'\\\\') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath')", "containing small and large files, then tear it all down", "expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='inclusion_test' ) # Download objects with inclusions", "'--page-size', '20']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert", "assert len(parsed_result['data']) == 33 assert 'next-start-with' in result.output # Bulk", "'*.jpg', '--exclude', 'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures']", "default of 128MiB) @util.skip_while_rerecording def test_bulk_put_default_options(): result = invoke(['os', 'object',", "'subfolder/subfolder2/testfile4.png') ] # Check that we uploaded what we said", "= parse_json_response_from_mixed_output(result.output) assert 'Are you sure you want to overwrite", "to upload with a part size of 10MiB (this will", "to a/ on the file system because we drop the", "result.output assert set(parsed_result['skipped-objects']) == object_name_set assert parsed_result['upload-failures'] == {} assert", "bucket_name=bulk_put_bucket_name, prefix='inclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) remaining_objects", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) if num_objects_to_delete >= 1000: confirm_prompt", "affiliates. All rights reserved. import filecmp import json import pytest", "LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '6.bin'), 1)", "end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) num_objects_in_bucket = 0 for", "subfolder/subfolder2/blag.txt '--include', 'subfolder/*.png', # Matches subfolder/testfile3.png, subfolder/subfolder2/testfile4.png '--include', 'subfolder/[b]lah.pdf', #", "= invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output',", "LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path) elif i != 0 and i % 10", "you want to overwrite it?' not in result.output assert len(parsed_result['skipped-objects'])", "retrieve_all=True ) for response in list_object_responses: for obj in response.data.objects:", "len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_and_subdirectories(vcr_fixture): download_folder = 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name)", "with multipart disabled @util.skip_while_rerecording def test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--part-size', '10'", "= 'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf = '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if not os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf) create_bucket_request", "[] } bulk_get_bucket_name = None bulk_put_large_files = set() bulk_put_mid_sized_files =", "'\\\\') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/')", "'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '47']) parsed_result = json.loads(result.output)", "be skipped. There should be no prompts result = invoke(['os',", "result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir',", "not os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder) # Make some files for include/exclude folders_to_files", "go both ways) then chop the front bit off def", "5000 MID_SIZED_FILE_IN_MEBIBTYES = 20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 150 # Default multipart", "assert 'opc-content-md5' in result.output assert 'etag' not in result.output result", "content = content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_object_to_content) ==", "at various heirarchy levels (to be surfaced as different directories", "not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'testfile4.png')) assert get_count_of_files_in_folder_and_subfolders(target_download_folder) == 2", "file path of the thing we uploaded. Normalize to #", "because it's not slah.pdf, plah.pdf, qlah.pdf or rlah.pdf ]) parsed_result", "invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all', '--page-size', '20'])", "source_file_path)) shutil.rmtree(download_folder) # Tests that multipart params are applied: #", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--output', 'table',", "def test_delete_dry_run(vcr_fixture): # Dry-run against entire bucket result = invoke(['os',", "a/b/c/d/<object> invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder,", "'--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', 'bulk_put_prefix_test/']) actual_download_folder = os.path.join(download_folder, 'bulk_put_prefix_test')", "since there is no --overwrite. There should be prompts result", "open(file_path, 'r') as content_file: content = content_file.read() assert content ==", "util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--force']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] ==", "assert 'etag' not in result.output result = invoke(['os', 'object', 'bulk-delete',", "= util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result =", "invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table'])", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--delimiter', '/', '--dry-run']) parsed_result", "all down afterwards # Bulk Put: create a folder structure", "= oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE,", "object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_put_bucket_name = create_bucket_request.name subfolders = ['', 'subfolder1', 'subfolder1/subfolder2',", "oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None, start=None, end=None, limit=1000, delimiter=None,", "'w') as f: f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield # Tear down stuff by", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all']) parsed_result = json.loads(result.output) assert len(parsed_result['data'])", "= util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_put_bucket_name =", "subfolder in subfolders: if subfolder == '': full_folder = root_bulk_put_folder", "MID_SIZED_FILE_IN_MEBIBTYES = 20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 150 # Default multipart is", "create_bucket_request) bulk_put_bucket_name = create_bucket_request.name subfolders = ['', 'subfolder1', 'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3']", "shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording def test_normalize_object_name_path(): assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert '/this/is/a/path'", "'--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are", "slah.pdf, plah.pdf, qlah.pdf or rlah.pdf ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "'bulk_put_prefix_test/']) actual_download_folder = os.path.join(download_folder, 'bulk_put_prefix_test') for dir_name, subdir_list, file_list in", "'': [] } bulk_get_bucket_name = None bulk_put_large_files = set() bulk_put_mid_sized_files", "not slah.pdf, plah.pdf, qlah.pdf or rlah.pdf ]) parsed_result = parse_json_response_from_mixed_output(result.output)", "assert parsed_result['upload-failures'] == {} expected_uploaded_files = [ '{}{}'.format('exclusion_test/', 'test_file2.png'), '{}{}'.format('exclusion_test/',", "it all down afterwards # Bulk Delete: uses the folders", "populate it with some objects, then tear it all down", "Put in one big file per subfolder util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path)", "as auto @util.skip_while_rerecording def test_bulk_put_auto_content_type(): result = invoke(['os', 'object', 'bulk-upload',", "'temp', 'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='exclusion_test' ) # Download", "bulk_get_object_to_content[object_name] assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_directory_and_subdirectories(vcr_fixture): download_folder", "a reasonable size so that we can force multipart util.create_large_file(file_path,", "test using the --all and --limit parameters @util.skip_while_rerecording def test_list_all_objects_operations(vcr_fixture):", "== {} assert parsed_result['uploaded-objects'] == {} # If we say", "folder_path = os.path.join(exclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for file", "expected_file) original_file = target_file.replace(os.path.join(target_download_folder, 'inclusion_test'), inclusion_test_folder) assert os.path.exists(target_file) assert filecmp.cmp(original_file,", "len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Pull everything down and verify that", "len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder = 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace',", "source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert guess_type(source_file_path)", "'--include', 'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] ==", "[], '': [] } bulk_get_bucket_name = None bulk_put_large_files = set()", "'--prefix', 'a/b']) for object_name in bulk_get_prefix_to_object['a/b']: file_path = os.path.join(download_folder, object_name)", "'--download-dir', download_folder, '--prefix', 'a/b/c/', '--delimiter', '/']) for object_name in bulk_get_prefix_to_object['a/b/c']:", "it's not slah.pdf, plah.pdf, qlah.pdf or rlah.pdf ]) parsed_result =", "return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) # Pull JSON data", "appears in destination and they are equal) download_folder = 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name)", "from tests import util from tests import test_config_container from mimetypes", "% 5 == 4: object_name = 'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif i", "@util.skip_while_rerecording def test_bulk_put_with_prefix(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "downloaded_file_path = source_file_path.replace(root_bulk_put_folder, actual_download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False)", "in object_name_set: assert object_name in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) # Bulk puts", "'xyz.jpg')) # Delete objects with inclusions result = invoke([ 'os',", "= output.split('\\n') json_str = '' object_begun = False for line", "generated for bulk put @pytest.fixture(scope='module', autouse=True) def generate_test_data(object_storage_client): global bulk_get_object_to_content,", "This is not in our --include switches assert not os.path.exists(os.path.join(target_download_folder,", "CONTENT_STRING_LENGTH = 5000 MID_SIZED_FILE_IN_MEBIBTYES = 20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 150 #", "oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='inclusion_test/', start=None, end=None, limit=1000, delimiter=None,", "# Create items at various heirarchy levels (to be surfaced", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b/c/',", "'--output', 'table']) assert 'action' in result.output assert 'object' in result.output", "100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT = 20 CONTENT_STRING_LENGTH = 5000 MID_SIZED_FILE_IN_MEBIBTYES = 20", "are applied: # # - Try to upload with a", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) print(result.output)", "per subfolder util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path) elif i != 0 and", "'r') as content_file: content = content_file.read() assert content == bulk_get_object_to_content[object_name]", "# Sanity check assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) # We should", "and all subfolders result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "/ in the paths (Windows can go both ways) then", "'byz.jpg', 'testfile4.png'] } for folder, files in six.iteritems(folders_to_files): folder_path =", "object_content = generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name, object_name, object_content) bulk_get_object_to_content[object_name] = object_content", "assert content == bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c']: file_path =", "--content-type as auto @util.skip_while_rerecording def test_bulk_put_auto_content_type(): result = invoke(['os', 'object',", "'{}{}'.format('inclusion_test/', 'subfolder/testfile3.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png') in remaining_objects assert", "len(file_list) return file_count def generate_random_string(length): if test_config_container.using_vcr_with_mock_responses(): return 'a' *", "def test_list_all_objects_operations(vcr_fixture): result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name',", "assert get_count_of_files_in_folder_and_subfolders(large_file_verify_dir) == 6 assert filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'), os.path.join(large_file_verify_dir, '1.bin')) assert", "large and mid-sized files to be multipart uploaded) # -", "else: return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) # Pull JSON", "set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d']) assert set(parsed_result['deleted-objects']) == expected_objects # Dry-run against", "files and check they are the same invoke(['os', 'object', 'bulk-download',", "assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result =", "limit=1000, delimiter=None, fields='name', retrieve_all=True ) for response in list_object_responses: for", "object_name in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r')", "'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', exclusion_test_folder, '--object-prefix',", "multipart is 128MiB # Holds the objects we create and", "util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object', 'bulk-upload', '--namespace',", "'/', '--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording", "in os.walk(root_bulk_put_folder): for file in file_list: source_file_path = os.path.join(dir_name, file)", "'test_file1.txt'), '{}{}'.format('inclusion_test/', 'subfolder/hello.txt'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/',", "it?' not in result.output assert set(parsed_result['skipped-objects']) == object_name_set assert parsed_result['upload-failures']", "down and verify that the files match (everything in source", "]) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) shutil.rmtree(target_download_folder) def invoke(commands, debug=False, ** args): if", "os.path.join(download_folder_base, 'get_with_exclude') invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "bucket_name, obj.name) object_storage_client.delete_bucket(util.NAMESPACE, bucket_name) def get_number_of_objects_in_bucket(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects(", "Windows. Using normpath converts these of # \"\\\" on Windows", "= 0 for dir_name, subdir_list, file_list in os.walk(directory): file_count =", "'6.bin')) shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) # Since we've created a", "download_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure you", "it in the same bucket without --overwrite then everything should", "download_prefix_no_slash + '/']) # The strings in the expected_uploaded_files array", "converts these of # \"\\\" on Windows and so our", "'verify_os_bulk_upload_inclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='inclusion_test' ) # Download objects", "request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='exclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True", "retrieve_all=True ) num_objects_in_bucket = 0 for response in list_object_responses: num_objects_in_bucket", "Generate test data for different operations: # # Bulk Get:", "os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png')) assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png')) assert filecmp.cmp(", "assert 'action' not in result.output assert '/a/Object_1' not in result.output", "bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d']) assert set(parsed_result['deleted-objects']) == expected_objects # Dry-run against a", "len(parsed_dry_run_result['deleted-objects']) == 4 result = invoke([ 'os', 'object', 'bulk-delete', '--namespace',", "assert len(parsed_result['deleted-objects']) == num_objects_to_delete # Check that the bucket is", "elif i % 5 == 3: object_name = 'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name)", "folder and no subfolders result = invoke(['os', 'object', 'bulk-delete', '--namespace',", "should be prompts result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "'multipart_get_large_files') if not os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir, '1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '2.bin'),", "= parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 4 result = invoke([ 'os',", "then tear it all down afterwards # Bulk Put: create", "in os.walk(directory): file_count = file_count + len(file_list) return file_count def", "f: # For non-text extension types this won't create a", "will force the large and mid-sized files to be multipart", "this test suite, it's a good opportunity to test using", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) print(result.output) # Ensure", "are taken from the file path of the thing we", "(c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder]) num_objects_to_delete", "@util.skip_while_rerecording def test_get_directory_no_subdirectory(vcr_fixture): download_folder = 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace',", "= invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder])", "path separators from the front to avoid unexpected results) object_name", "os.walk(directory): file_count = file_count + len(file_list) return file_count def generate_random_string(length):", "string from tests import util from tests import test_config_container from", "os.path.join('tests', 'temp', 'os_bulk_upload_inclusion_test') if not os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder) # Make some", "client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='inclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name',", "os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir, '1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '3.bin'),", "['xyz.jpg', 'blag.txt', 'byz.jpg', 'testfile4.png'] } for folder, files in six.iteritems(folders_to_files):", "if subfolder == '': full_folder = root_bulk_put_folder else: full_folder =", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'exclusion_test/', '--exclude', '*.jpg',", "exclusion_test_folder, '--object-prefix', 'exclusion_test/', '--exclude', '*.txt', '--exclude', '*.ps1', # Shouldn't match", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'exclusion_test/',", "json.loads(result.output) expected_objects = set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d']) assert set(parsed_result['deleted-objects']) == expected_objects", "sure you want to overwrite it?' in result.output assert set(parsed_result['skipped-objects'])", "= json.loads(result.output) expected_objects = set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d']) assert set(parsed_result['deleted-objects']) ==", "'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '33', '--page-size', '3']) parsed_result", "OK f.write(generate_random_string(CONTENT_STRING_LENGTH)) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "'--src-dir', inclusion_test_folder, '--object-prefix', 'inclusion_test/', '--include', '*.txt', # Matches test_file1.txt, subfolder/hello.txt,", "Download a specific object with inclusions invoke([ 'os', 'object', 'bulk-download',", "\"[?object=='Object_0'][object]\"]) assert 'action' not in result.output assert '/a/Object_1' not in", "result.output assert '/a/Object_1' in result.output result = invoke(['os', 'object', 'bulk-delete',", "'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output)", "} for folder, files in six.iteritems(folders_to_files): folder_path = os.path.join(inclusion_test_folder, folder)", "should still be included because it's not slah.pdf, plah.pdf, qlah.pdf", "bucket has things in it assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) > 0", "'a/b': [], '/a': [], '': [] } bulk_get_bucket_name = None", "'next-start-with' not in result.output result = invoke(['os', 'object', 'list', '--namespace',", "bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name, prefix=None, start=None,", "subfolders: if subfolder == '': full_folder = root_bulk_put_folder else: full_folder", "suite, it's a good opportunity to test using the --all", "shutil.rmtree(download_folder) # Bulk puts objects with --content-type as auto @util.skip_while_rerecording", "file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(source_folder, actual_download_folder) if", "it?' in result.output assert set(parsed_result['skipped-objects']) == object_name_set assert parsed_result['upload-failures'] ==", "Delete objects with exclusions result = invoke([ 'os', 'object', 'bulk-delete',", "def get_number_of_objects_in_bucket(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bucket_name,", "down afterwards # Bulk Delete: uses the folders and files", "debug is True: commands = ['--debug'] + commands return util.invoke_command(commands,", "object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir',", "in bulk_get_prefix_to_object['a/b/c/d']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as", "list_object_responses: for obj in response.data.objects: object_storage_client.delete_object(util.NAMESPACE, bucket_name, obj.name) object_storage_client.delete_bucket(util.NAMESPACE, bucket_name)", "= invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) if num_objects_to_delete", "of # \"\\\" on Windows and so our matching/comparison works.", "in six.iteritems(folders_to_files): folder_path = os.path.join(inclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path)", "now empty assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) == 0 delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--content-type', 'auto', '--overwrite']) # No", "# Creates a 1 MiB file for variety invoke([ 'os',", "invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', target_download_folder,", "a folder structure containing small and large files, then tear", "Remove all directories recursively shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording def test_normalize_object_name_path(): assert '/this/is/a/path'", "operations: # # Bulk Get: create a new bucket and", "\"/\" in them, but this doesn't match with paths on", "oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\') assert 'thisisapath' ==", "'--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--part-size', '10' ]) parsed_result = parse_json_response_from_mixed_output(result.output)", "assert '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(exclusion_test_folder) @util.skip_while_rerecording def test_delete_when_no_objects_in_bucket(vcr_fixture,", "True json_str += line return json.loads(json_str) # For the bulk", "'--all', '--page-size', '20']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET", "'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name) object_content = generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name, object_name, object_content) bulk_get_object_to_content[object_name]", "objects we create and their content so that we can", "oci import services.object_storage.src.oci_cli_object_storage as oci_cli_object_storage import os import random import", "in normalized_expected_uploaded_files: files_compared += 1 assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path,", "# blah.pdf should still be included because it's not slah.pdf,", "and their content so that we can verify results bulk_get_object_to_content", "4: object_name = 'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif i % 5 ==", "Using normpath converts these of # \"\\\" on Windows and", "i in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT + 1): file_path = '{}/object_{}'.format(full_folder, i) if", "'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request)", "out of output which may have stuff other than JSON", "} for folder, files in six.iteritems(folders_to_files): folder_path = os.path.join(exclusion_test_folder, folder)", "util.create_large_file(os.path.join(large_file_root_dir, '4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '6.bin'), 1) #", "that nothing # comes after the JSON data def parse_json_response_from_mixed_output(output):", "# Since we've created a reasonable number of objects in", "= oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE,", "result.output @util.skip_while_rerecording def test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_inclusion_test') if", "'--download-dir', download_folder]) object_name_set = set() for dir_name, subdir_list, file_list in", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all', '--page-size', '20']) parsed_result = json.loads(result.output)", "result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We should skip over", "128MiB # Holds the objects we create and their content", "'{}{}'.format('exclusion_test/', 'subfolder/blah.pdf') in remaining_objects assert '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg') in remaining_objects shutil.rmtree(target_download_folder)", "but for testing is probably OK f.write(generate_random_string(CONTENT_STRING_LENGTH)) result = invoke([", "== len(object_name_set) for object_name in object_name_set: assert object_name in parsed_result['uploaded-objects']", "'/a': [], '': [] } bulk_get_bucket_name = None bulk_put_large_files =", "== OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET assert 'next-start-with' not in result.output result = invoke(['os',", "that we uploaded the right files assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path)) in", "'get_with_include') invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir',", "'*.txt', '--include', 'subfolder/*.png', '--include', 'subfolder/blah.pdf', ]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')) # This", "'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/*.png', '--include', 'subfolder/blah.pdf', ]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg'))", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--dry-run'", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', inclusion_test_folder, '--object-prefix', 'inclusion_test/', '--include', '*.txt', #", "download_prefix_no_slash) files_compared = 0 for dir_name, subdir_list, file_list in os.walk(source_folder):", "assert len(parsed_result['uploaded-objects']) == len(expected_uploaded_files) for f in expected_uploaded_files: assert f", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) # Sanity check assert", "create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--output', 'table', '--query', \"[?action=='Uploaded'].{file: file, \\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"])", "in expected_uploaded_files: assert f in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp',", "result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir',", "= invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run']) parsed_result", "'batman']) assert 0 == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_multipart(object_storage_client): create_bucket_request", "file with a reasonable size so that we can force", "'--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--dry-run' ])", "parsed_result = json.loads(result.output) assert len(parsed_result['data']) == 47 assert 'next-start-with' in", "the same invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir',", "'--content-type', 'auto', '--overwrite']) # No failures or skips and we", "import util from tests import test_config_container from mimetypes import guess_type", "limit=1000, delimiter=None, fields='name', retrieve_all=True ) remaining_objects = [] for response", "file) with open(file_path, 'w') as f: # For non-text extension", "if not os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder) # Make some files for include/exclude", "list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert len(remaining_objects) == 2 assert", "util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--no-multipart', '--overwrite' ]) parsed_result =", "1000000)) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request)", "== {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Pull everything down", "not os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf) create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id", "# Bulk Delete: uses the folders and files generated for", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) print(result.output) # Ensure that", "i % 5 == 4: object_name = 'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif", "in list_objects_responses: remaining_objects.extend(map(lambda obj: obj.name, response.data.objects)) assert len(remaining_objects) == 2", "'exclusion_test', 'subfolder', 'subfolder2', 'testfile4.png')) assert get_count_of_files_in_folder_and_subfolders(target_download_folder) == 2 assert os.path.exists(os.path.join(target_download_folder,", "# Tear down stuff by deleting all the things and", "test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_exclusion_test') if not os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder)", "off def get_object_name_from_path(path_root, full_path): return full_path.replace(os.sep, '/').replace(path_root + '/', '')", "root_bulk_put_folder, '--output', 'table', '--query', \"[?action=='Uploaded'].{file: file, \\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"]) assert 'file'", "set(parsed_result['deleted-objects']) == set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording def test_delete(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name", "Delete objects with inclusions result = invoke([ 'os', 'object', 'bulk-delete',", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output)", "5 == 4: object_name = 'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif i %", "in this test suite, it's a good opportunity to test", "f in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files,", "everything parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures']", "'{}{}'.format('inclusion_test/', 'test_file1.txt'), '{}{}'.format('inclusion_test/', 'subfolder/hello.txt'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'),", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder]) object_name_set", "def test_get_directory_and_subdirectories(vcr_fixture): download_folder = 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) # This should get us", "'--bucket-name', bulk_put_bucket_name, '--src-dir', exclusion_test_folder, '--object-prefix', 'exclusion_test/', '--exclude', '*.txt', '--exclude', '*.ps1',", "'--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'batman']) assert 0 == get_count_of_files_in_folder_and_subfolders(download_folder)", "download_prefix_no_slash='inclusion_test' ) # Download objects with inclusions to make sure", "os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir, '1.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES)", "said we did assert len(parsed_result['uploaded-objects']) == len(expected_uploaded_files) for f in", "Oracle and/or its affiliates. All rights reserved. import filecmp import", "== [] assert parsed_result['upload-failures'] == {} expected_uploaded_files = [ '{}{}'.format('exclusion_test/',", "Bulk puts objects, uses multipart where appropriate (when we breach", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) # No failures or", "multipart where appropriate (when we breach the default of 128MiB)", "'subfolder/testfile3.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png') in remaining_objects assert '{}{}'.format('inclusion_test/',", "if debug is True: commands = ['--debug'] + commands return", "file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, actual_download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path,", "parsed_result['upload-failures'] == {} assert parsed_result['uploaded-objects'] == {} # If we", "'a/b/c/', '--delimiter', '/']) for object_name in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder,", "of the thing we uploaded. Normalize to # / in", "test_file1.txt, subfolder/hello.txt, subfolder/subfolder2/blag.txt '--include', 'subfolder/*.png', # Matches subfolder/testfile3.png, subfolder/subfolder2/testfile4.png '--include',", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt',", "'--download-dir', target_download_folder, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/subfolder2/*.png', '--exclude', 'subfolder/blah.pdf',", "= oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE,", "We should skip over all objects since we say --no-overwrite.", "import test_config_container from mimetypes import guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET = 100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT", "== get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/') assert", "os.path.join(download_folder, object_name) with open(file_path, 'r') as content_file: content = content_file.read()", "parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert set(parsed_result['deleted-objects']) == set(parsed_dry_run_result['deleted-objects']) list_objects_responses", "to make sure that works target_download_folder = os.path.join(download_folder_base, 'get_with_exclude') invoke([", "'--bucket-name', create_bucket_request.name, '--download-dir', target_download_folder, '--output', 'table', ]) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) shutil.rmtree(target_download_folder)", "assert '/a/Object_1' in result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace',", "'/a/Object_1' in result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "generate_random_string(length): if test_config_container.using_vcr_with_mock_responses(): return 'a' * length else: return ''.join(random.choice(string.ascii_lowercase)", "create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE,", "Dry-run against a folder and no subfolders result = invoke(['os',", "dir_name, subdir_list, file_list in os.walk(source_folder): for file in file_list: source_file_path", "'10' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert", "include/exclude folders_to_files = { '': ['test_file1.txt', 'test_file2.png'], 'subfolder': ['blah.pdf', 'hello.txt',", "+ commands return util.invoke_command(commands, ** args) def get_count_of_files_in_folder_and_subfolders(directory): file_count =", "os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert guess_type(source_file_path) == guess_type(downloaded_file_path) #", "not in our --include switches assert not os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder',", "with exclusions result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "= 'tests/temp/get_directory_and_subdirectories_{}'.format(bulk_get_bucket_name) # This should get us a/b/<object>, a/b/c/<object> and", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output)", "uploaded the right files assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder,", "then deleting the buckets delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name) # Remove", "assert len(parsed_result['uploaded-objects']) == len(object_name_set) for object_name in object_name_set: assert object_name", "== 0 shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_no_objects(vcr_fixture): download_folder = 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os',", "invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '33', '--page-size',", "puts objects, uses multipart where appropriate (when we breach the", "# Shouldn't match anything '--exclude', 'subfolder/subfolder2/xyz.jpg', '--exclude', 'subfolder/[spqr]lah.pdf' # blah.pdf", "full_folder = os.path.join(root_bulk_put_folder, subfolder) for i in range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT + 1):", "def generate_random_string(length): if test_config_container.using_vcr_with_mock_responses(): return 'a' * length else: return", "if test_config_container.using_vcr_with_mock_responses(): return 'a' * length else: return ''.join(random.choice(string.ascii_lowercase) for", "return num_objects_in_bucket def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder, download_folder, download_prefix_no_slash): # Download uploaded", "There should be prompts result = invoke(['os', 'object', 'bulk-download', '--namespace',", "'{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png') ] # Check that", "object_name_set = set() for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder): for", "delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) # Since we've created a reasonable number of", "['test_file1.txt', 'test_file2.png'], 'subfolder': ['blah.pdf', 'hello.txt', 'testfile3.png'], 'subfolder/subfolder2': ['xyz.jpg', 'blag.txt', 'byz.jpg',", "get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Sanity check that the bucket has things in", "JSON data out of output which may have stuff other", "'--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) print(result.output) # Ensure that content matches", "set(parsed_result['deleted-objects']) == set(bulk_get_object_to_content.keys()) # Dry-run against a folder and all", "actual_download_folder = os.path.join(download_folder, download_prefix_no_slash) files_compared = 0 for dir_name, subdir_list,", "@util.skip_while_rerecording def test_get_files_skipped(): download_folder = 'tests/temp/skip_and_replace_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace',", "'exclusion_test', 'subfolder', 'testfile3.png')) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'test_file2.png'), os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png')", "= os.path.join(inclusion_test_folder, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) for file in", "'UsageError' in result.output assert 'The specified --src-dir {} (expanded to:", "appear to have an impact normalized_expected_uploaded_files = [] for euf", "= 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir',", "= '/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name) else: # At the root of the", "def test_get_all_objects_in_bucket(vcr_fixture): download_folder = 'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result = invoke(['os', 'object', 'bulk-download',", "extension types this won't create a valid file, but for", "be multipart uploaded) # - Try to upload with multipart", "# If we try and put it in the same", "since we --overwrite result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "= 'tests/temp/get_all_{}'.format(bulk_get_bucket_name) result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording def test_delete(object_storage_client):", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--overwrite']) parsed_result =", "from the file path of the thing we uploaded. Normalize", "assert f in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests(", "'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) for expected_file in expected_uploaded_files: target_file =", "empty assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) == 0 delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def", "assert 'bulk_put_prefix_test/{}'.format(get_object_name_from_path(root_bulk_put_folder, source_file_path)) in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) @util.skip_while_rerecording def test_bulk_put_with_non_existent_folder(): fake_directory", "assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording", "['--debug'] + commands return util.invoke_command(commands, ** args) def get_count_of_files_in_folder_and_subfolders(directory): file_count", "we breach the default of 128MiB) @util.skip_while_rerecording def test_bulk_put_default_options(): result", "not os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder) # Make some files for include/exclude folders_to_files", "in result.output assert '/a/Object_1' not in result.output assert 'Object_0' in", "Sanity check that we're reporting back that we uploaded the", "Are you sure you wish to continue?'.format(num_objects_to_delete) assert confirm_prompt in", "'6.bin'), os.path.join(large_file_verify_dir, '6.bin')) shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) # Since we've", "parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) shutil.rmtree(download_folder) # Tests that multipart params are", "bulk_get_bucket_name, '--download-dir', download_folder]) # Sanity check assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder)", "= content_file.read() assert content == bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c']:", "you want to overwrite it?' not in result.output assert set(parsed_result['skipped-objects'])", "did assert len(parsed_result['uploaded-objects']) == len(expected_uploaded_files) for f in expected_uploaded_files: assert", "assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/') assert", "download_folder, download_prefix_no_slash): # Download uploaded files and check they are", "tests import test_config_container from mimetypes import guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET = 100", "uploaded) # - Try to upload with multipart disabled @util.skip_while_rerecording", "test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield # Generate test data for different operations: #", "1 MiB file for variety invoke([ 'os', 'object', 'bulk-upload', '--namespace',", "parameters @util.skip_while_rerecording def test_list_all_objects_operations(vcr_fixture): result = invoke(['os', 'object', 'list', '--namespace',", "works target_download_folder = os.path.join(download_folder_base, 'get_with_exclude') invoke([ 'os', 'object', 'bulk-download', '--namespace',", "def test_bulk_put_auto_content_type(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "'os_bulk_upload_exclusion_test') if not os.path.exists(exclusion_test_folder): os.makedirs(exclusion_test_folder) # Make some files for", "invoke(commands, debug=False, ** args): if debug is True: commands =", "'{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') ] # Check that", "'/']) # The strings in the expected_uploaded_files array have a", "invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/',", "assert parsed_result['upload-failures'] == {} expected_uploaded_files = [ '{}{}'.format('inclusion_test/', 'test_file1.txt'), '{}{}'.format('inclusion_test/',", "'action' not in result.output assert '/a/Object_1' not in result.output assert", "'test_file2.png'], 'subfolder': ['blah.pdf', 'hello.txt', 'testfile3.png'], 'subfolder/subfolder2': ['xyz.jpg', 'blag.txt', 'byz.jpg', 'testfile4.png']", "start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) for response in", "download_folder]) # Sanity check assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) # We", "assert parsed_result['skipped-objects'] == [] assert parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects'])", "== 3 assert '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png')", "= content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder)", "else: # At the root of the bucket object_name =", "= [ '{}{}'.format('inclusion_test/', 'test_file1.txt'), '{}{}'.format('inclusion_test/', 'subfolder/hello.txt'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/blag.txt'), '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png'),", "filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'), os.path.join(large_file_verify_dir, '1.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'), os.path.join(large_file_verify_dir, '2.bin')) assert", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', exclusion_test_folder, '--object-prefix', 'exclusion_test/', '--exclude', '*.txt',", "coding: utf-8 # Copyright (c) 2016, 2019, Oracle and/or its", "bulk_get_bucket_name, root_bulk_put_folder, bulk_put_large_files, bulk_put_mid_sized_files, bulk_put_bucket_name # Create a test bucket", "# Pull everything down and verify that the files match", "import six import string from tests import util from tests", "for folder, files in six.iteritems(folders_to_files): folder_path = os.path.join(exclusion_test_folder, folder) if", "wish to continue?'.format(num_objects_to_delete) assert confirm_prompt in result.output result = invoke(['os',", "assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'blah.pdf')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test',", "to overwrite it?' in result.output assert set(parsed_result['skipped-objects']) == object_name_set assert", "the bucket has things in it assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) >", "--no-overwrite. Additionally there should be no prompts result = invoke(['os',", "'' object_begun = False for line in lines: if object_begun", "'temp', 'multipart_get_large_files_verify') invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir',", "request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='inclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True", "bucket_name) def get_number_of_objects_in_bucket(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE,", "+ '/']) # The strings in the expected_uploaded_files array have", "big file per subfolder util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path) elif i !=", "target_download_folder = os.path.join(download_folder_base, 'get_with_exclude') invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='exclusion_test/', start=None, end=None, limit=1000, delimiter=None,", "create_bucket_request.name) == 0 delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_operation_table_output_query(object_storage_client): create_bucket_request =", "multipart disabled @util.skip_while_rerecording def test_bulk_put_with_multipart_params(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name =", "breach the default of 128MiB) @util.skip_while_rerecording def test_bulk_put_default_options(): result =", "size of 10MiB (this will force the large and mid-sized", "structure containing small and large files, then tear it all", "== len(expected_uploaded_files) for f in expected_uploaded_files: assert f in parsed_result['uploaded-objects']", "json.loads(result.output) assert len(parsed_result['data']) == 47 assert 'next-start-with' in result.output result", "invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) if num_objects_to_delete >=", "buckets delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name) # Remove all directories recursively", "# Check that the bucket is now empty assert get_number_of_objects_in_bucket(object_storage_client,", "because we drop the leading slash (we drop path separators", "full_folder = root_bulk_put_folder else: full_folder = os.path.join(root_bulk_put_folder, subfolder) for i", "Put in the occasional file with a reasonable size so", "i != 0 and i % 10 == 0: #", "create a new bucket and populate it with some objects,", "else: confirm_prompt = 'WARNING: This command will delete {} objects.", "source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(source_folder, actual_download_folder) if downloaded_file_path.replace(actual_download_folder,", "'--exclude', 'subfolder/subfolder2/xyz.jpg', '--exclude', 'subfolder/[spqr]lah.pdf' # blah.pdf should still be included", "assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) == 0 delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def test_bulk_operation_table_output_query(object_storage_client):", "@util.skip_while_rerecording def test_delete_dry_run(vcr_fixture): # Dry-run against entire bucket result =", "'{}/object_{}'.format(full_folder, i) if i != 0 and i % OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT", "assert filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'), os.path.join(large_file_verify_dir, '2.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'), os.path.join(large_file_verify_dir, '3.bin'))", "in result.output target_download_folder = os.path.join('tests', 'temp', create_bucket_request.name) result = invoke([", "Default multipart is 128MiB # Holds the objects we create", "list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='inclusion_test/', start=None, end=None,", "= object_content # makedirs creates all subfolders recursively root_bulk_put_folder =", "@util.skip_while_rerecording def test_bulk_put_with_non_existent_folder(): fake_directory = 'tests/folder/not/exist' result = invoke(['os', 'object',", "expected_objects # Dry-run against a folder and no subfolders result", "sure that works target_download_folder = os.path.join(download_folder_base, 'get_with_include') invoke([ 'os', 'object',", "overwrite it?' not in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) #", "os.makedirs(inclusion_test_folder) # Make some files for include/exclude folders_to_files = {", "prompts result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--force']) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "test_bulk_operation_table_output_query(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID", "check that the bucket has things in it assert get_number_of_objects_in_bucket(object_storage_client,", "result.output assert 'object' in result.output assert '/a/Object_1' in result.output result", "util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "want to overwrite it?' not in result.output assert set(parsed_result['skipped-objects']) ==", "file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as content_file: content", "assert 'The specified --src-dir {} (expanded to: {}) does not", "Download objects with inclusions to make sure that works target_download_folder", "you sure you wish to continue?'.format(num_objects_to_delete) assert confirm_prompt in result.output", "variety invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir',", "'object' in result.output assert '/a/Object_1' in result.output result = invoke(['os',", "create_bucket_request.name, '--download-dir', target_download_folder, '--output', 'table', ]) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) shutil.rmtree(target_download_folder) def", "'--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--force' ])", "continue?'.format(num_objects_to_delete) else: confirm_prompt = 'WARNING: This command will delete {}", "* length else: return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) #", "bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name) # Remove all directories recursively shutil.rmtree(root_bulk_put_folder) @util.skip_while_rerecording", "subdir_list, file_list in os.walk(source_folder): for file in file_list: source_file_path =", "util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path) else: with open(file_path, 'w') as f: f.write(generate_random_string(CONTENT_STRING_LENGTH))", "'--bucket-name', create_bucket_request.name]) assert 'There are no objects to delete in", "oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID,", "equivalent to a/ on the file system because we drop", "# Matches subfolder/testfile3.png, subfolder/subfolder2/testfile4.png '--include', 'subfolder/[b]lah.pdf', # Matches subfolder/blah.pdf '--include',", "'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include',", "> 0 result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "== object_name_set assert parsed_result['upload-failures'] == {} assert parsed_result['uploaded-objects'] == {}", "'WARNING: This command will delete at least {} objects. Are", "in it. Assumes that nothing # comes after the JSON", "objects, uses multipart where appropriate (when we breach the default", "'47']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == 47 assert 'next-start-with'", "we uploaded what we said we did assert len(parsed_result['uploaded-objects']) ==", "args) def get_count_of_files_in_folder_and_subfolders(directory): file_count = 0 for dir_name, subdir_list, file_list", "'/' or object_name[0] == '\\\\': file_path = os.path.join(download_folder, object_name[1:]) else:", "= util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object', 'bulk-delete', '--namespace',", "{} objects. Are you sure you wish to continue?'.format(num_objects_to_delete) else:", "'subfolder/subfolder2': ['xyz.jpg', 'blag.txt', 'byz.jpg', 'testfile4.png'] } for folder, files in", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include',", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg',", "result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name]) assert", "'--src-dir', large_file_root_dir ]) large_file_verify_dir = os.path.join('tests', 'temp', 'multipart_get_large_files_verify') invoke(['os', 'object',", "down stuff by deleting all the things and then deleting", "'--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result =", "parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] == {} assert set(parsed_result['deleted-objects']) ==", "expected_uploaded_files: assert f in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_inclusion_test')", "line in lines: if object_begun or line.startswith('{'): object_begun = True", "skip over all objects since we say --no-overwrite. Additionally there", "'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix',", "assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b']) + len(bulk_get_prefix_to_object['a/b/c']) + len(bulk_get_prefix_to_object['a/b/c/d'])", "'--src-dir', root_bulk_put_folder, '--part-size', '10' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects']", "bulk_put_large_files.add(file_path) elif i != 0 and i % 10 ==", "bulk_get_bucket_name, '--limit', '33', '--page-size', '3']) parsed_result = json.loads(result.output) assert len(parsed_result['data'])", "assert object_name in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) # Bulk puts objects with", "bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b']) + len(bulk_get_prefix_to_object['a/b/c']) + len(bulk_get_prefix_to_object['a/b/c/d']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder)", "result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "object_name, object_content) bulk_get_object_to_content[object_name] = object_content # makedirs creates all subfolders", "by deleting all the things and then deleting the buckets", "'--limit', '33', '--page-size', '3']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) ==", "create_bucket_request.name) @util.skip_while_rerecording def test_delete_dry_run(vcr_fixture): # Dry-run against entire bucket result", "in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) shutil.rmtree(download_folder) # Tests that multipart params", "sure you wish to continue?'.format(num_objects_to_delete) else: confirm_prompt = 'WARNING: This", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--delimiter', '/', '--dry-run'])", "create_bucket_request.name # Create items at various heirarchy levels (to be", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', download_prefix_no_slash", "test_bulk_put_with_prefix(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "full_path.replace(os.sep, '/').replace(path_root + '/', '') def delete_bucket_and_all_items(object_storage_client, bucket_name): list_object_responses =", "bulk_get_bucket_name, '--download-dir', download_folder]) print(result.output) # Ensure that content matches for", "folders and files generated for bulk put @pytest.fixture(scope='module', autouse=True) def", "shutil.rmtree(download_folder) # Tests that multipart params are applied: # #", "'subfolder1', 'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3'] for subfolder in subfolders: if subfolder ==", "source_file_path)) in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) @util.skip_while_rerecording def test_bulk_put_with_non_existent_folder(): fake_directory = 'tests/folder/not/exist'", "'--bucket-name', bulk_get_bucket_name, '--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_object_to_content.keys())", "== oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\') assert '/this/is/a/path'", "target_download_folder, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/*.png', '--include', 'subfolder/blah.pdf', ])", "parsed_result['uploaded-objects'] shutil.rmtree(download_folder) # Bulk puts objects with --content-type as auto", "== set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='inclusion_test/',", "as content_file: content = content_file.read() assert content == bulk_get_object_to_content[object_name] for", "'testfile3.png') ) # Delete objects with exclusions result = invoke([", "result.output result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name,", "'inclusion_test/', '--include', 'subfolder/subfolder2/xyz.jpg' ]) assert os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg'))", "in file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(source_folder, actual_download_folder)", "skip over all objects since there is no --overwrite. There", "'table', ]) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) shutil.rmtree(target_download_folder) def invoke(commands, debug=False, ** args):", "= source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output)", "params are applied: # # - Try to upload with", "= parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 3 result = invoke([ 'os',", "This command will delete {} objects. Are you sure you", "'--bucket-name', bulk_get_bucket_name, '--limit', '33', '--page-size', '3']) parsed_result = json.loads(result.output) assert", "len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We should skip over no objects", "None bulk_put_bucket_name = None @pytest.fixture def vcr_fixture(request): with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield", "'test_file2.png') ) assert filecmp.cmp( os.path.join(exclusion_test_folder, 'subfolder', 'testfile3.png'), os.path.join(target_download_folder, 'exclusion_test', 'subfolder',", "10MiB (this will force the large and mid-sized files to", "= None @pytest.fixture def vcr_fixture(request): with test_config_container.create_vcr(cassette_library_dir='services/object_storage/tests/cassettes').use_cassette('object_storage_bulk_operations_{name}.yml'.format(name=request.function.__name__)): yield # Generate", "oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID,", "'subfolder/subfolder2/testfile4.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') in remaining_objects shutil.rmtree(target_download_folder) shutil.rmtree(inclusion_test_folder)", "'action' in result.output assert 'object' in result.output assert '/a/Object_1' in", "parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder, download_folder=download_folder_base,", "def invoke(commands, debug=False, ** args): if debug is True: commands", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include',", "len(bulk_get_object_to_content) # We should skip over all objects since we", "get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder = 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "output which may have stuff other than JSON in it.", "and they are equal) download_folder = 'tests/temp/verify_files_{}'.format(bulk_put_bucket_name) invoke(['os', 'object', 'bulk-download',", "We should skip over no objects since we --overwrite result", "source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) # Sanity", "+ len(response.data.objects) return num_objects_in_bucket def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder, download_folder, download_prefix_no_slash): #", "20 CONTENT_STRING_LENGTH = 5000 MID_SIZED_FILE_IN_MEBIBTYES = 20 LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES = 150", "included because it's not slah.pdf, plah.pdf, qlah.pdf or rlah.pdf ])", "assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) # If we", "{ 'a/b/c/d': [], 'a/b/c': [], 'a/b': [], '/a': [], '':", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--no-multipart', '--overwrite' ])", "'--delimiter', '/', '--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_prefix_to_object['a/b'])", "= 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE,", "'{}{}'.format('exclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('exclusion_test/', 'subfolder/testfile3.png'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/byz.jpg'), '{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png') ] #", "get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_multipart(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name =", "or rlah.pdf ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == []", "2019, Oracle and/or its affiliates. All rights reserved. import filecmp", "# Sanity check that the bucket has things in it", "content so that we can verify results bulk_get_object_to_content = {}", "== len(bulk_get_object_to_content) # We should skip over all objects since", "parsed_result['upload-failures'] == {} assert parsed_result['uploaded-objects'] == {} # Now we", "assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) > 0 result = invoke(['os', 'object', 'bulk-delete',", "the buckets delete_bucket_and_all_items(object_storage_client, bulk_get_bucket_name) delete_bucket_and_all_items(object_storage_client, bulk_put_bucket_name) # Remove all directories", "in bulk_get_object_to_content: if object_name[0] == '/' or object_name[0] == '\\\\':", "import random import shutil import six import string from tests", "create_bucket_request) bulk_get_bucket_name = create_bucket_request.name # Create items at various heirarchy", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder]) num_objects_to_delete = get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) #", "and a/b/c/d/<object> invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir',", "'/') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\') @util.skip_while_rerecording def test_get_all_objects_in_bucket(vcr_fixture): download_folder", "retrieve_all=True ) remaining_objects = [] for response in list_objects_responses: remaining_objects.extend(map(lambda", "assert parsed_result['upload-failures'] == {} assert parsed_result['uploaded-objects'] == {} # If", "files generated for bulk put @pytest.fixture(scope='module', autouse=True) def generate_test_data(object_storage_client): global", "in result.output result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name',", "return full_path.replace(os.sep, '/').replace(path_root + '/', '') def delete_bucket_and_all_items(object_storage_client, bucket_name): list_object_responses", "on Windows and so our matching/comparison works. For Linux/Unix/macOS this", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'batman']) assert 0 ==", "limit=1000, delimiter=None, fields='name', retrieve_all=True ) num_objects_in_bucket = 0 for response", "autouse=True) def generate_test_data(object_storage_client): global bulk_get_object_to_content, bulk_get_bucket_name, root_bulk_put_folder, bulk_put_large_files, bulk_put_mid_sized_files, bulk_put_bucket_name", "heirarchy levels (to be surfaced as different directories on disk)", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output)", "in them, but this doesn't match with paths on Windows.", "match with paths on Windows. Using normpath converts these of", "create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_put_bucket_name", "create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name,", "one big file per subfolder util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path) elif i", "blah.pdf should still be included because it's not slah.pdf, plah.pdf,", "entire bucket result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "return json.loads(json_str) # For the bulk operations, object names are", "files assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) shutil.rmtree(download_folder) #", "'--download-dir', download_folder, '--prefix', 'bulk_put_prefix_test/']) actual_download_folder = os.path.join(download_folder, 'bulk_put_prefix_test') for dir_name,", "'--include', 'subfolder/[b]lah.pdf', # Matches subfolder/blah.pdf '--include', '*/[ax]yz.jpg' # Matches subfolder/subfolder2/xyz.jpg", "== get_count_of_files_in_folder_and_subfolders(download_folder) # We should skip over all objects since", "== [] assert parsed_result['upload-failures'] == {} expected_uploaded_files = [ '{}{}'.format('inclusion_test/',", "\"\\\" on Windows and so our matching/comparison works. For Linux/Unix/macOS", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', download_prefix_no_slash +", "in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests', 'temp', 'verify_os_bulk_upload_exclusion_test') verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder,", "'--include', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) ==", "== 6 assert filecmp.cmp(os.path.join(large_file_root_dir, '1.bin'), os.path.join(large_file_verify_dir, '1.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '2.bin'),", "that we can force multipart util.create_large_file(file_path, MID_SIZED_FILE_IN_MEBIBTYES) bulk_put_mid_sized_files.add(file_path) else: with", "len(parsed_dry_run_result['deleted-objects']) == 3 result = invoke([ 'os', 'object', 'bulk-delete', '--namespace',", "'--prefix', 'a/b/', '--dry-run']) parsed_result = json.loads(result.output) expected_objects = set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'],", "util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', large_file_root_dir ]) large_file_verify_dir = os.path.join('tests', 'temp',", "assert 'action' in result.output assert 'object' in result.output assert '/a/Object_1'", "or object_name[0] == '\\\\': file_path = os.path.join(download_folder, object_name[1:]) else: file_path", "inclusions to make sure that works target_download_folder = os.path.join(download_folder_base, 'get_with_include')", "# Make some files for include/exclude folders_to_files = { '':", "the files match (everything in source appears in destination and", "assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/testfile4.png') in remaining_objects assert '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') in remaining_objects", "shutil.rmtree(inclusion_test_folder) @util.skip_while_rerecording def test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_exclusion_test') if", "import shutil import six import string from tests import util", "150 # Default multipart is 128MiB # Holds the objects", "'opc-content-md5' in result.output assert 'etag' not in result.output result =", "test data for different operations: # # Bulk Get: create", "range(OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET): if i % 5 == 4: object_name = 'a/b/c/d/Object_{}'.format(i)", "this doesn't appear to have an impact normalized_expected_uploaded_files = []", "= get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Sanity check that the bucket has things", "assert filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'), os.path.join(large_file_verify_dir, '3.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'), os.path.join(large_file_verify_dir, '4.bin'))", "object_name = 'a/b/c/d/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c/d'].append(object_name) elif i % 5 == 3:", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--no-overwrite']) parsed_result =", "(this will force the large and mid-sized files to be", "object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "prefix='exclusion_test/', start=None, end=None, limit=1000, delimiter=None, fields='name', retrieve_all=True ) remaining_objects =", "'subfolder2', 'byz.jpg')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'testfile4.png')) assert", "util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_put_bucket_name = create_bucket_request.name subfolders = ['',", "= generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE, create_bucket_request.name, object_name, object_content) bulk_get_object_to_content[object_name] = object_content #", "should skip over all objects since we say --no-overwrite. Additionally", "test_get_multipart(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID", "a 1 MiB file for variety invoke([ 'os', 'object', 'bulk-upload',", "if not os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf) create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutTest_{}'.format(util.random_number_string())", "download_folder, '--prefix', 'a/b/c/', '--delimiter', '/']) for object_name in bulk_get_prefix_to_object['a/b/c']: file_path", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--download-dir', large_file_verify_dir, '--multipart-download-threshold', '128'])", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects']) ==", "'--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result =", "for line in lines: if object_begun or line.startswith('{'): object_begun =", "get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Pull everything down and verify that the files", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--object-prefix',", "'testfile3.png'], 'subfolder/subfolder2': ['xyz.jpg', 'blag.txt', 'byz.jpg', 'testfile4.png'] } for folder, files", "= os.path.join(download_folder, 'bulk_put_prefix_test') for dir_name, subdir_list, file_list in os.walk(root_bulk_put_folder): for", "len(parsed_result['uploaded-objects']) == len(expected_uploaded_files) for f in expected_uploaded_files: assert f in", "object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "len(parsed_result['data']) == 33 assert 'next-start-with' in result.output # Bulk puts", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder, '--prefix', download_prefix_no_slash + '/'])", "f in expected_uploaded_files: assert f in parsed_result['uploaded-objects'] download_folder_base = os.path.join('tests',", "set(parsed_dry_run_result['deleted-objects']) list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='inclusion_test/', start=None,", "in the expected_uploaded_files array have a \"/\" in them, but", "return util.invoke_command(commands, ** args) def get_count_of_files_in_folder_and_subfolders(directory): file_count = 0 for", "parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) # If we try and put it", "]) expected_uploaded_files.remove('{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg')) # This is not in our --include", "'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3'] for subfolder in subfolders: if subfolder == '':", "= os.path.join(folder_path, file) with open(file_path, 'w') as f: # For", "{} bulk_get_prefix_to_object = { 'a/b/c/d': [], 'a/b/c': [], 'a/b': [],", "util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_get_bucket_name = create_bucket_request.name # Create items", "util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) bulk_put_bucket_name = create_bucket_request.name subfolders", "LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '6.bin'), 1) # Creates a", "for folder, files in six.iteritems(folders_to_files): folder_path = os.path.join(inclusion_test_folder, folder) if", "subfolder/blah.pdf '--include', '*/[ax]yz.jpg' # Matches subfolder/subfolder2/xyz.jpg ]) parsed_result = parse_json_response_from_mixed_output(result.output)", "all down afterwards # Bulk Delete: uses the folders and", "'{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if not os.path.exists(bulk_put_folder_leaf): os.makedirs(bulk_put_folder_leaf) create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name =", "= 'ObjectStorageTableOutput_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE,", "for dir_name, subdir_list, file_list in os.walk(source_folder): for file in file_list:", "@util.skip_while_rerecording def test_delete(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(random.randint(0, 1000000))", "a new bucket and populate it with some objects, then", "for object_name in bulk_get_prefix_to_object['a/b/c/d']: file_path = os.path.join(download_folder, object_name) with open(file_path,", "downloaded_file_path = source_file_path.replace(root_bulk_put_folder, download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False)", "parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) download_folder = 'tests/temp/verify_files_bulk_put_prefix_{}'.format(bulk_put_bucket_name)", "'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude',", "def test_get_directory_no_subdirectory(vcr_fixture): download_folder = 'tests/temp/get_directory_only_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run',", "verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder, download_folder, download_prefix_no_slash): # Download uploaded files and check", "file_list in os.walk(source_folder): for file in file_list: source_file_path = os.path.join(dir_name,", "it?' in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We should", "'--download-dir', target_download_folder, '--prefix', 'inclusion_test/', '--include', 'subfolder/subfolder2/xyz.jpg' ]) assert os.path.exists(os.path.join(target_download_folder, 'inclusion_test',", "right files assert get_object_name_from_path(root_bulk_put_folder, source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) #", "'--object-prefix', 'bulk_put_prefix_test/']) # No failures or skips and we uploaded", "you sure you want to overwrite it?' not in result.output", "# Download uploaded files and check they are the same", "# Holds the objects we create and their content so", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', inclusion_test_folder, '--object-prefix', 'inclusion_test/',", "def test_get_no_objects(vcr_fixture): download_folder = 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "# Bulk puts objects, uses multipart where appropriate (when we", "i % 5 == 3: object_name = 'a/b/c/Object_{}'.format(i) bulk_get_prefix_to_object['a/b/c'].append(object_name) elif", "'5.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '6.bin'), os.path.join(large_file_verify_dir, '6.bin')) shutil.rmtree(large_file_root_dir) shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name)", "obj: obj.name, response.data.objects)) assert len(remaining_objects) == 3 assert '{}{}'.format('inclusion_test/', 'subfolder/testfile3.png')", "in result.output # Bulk puts objects, uses multipart where appropriate", "{ '': ['test_file1.txt', 'test_file2.png'], 'subfolder': ['blah.pdf', 'hello.txt', 'testfile3.png'], 'subfolder/subfolder2': ['xyz.jpg',", "at least {} objects. Are you sure you wish to", "# - Try to upload with a part size of", "response.data.objects: object_storage_client.delete_object(util.NAMESPACE, bucket_name, obj.name) object_storage_client.delete_bucket(util.NAMESPACE, bucket_name) def get_number_of_objects_in_bucket(object_storage_client, bucket_name): list_object_responses", "create a folder structure containing small and large files, then", "'/') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path',", "objects since we say --no-overwrite. Additionally there should be no", "len(bulk_get_prefix_to_object['a/b']) + len(bulk_get_prefix_to_object['a/b/c']) + len(bulk_get_prefix_to_object['a/b/c/d']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording def", "[], 'a/b/c': [], 'a/b': [], '/a': [], '': [] }", "= json.loads(result.output) assert len(parsed_result['data']) == 33 assert 'next-start-with' in result.output", "'\\\\': file_path = os.path.join(download_folder, object_name[1:]) else: file_path = os.path.join(download_folder, object_name)", "guess_type(source_file_path) == guess_type(downloaded_file_path) # Sanity check that we're reporting back", "object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) large_file_root_dir = os.path.join('tests', 'temp', 'multipart_get_large_files') if not os.path.exists(large_file_root_dir):", "- Try to upload with multipart disabled @util.skip_while_rerecording def test_bulk_put_with_multipart_params(object_storage_client):", "Matches test_file1.txt, subfolder/hello.txt, subfolder/subfolder2/blag.txt '--include', 'subfolder/*.png', # Matches subfolder/testfile3.png, subfolder/subfolder2/testfile4.png", "source_file_path) in parsed_result['uploaded-objects'] object_name_set.add(get_object_name_from_path(root_bulk_put_folder, source_file_path)) # If we try and", "should be prompts result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE,", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--no-overwrite']) parsed_result", "get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "and put it in the same bucket without --overwrite then", "'tests/folder/not/exist' result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "shutil.rmtree(large_file_verify_dir) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) # Since we've created a reasonable number", "Now we force it result = invoke(['os', 'object', 'bulk-upload', '--namespace',", "3 result = invoke([ 'os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name',", "create_bucket_request.name, object_name, object_content) bulk_get_object_to_content[object_name] = object_content # makedirs creates all", "'a/b/', '--dry-run']) parsed_result = json.loads(result.output) expected_objects = set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d'])", "verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=inclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='inclusion_test' ) # Download objects with", "num_objects_in_bucket = num_objects_in_bucket + len(response.data.objects) return num_objects_in_bucket def verify_downloaded_folders_for_inclusion_exclusion_tests(expected_uploaded_files, source_folder,", "bulk_put_bucket_name, '--prefix', 'exclusion_test/', '--exclude', '*.jpg', '--exclude', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result", "range(OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT + 1): file_path = '{}/object_{}'.format(full_folder, i) if i !=", "'--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 3 result", "content = content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b']) +", "'--prefix', 'a/b/', '--delimiter', '/', '--dry-run']) parsed_result = json.loads(result.output) assert set(parsed_result['deleted-objects'])", "test_delete_when_no_objects_in_bucket(vcr_fixture, object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(util.random_number_string()) create_bucket_request.compartment_id =", "assert parsed_result['delete-failures'] == {} assert len(parsed_result['deleted-objects']) == num_objects_to_delete # Check", "'--exclude', 'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) ==", "\\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"]) assert 'file' in result.output assert 'opc-content-md5' in result.output", "@pytest.fixture(scope='module', autouse=True) def generate_test_data(object_storage_client): global bulk_get_object_to_content, bulk_get_bucket_name, root_bulk_put_folder, bulk_put_large_files, bulk_put_mid_sized_files,", "actual_download_folder) if downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash) in normalized_expected_uploaded_files: files_compared += 1 assert", "\"[?action=='Uploaded'].{file: file, \\\"opc-content-md5\\\": \\\"opc-content-md5\\\"}\"]) assert 'file' in result.output assert 'opc-content-md5'", "is not in our --include switches assert not os.path.exists(os.path.join(target_download_folder, 'inclusion_test',", "result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run'])", "'2.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '3.bin'), os.path.join(large_file_verify_dir, '3.bin')) assert filecmp.cmp(os.path.join(large_file_root_dir, '4.bin'), os.path.join(large_file_verify_dir,", "JSON data def parse_json_response_from_mixed_output(output): lines = output.split('\\n') json_str = ''", "assert 'Are you sure you want to overwrite it?' not", "parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 3 result = invoke([ 'os', 'object',", "0 for response in list_object_responses: num_objects_in_bucket = num_objects_in_bucket + len(response.data.objects)", "'4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '5.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '6.bin'), 1) # Creates", "subdir_list, file_list in os.walk(directory): file_count = file_count + len(file_list) return", "os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'testfile4.png')) assert get_count_of_files_in_folder_and_subfolders(target_download_folder) == 2 assert", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', inclusion_test_folder, '--object-prefix', 'inclusion_test/', '--include', '*.txt',", "uses the folders and files generated for bulk put @pytest.fixture(scope='module',", "'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all', '--page-size', '20']) parsed_result =", "= [] for euf in expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder = os.path.join(download_folder,", "content == bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder,", "'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) parsed_result = parse_json_response_from_mixed_output(result.output)", "os.path.exists(folder_path): os.makedirs(folder_path) for file in files: file_path = os.path.join(folder_path, file)", "normpath converts these of # \"\\\" on Windows and so", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) # Sanity check", "result = invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir',", "os.makedirs(folder_path) for file in files: file_path = os.path.join(folder_path, file) with", "in expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder = os.path.join(download_folder, download_prefix_no_slash) files_compared = 0", "subfolders recursively root_bulk_put_folder = 'tests/temp/bulk_put_{}'.format(util.random_number_string()) bulk_put_folder_leaf = '{}/subfolder1/subfolder2/subfolder3'.format(root_bulk_put_folder) if not", "invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--no-overwrite'])", "have an impact normalized_expected_uploaded_files = [] for euf in expected_uploaded_files:", "0 shutil.rmtree(download_folder) @util.skip_while_rerecording def test_get_no_objects(vcr_fixture): download_folder = 'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os', 'object',", "large_file_root_dir = os.path.join('tests', 'temp', 'multipart_get_large_files') if not os.path.exists(large_file_root_dir): os.makedirs(large_file_root_dir) util.create_large_file(os.path.join(large_file_root_dir,", "util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) large_file_root_dir = os.path.join('tests', 'temp', 'multipart_get_large_files')", "util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path) elif i != 0 and i %", "== 47 assert 'next-start-with' in result.output result = invoke(['os', 'object',", "euf in expected_uploaded_files: normalized_expected_uploaded_files.append(os.path.normpath(euf)) actual_download_folder = os.path.join(download_folder, download_prefix_no_slash) files_compared =", "= ['--debug'] + commands return util.invoke_command(commands, ** args) def get_count_of_files_in_folder_and_subfolders(directory):", "'--src-dir', root_bulk_put_folder, '--no-multipart', '--overwrite' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects']", "= '{}/object_{}'.format(full_folder, i) if i != 0 and i %", "not in result.output result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE,", "- Try to upload with a part size of 10MiB", "parsed_result = json.loads(result.output) expected_objects = set().union(bulk_get_prefix_to_object['a/b'], bulk_get_prefix_to_object['a/b/c'], bulk_get_prefix_to_object['a/b/c/d']) assert set(parsed_result['deleted-objects'])", "parsed_result['upload-failures'] == {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Pull everything", "download_folder=download_folder_base, download_prefix_no_slash='exclusion_test' ) # Download objects with exclusions to make", "'/').replace(path_root + '/', '') def delete_bucket_and_all_items(object_storage_client, bucket_name): list_object_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects(", "root_bulk_put_folder, '--overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['skipped-objects'] == [] assert", "in os.walk(source_folder): for file in file_list: source_file_path = os.path.join(dir_name, file)", "data for different operations: # # Bulk Get: create a", "'exclusion_test', 'subfolder', 'blah.pdf')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'byz.jpg'))", "elif i % 5 == 2: object_name = 'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name)", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder]) object_name_set = set()", "'subfolder2', 'xyz.jpg')) # Delete objects with inclusions result = invoke([", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table', '--query', \"[?object=='Object_0'][object]\"]) assert", "object_name in object_name_set: assert object_name in parsed_result['uploaded-objects'] shutil.rmtree(download_folder) # Bulk", "should get us a/b/<object>, a/b/c/<object> and a/b/c/d/<object> invoke(['os', 'object', 'bulk-download',", "'--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you", "delimiter=None, fields='name', retrieve_all=True ) remaining_objects = [] for response in", "they are the same invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name',", "unexpected results) object_name = '/a/Object_{}'.format(i) bulk_get_prefix_to_object['/a'].append(object_name) else: # At the", "util.COMPARTMENT_ID object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE,", "= 0 for dir_name, subdir_list, file_list in os.walk(source_folder): for file", "the --all and --limit parameters @util.skip_while_rerecording def test_list_all_objects_operations(vcr_fixture): result =", "OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT == 0: # Put in one big file per", "wish to continue?'.format(num_objects_to_delete) else: confirm_prompt = 'WARNING: This command will", "assert filecmp.cmp( os.path.join(exclusion_test_folder, 'subfolder', 'testfile3.png'), os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png') )", "== oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this/is/a\\\\path', '\\\\') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath') assert 'thisisapath' ==", "assert len(bulk_get_object_to_content) == get_count_of_files_in_folder_and_subfolders(download_folder) # We should skip over all", "os.path.join(folder_path, file) with open(file_path, 'w') as f: # For non-text", "result.output target_download_folder = os.path.join('tests', 'temp', create_bucket_request.name) result = invoke([ 'os',", "test_bulk_put_auto_content_type(): result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name,", "root_bulk_put_folder]) num_objects_to_delete = get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Sanity check that the bucket", "in range(length)) # Pull JSON data out of output which", "result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--force'])", "set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording def test_delete(object_storage_client): create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkDelete_{}'.format(random.randint(0,", "# This should get us a/b/<object>, a/b/c/<object> and a/b/c/d/<object> invoke(['os',", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder, '--no-multipart', '--overwrite'", "'3']) parsed_result = json.loads(result.output) assert len(parsed_result['data']) == 33 assert 'next-start-with'", "@util.skip_while_rerecording def test_bulk_put_get_delete_with_inclusions(object_storage_client): inclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_inclusion_test') if not", "os.walk(source_folder): for file in file_list: source_file_path = os.path.join(dir_name, file) downloaded_file_path", "may have stuff other than JSON in it. Assumes that", "assert os.path.exists(os.path.join(target_download_folder, 'inclusion_test', 'subfolder', 'subfolder2', 'xyz.jpg')) # Delete objects with", "what we said we did assert len(parsed_result['uploaded-objects']) == len(expected_uploaded_files) for", "= os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(source_folder, actual_download_folder) if downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash)", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', large_file_root_dir ]) large_file_verify_dir = os.path.join('tests',", "shutil.rmtree(target_download_folder) def invoke(commands, debug=False, ** args): if debug is True:", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf',", "guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET = 100 OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT = 20 CONTENT_STRING_LENGTH = 5000", "'--download-dir', download_folder, '--prefix', 'a/b']) for object_name in bulk_get_prefix_to_object['a/b']: file_path =", "bulk_put_bucket_name, '--download-dir', download_folder]) object_name_set = set() for dir_name, subdir_list, file_list", "then everything should be skipped. There should be prompts result", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b']) for object_name", "= os.path.join(dir_name, file) downloaded_file_path = source_file_path.replace(root_bulk_put_folder, actual_download_folder) assert os.path.exists(downloaded_file_path) assert", "from the front to avoid unexpected results) object_name = '/a/Object_{}'.format(i)", ") assert filecmp.cmp( os.path.join(exclusion_test_folder, 'subfolder', 'testfile3.png'), os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png')", "invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) parsed_result", "'*.txt', # Matches test_file1.txt, subfolder/hello.txt, subfolder/subfolder2/blag.txt '--include', 'subfolder/*.png', # Matches", "system because we drop the leading slash (we drop path", "util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--prefix', 'inclusion_test/', '--include', '*.txt', '--include', 'subfolder/blah.pdf', '--force'", "subfolder == '': full_folder = root_bulk_put_folder else: full_folder = os.path.join(root_bulk_put_folder,", "'--exclude', '*.jpg', '--exclude', 'subfolder/subfolder2/*.png', '--exclude', 'subfolder/blah.pdf', ]) assert not os.path.exists(os.path.join(target_download_folder,", "to test using the --all and --limit parameters @util.skip_while_rerecording def", "@util.skip_while_rerecording def test_normalize_object_name_path(): assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path') assert '/this/is/a/path' ==", "object_name = 'a/b/Object_{}'.format(i) bulk_get_prefix_to_object['a/b'].append(object_name) elif i % 5 == 1:", "bulk_get_object_to_content, bulk_get_bucket_name, root_bulk_put_folder, bulk_put_large_files, bulk_put_mid_sized_files, bulk_put_bucket_name # Create a test", "create_bucket_request.name) shutil.rmtree(target_download_folder) def invoke(commands, debug=False, ** args): if debug is", "response in list_object_responses: num_objects_in_bucket = num_objects_in_bucket + len(response.data.objects) return num_objects_in_bucket", "verify_downloaded_folders_for_inclusion_exclusion_tests( expected_uploaded_files=expected_uploaded_files, source_folder=exclusion_test_folder, download_folder=download_folder_base, download_prefix_no_slash='exclusion_test' ) # Download objects with", "some files for include/exclude folders_to_files = { '': ['test_file1.txt', 'test_file2.png'],", "'--download-dir', target_download_folder, '--output', 'table', ]) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) shutil.rmtree(target_download_folder) def invoke(commands,", "list_objects_responses = oci_cli_object_storage.objectstorage_cli_extended.retrying_list_objects( client=object_storage_client, request_id=None, namespace=util.NAMESPACE, bucket_name=bulk_put_bucket_name, prefix='exclusion_test/', start=None, end=None,", "the bucket object_name = 'Object_{}'.format(i) bulk_get_prefix_to_object[''].append(object_name) object_content = generate_random_string(CONTENT_STRING_LENGTH) object_storage_client.put_object(util.NAMESPACE,", "util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '47']) parsed_result = json.loads(result.output) assert len(parsed_result['data'])", "'temp', 'os_bulk_upload_inclusion_test') if not os.path.exists(inclusion_test_folder): os.makedirs(inclusion_test_folder) # Make some files", "'Object_0' in result.output target_download_folder = os.path.join('tests', 'temp', create_bucket_request.name) result =", "confirm_prompt = 'WARNING: This command will delete at least {}", "a/b/c/<object> and a/b/c/d/<object> invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name,", "'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--download-dir', target_download_folder, '--prefix', 'inclusion_test/',", "subfolders = ['', 'subfolder1', 'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3'] for subfolder in subfolders:", "0 and i % OBJECTS_TO_CREATE_IN_FOLDER_FOR_BULK_PUT == 0: # Put in", "skip over no objects since we --overwrite result = invoke(['os',", "puts objects with --content-type as auto @util.skip_while_rerecording def test_bulk_put_auto_content_type(): result", "create_bucket_request.name subfolders = ['', 'subfolder1', 'subfolder1/subfolder2', 'subfolder1/subfolder2/subfolder3'] for subfolder in", "using the --all and --limit parameters @util.skip_while_rerecording def test_list_all_objects_operations(vcr_fixture): result", "== 33 assert 'next-start-with' in result.output # Bulk puts objects,", "'--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--force']) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures']", "say --no-overwrite. Additionally there should be no prompts result =", "'subfolder/subfolder2/testfile4.png'), '{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') ] # Check that we", "'temp', create_bucket_request.name) result = invoke([ 'os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "make sure that works target_download_folder = os.path.join(download_folder_base, 'get_with_exclude') invoke([ 'os',", "content = content_file.read() assert content == bulk_get_object_to_content[object_name] for object_name in", "'tests/temp/no_objects_{}'.format(bulk_get_bucket_name) invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder,", "large_file_verify_dir = os.path.join('tests', 'temp', 'multipart_get_large_files_verify') invoke(['os', 'object', 'bulk-download', '--namespace', util.NAMESPACE,", "create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkPutMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client,", "'subfolder', 'subfolder2', 'xyz.jpg')) # Delete objects with inclusions result =", "'bulk-download', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder, '--prefix', 'a/b']) for", "'/']) for object_name in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder, object_name) with", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--object-prefix', 'bulk_put_prefix_test/'])", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_put_bucket_name, '--src-dir', root_bulk_put_folder, '--object-prefix', 'bulk_put_prefix_test/']) # No", "num_objects_to_delete >= 1000: confirm_prompt = 'WARNING: This command will delete", "# Pull JSON data out of output which may have", "file per subfolder util.create_large_file(file_path, LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) bulk_put_large_files.add(file_path) elif i != 0", "{} (expanded to: {}) does not exist'.format(fake_directory, fake_directory) in result.output", "= os.path.join(download_folder, object_name[1:]) else: file_path = os.path.join(download_folder, object_name) with open(file_path,", "assert get_count_of_files_in_folder_and_subfolders(target_download_folder) == 2 assert os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'test_file2.png')) assert os.path.exists(os.path.join(target_download_folder,", "assert len(bulk_get_prefix_to_object['a/b']) + len(bulk_get_prefix_to_object['a/b/c']) + len(bulk_get_prefix_to_object['a/b/c/d']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder) @util.skip_while_rerecording", "'byz.jpg')) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'subfolder2', 'testfile4.png')) assert get_count_of_files_in_folder_and_subfolders(target_download_folder)", "{}) does not exist'.format(fake_directory, fake_directory) in result.output @util.skip_while_rerecording def test_bulk_put_get_delete_with_inclusions(object_storage_client):", "target_file = os.path.join(target_download_folder, expected_file) original_file = target_file.replace(os.path.join(target_download_folder, 'inclusion_test'), inclusion_test_folder) assert", "]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 3 result =", "objects to delete in {}'.format(create_bucket_request.name) in result.output delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording", "these of # \"\\\" on Windows and so our matching/comparison", "with some objects, then tear it all down afterwards #", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run', '--output', 'table']) assert 'action' in", "'{}{}'.format('exclusion_test/', 'subfolder/subfolder2/testfile4.png') ] # Check that we uploaded what we", "invoke([ 'os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', root_bulk_put_folder,", "assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '/') assert 'thisisapath' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('thisisapath', '\\\\')", "large_file_root_dir ]) large_file_verify_dir = os.path.join('tests', 'temp', 'multipart_get_large_files_verify') invoke(['os', 'object', 'bulk-download',", "'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name, '--src-dir', large_file_root_dir ]) large_file_verify_dir", "'subfolder/subfolder2/*.png', '--exclude', 'subfolder/blah.pdf', ]) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'blah.pdf'))", "'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '33', '--page-size', '3'])", "import json import pytest import oci import services.object_storage.src.oci_cli_object_storage as oci_cli_object_storage", "test bucket create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name = 'ObjectStorageBulkGetTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id =", "'testfile3.png'), os.path.join(target_download_folder, 'exclusion_test', 'subfolder', 'testfile3.png') ) # Delete objects with", "util from tests import test_config_container from mimetypes import guess_type OBJECTS_TO_CREATE_IN_BUCKET_FOR_BULK_GET", "'--download-dir', download_folder, '--no-overwrite']) parsed_result = parse_json_response_from_mixed_output(result.output) assert 'Are you sure", "@util.skip_while_rerecording def test_list_all_objects_operations(vcr_fixture): result = invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE,", "shutil import six import string from tests import util from", "'a/b/c/d': [], 'a/b/c': [], 'a/b': [], '/a': [], '': []", "assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) # We should skip over all", "source_file_path.replace(root_bulk_put_folder, actual_download_folder) assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) # Sanity", "== {} assert len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) delete_bucket_and_all_items(object_storage_client, create_bucket_request.name) @util.skip_while_rerecording def", "content_file.read() assert content == bulk_get_object_to_content[object_name] for object_name in bulk_get_prefix_to_object['a/b/c']: file_path", "in bulk_get_prefix_to_object['a/b/c']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as", "'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--all', '--page-size', '20']) parsed_result", "we said we did assert len(parsed_result['uploaded-objects']) == len(expected_uploaded_files) for f", "Linux/Unix/macOS this doesn't appear to have an impact normalized_expected_uploaded_files =", "objects in this test suite, it's a good opportunity to", "# We should skip over all objects since there is", "assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert guess_type(source_file_path) == guess_type(downloaded_file_path) # Sanity", "def test_bulk_put_get_delete_with_exclusions(object_storage_client): exclusion_test_folder = os.path.join('tests', 'temp', 'os_bulk_upload_exclusion_test') if not os.path.exists(exclusion_test_folder):", "'--exclude', 'subfolder/subfolder2/*.png', '--exclude', 'subfolder/blah.pdf', ]) assert not os.path.exists(os.path.join(target_download_folder, 'exclusion_test', 'subfolder',", "json.loads(result.output) assert set(parsed_result['deleted-objects']) == set(bulk_get_prefix_to_object['a/b']) @util.skip_while_rerecording def test_delete(object_storage_client): create_bucket_request =", "+ 1): file_path = '{}/object_{}'.format(full_folder, i) if i != 0", "created a reasonable number of objects in this test suite,", "failures or skips and we uploaded everything parsed_result = parse_json_response_from_mixed_output(result.output)", "{} objects. Are you sure you wish to continue?'.format(num_objects_to_delete) assert", "'2.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '3.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '4.bin'), LARGE_CONTENT_FILE_SIZE_IN_MEBIBYTES) util.create_large_file(os.path.join(large_file_root_dir, '5.bin'),", "Dry-run against a folder and all subfolders result = invoke(['os',", "to overwrite it?' in result.output assert len(parsed_result['skipped-objects']) == len(bulk_get_object_to_content) #", "oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('/this/is/a/path', '/') assert '/this/is/a/path' == oci_cli_object_storage.objectstorage_cli_extended.normalize_object_name_path_for_object_storage('\\\\this\\\\is\\\\a\\\\path', '\\\\') assert '/this/is/a/path' ==", "content_file: content = content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_object_to_content)", "num_objects_to_delete = get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) # Sanity check that the bucket has", "the leading slash (we drop path separators from the front", "content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b/c']) == get_count_of_files_in_folder_and_subfolders(download_folder) shutil.rmtree(download_folder)", "'--bucket-name', bulk_put_bucket_name, '--download-dir', download_folder]) object_name_set = set() for dir_name, subdir_list,", "'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--dry-run']) parsed_result = json.loads(result.output)", "'{}{}'.format('inclusion_test/', 'subfolder/blah.pdf'), '{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') ] # Check that we uploaded", "we uploaded. Normalize to # / in the paths (Windows", "files match (everything in source appears in destination and they", "in bulk_get_prefix_to_object['a/b']: file_path = os.path.join(download_folder, object_name) with open(file_path, 'r') as", "'--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--download-dir', download_folder]) parsed_result = parse_json_response_from_mixed_output(result.output) assert", "bulk_get_object_to_content: if object_name[0] == '/' or object_name[0] == '\\\\': file_path", "+ len(file_list) return file_count def generate_random_string(length): if test_config_container.using_vcr_with_mock_responses(): return 'a'", "files_compared += 1 assert os.path.exists(downloaded_file_path) assert filecmp.cmp(source_file_path, downloaded_file_path, shallow=False) assert", "'ObjectStorageBulkGetMultipartsTest_{}'.format(util.random_number_string()) create_bucket_request.compartment_id = util.COMPARTMENT_ID util.clear_test_data(object_storage_client, util.NAMESPACE, util.COMPARTMENT_ID, create_bucket_request.name) object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request)", "the file system because we drop the leading slash (we", "'subfolder/blah.pdf', '--dry-run' ]) parsed_dry_run_result = parse_json_response_from_mixed_output(result.output) assert len(parsed_dry_run_result['deleted-objects']) == 4", "5 == 1: # This is equivalent to a/ on", "nothing # comes after the JSON data def parse_json_response_from_mixed_output(output): lines", "applied: # # - Try to upload with a part", "create_bucket_request) result = invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name])", "= invoke(['os', 'object', 'list', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--limit', '47'])", "download_folder]) print(result.output) # Ensure that content matches for object_name in", "'{}{}'.format('inclusion_test/', 'subfolder/subfolder2/xyz.jpg') ] # Check that we uploaded what we", "create_bucket_request) result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name', create_bucket_request.name,", "# Create a test bucket create_bucket_request = oci.object_storage.models.CreateBucketDetails() create_bucket_request.name =", "content_file: content = content_file.read() assert content == bulk_get_object_to_content[object_name] assert len(bulk_get_prefix_to_object['a/b/c'])", "inclusion_test_folder, '--object-prefix', 'inclusion_test/', '--include', '*.txt', # Matches test_file1.txt, subfolder/hello.txt, subfolder/subfolder2/blag.txt", "invoke(['os', 'object', 'bulk-delete', '--namespace', util.NAMESPACE, '--bucket-name', bulk_get_bucket_name, '--prefix', 'a/b/', '--dry-run'])", "the bucket is now empty assert get_number_of_objects_in_bucket(object_storage_client, create_bucket_request.name) == 0", "else: with open(file_path, 'w') as f: f.write(generate_random_string(CONTENT_STRING_LENGTH)) yield # Tear", "= source_file_path.replace(source_folder, actual_download_folder) if downloaded_file_path.replace(actual_download_folder, download_prefix_no_slash) in normalized_expected_uploaded_files: files_compared +=", "len(parsed_result['uploaded-objects']) == get_count_of_files_in_folder_and_subfolders(root_bulk_put_folder) result = invoke([ 'os', 'object', 'bulk-upload', '--namespace',", "'--exclude', 'subfolder/blah.pdf', '--force' ]) parsed_result = parse_json_response_from_mixed_output(result.output) assert parsed_result['delete-failures'] ==", "object_storage_client.create_bucket(util.NAMESPACE, create_bucket_request) result = invoke(['os', 'object', 'bulk-upload', '--namespace', util.NAMESPACE, '--bucket-name',", "# For non-text extension types this won't create a valid" ]
[ "t1.join() t1.join() test_set = {} test_set.update(d1) test_set.update(d2) test_set.update(d3) test_set.update(d4) print(len(test_set))", "# TODO: make is an command line argument port =", "= time.time() print(\"testing set\") for k,v in test_set.items(): r.set(k, v)", "partition, d4)) t1.start() t2.start() t3.start() t4.start() t1.join() t1.join() t1.join() t1.join()", "of total operations with 50% Set and 50% Get: {ops}", "v) r.wait(3, 0) print(\"testing get\") for k,v in test_set.items(): r.get(k)", "#!/usr/bin/python3 import random import string import time import subprocess import", "d2)) t3 = threading.Thread(target=generate_string, args = (string_size, partition, d3)) t4", "= {} d3 = {} d4 = {} t1 =", "+ b % len_lc # convert 0..255 to 97..122 key", "= 1000 # TODO: make is an command line argument", "threading.Thread(target=generate_string, args = (string_size, partition, d4)) t1.start() t2.start() t3.start() t4.start()", "sets\") d1 = {} d2 = {} d3 = {}", "(string_size, partition, d2)) t3 = threading.Thread(target=generate_string, args = (string_size, partition,", "TODO: make is an command line argument port = 7000", "print(\"testing get\") for k,v in test_set.items(): r.get(k) r.wait(3, 0) end", "int(size/4) print(\"generating test sets\") d1 = {} d2 = {}", "db=0) start = time.time() print(\"testing set\") for k,v in test_set.items():", "start = time.time() print(\"testing set\") for k,v in test_set.items(): r.set(k,", "key = bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big')) for i, b in enumerate(key): key[i]", "''' for i in range(size): min_lc = ord(b'a') len_lc =", "argument port = 7000 FNULL = open(os.devnull, 'w') string_size =", "os import redis import threading def generate_string(string_size, size, dict): '''", "partition, d2)) t3 = threading.Thread(target=generate_string, args = (string_size, partition, d3))", "tests...\") r = redis.StrictRedis(host='localhost', port=port, db=0) start = time.time() print(\"testing", "port = 7000 FNULL = open(os.devnull, 'w') string_size = 100000", "r = redis.StrictRedis(host='localhost', port=port, db=0) start = time.time() print(\"testing set\")", "bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big')) for i, b in enumerate(key): key[i] = min_lc", "{} test_set.update(d1) test_set.update(d2) test_set.update(d3) test_set.update(d4) print(len(test_set)) print(\"running tests...\") r =", "enumerate(key): key[i] = min_lc + b % len_lc # convert", "= {} t1 = threading.Thread(target=generate_string, args = (string_size, partition, d1))", "for i in range(size): min_lc = ord(b'a') len_lc = 26", "generate_string(string_size, size, dict): ''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters ''' for i in range(size):", "print(len(test_set)) print(\"running tests...\") r = redis.StrictRedis(host='localhost', port=port, db=0) start =", "run time: {runtime}s \\n\\ number of total operations with 50%", "random import string import time import subprocess import os import", "an command line argument port = 7000 FNULL = open(os.devnull,", "test_set = {} test_set.update(d1) test_set.update(d2) test_set.update(d3) test_set.update(d4) print(len(test_set)) print(\"running tests...\")", "k,v in test_set.items(): r.get(k) r.wait(3, 0) end = time.time() runtime", "2 throughput = float(ops/runtime) latency = float(1/throughput) print(\"total run time:", "= (string_size, partition, d4)) t1.start() t2.start() t3.start() t4.start() t1.join() t1.join()", "size * 2 throughput = float(ops/runtime) latency = float(1/throughput) print(\"total", "redis import threading def generate_string(string_size, size, dict): ''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters '''", "import subprocess import os import redis import threading def generate_string(string_size,", "start ops = size * 2 throughput = float(ops/runtime) latency", "d2 = {} d3 = {} d4 = {} t1", "time.time() print(\"testing set\") for k,v in test_set.items(): r.set(k, v) r.wait(3,", "= redis.StrictRedis(host='localhost', port=port, db=0) start = time.time() print(\"testing set\") for", "line argument port = 7000 FNULL = open(os.devnull, 'w') string_size", "t4.start() t1.join() t1.join() t1.join() t1.join() test_set = {} test_set.update(d1) test_set.update(d2)", "runtime = end - start ops = size * 2", "avg. throughput: {throughput} ops/s \\n\\ avg. latency: {latency} s\".format( runtime=runtime,", "float(ops/runtime) latency = float(1/throughput) print(\"total run time: {runtime}s \\n\\ number", "26 key = bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big')) for i, b in enumerate(key):", "ord(b'a') len_lc = 26 key = bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big')) for i,", "test_set.update(d4) print(len(test_set)) print(\"running tests...\") r = redis.StrictRedis(host='localhost', port=port, db=0) start", "throughput: {throughput} ops/s \\n\\ avg. latency: {latency} s\".format( runtime=runtime, ops=ops,", "print(\"running tests...\") r = redis.StrictRedis(host='localhost', port=port, db=0) start = time.time()", "r.wait(3, 0) end = time.time() runtime = end - start", "threading def generate_string(string_size, size, dict): ''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters ''' for i", "print(\"generating test sets\") d1 = {} d2 = {} d3", "'big')) for i, b in enumerate(key): key[i] = min_lc +", "d4)) t1.start() t2.start() t3.start() t4.start() t1.join() t1.join() t1.join() t1.join() test_set", "min_lc = ord(b'a') len_lc = 26 key = bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big'))", "r.wait(3, 0) print(\"testing get\") for k,v in test_set.items(): r.get(k) r.wait(3,", "val = key dict[key] = val if __name__ == \"__main__\":", "= size * 2 throughput = float(ops/runtime) latency = float(1/throughput)", "size, dict): ''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters ''' for i in range(size): min_lc", "and 50% Get: {ops} \\n\\ avg. throughput: {throughput} ops/s \\n\\", "test_set.update(d2) test_set.update(d3) test_set.update(d4) print(len(test_set)) print(\"running tests...\") r = redis.StrictRedis(host='localhost', port=port,", "test_set.items(): r.set(k, v) r.wait(3, 0) print(\"testing get\") for k,v in", "i in range(size): min_lc = ord(b'a') len_lc = 26 key", "in test_set.items(): r.get(k) r.wait(3, 0) end = time.time() runtime =", "string_size = 100000 partition = int(size/4) print(\"generating test sets\") d1", "for k,v in test_set.items(): r.set(k, v) r.wait(3, 0) print(\"testing get\")", "time: {runtime}s \\n\\ number of total operations with 50% Set", "ops = size * 2 throughput = float(ops/runtime) latency =", "d1 = {} d2 = {} d3 = {} d4", "{} t1 = threading.Thread(target=generate_string, args = (string_size, partition, d1)) t2", "redis.StrictRedis(host='localhost', port=port, db=0) start = time.time() print(\"testing set\") for k,v", "set\") for k,v in test_set.items(): r.set(k, v) r.wait(3, 0) print(\"testing", "{} d3 = {} d4 = {} t1 = threading.Thread(target=generate_string,", "in test_set.items(): r.set(k, v) r.wait(3, 0) print(\"testing get\") for k,v", "d3)) t4 = threading.Thread(target=generate_string, args = (string_size, partition, d4)) t1.start()", "# convert 0..255 to 97..122 key = key.decode() val =", "= threading.Thread(target=generate_string, args = (string_size, partition, d2)) t3 = threading.Thread(target=generate_string,", "import os import redis import threading def generate_string(string_size, size, dict):", "(string_size, partition, d1)) t2 = threading.Thread(target=generate_string, args = (string_size, partition,", "100000 partition = int(size/4) print(\"generating test sets\") d1 = {}", "convert 0..255 to 97..122 key = key.decode() val = key", "= (string_size, partition, d3)) t4 = threading.Thread(target=generate_string, args = (string_size,", "* 2 throughput = float(ops/runtime) latency = float(1/throughput) print(\"total run", "Get: {ops} \\n\\ avg. throughput: {throughput} ops/s \\n\\ avg. latency:", "\\n\\ avg. throughput: {throughput} ops/s \\n\\ avg. latency: {latency} s\".format(", "''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters ''' for i in range(size): min_lc = ord(b'a')", "= {} d4 = {} t1 = threading.Thread(target=generate_string, args =", "partition, d3)) t4 = threading.Thread(target=generate_string, args = (string_size, partition, d4))", "dict): ''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters ''' for i in range(size): min_lc =", "b in enumerate(key): key[i] = min_lc + b % len_lc", "{ops} \\n\\ avg. throughput: {throughput} ops/s \\n\\ avg. latency: {latency}", "end = time.time() runtime = end - start ops =", "50% Set and 50% Get: {ops} \\n\\ avg. throughput: {throughput}", "{} d2 = {} d3 = {} d4 = {}", "total operations with 50% Set and 50% Get: {ops} \\n\\", "FNULL = open(os.devnull, 'w') string_size = 100000 partition = int(size/4)", "97..122 key = key.decode() val = key dict[key] = val", "args = (string_size, partition, d1)) t2 = threading.Thread(target=generate_string, args =", "= bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big')) for i, b in enumerate(key): key[i] =", "= 26 key = bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big')) for i, b in", "d3 = {} d4 = {} t1 = threading.Thread(target=generate_string, args", "args = (string_size, partition, d3)) t4 = threading.Thread(target=generate_string, args =", "port=port, db=0) start = time.time() print(\"testing set\") for k,v in", "t1.join() test_set = {} test_set.update(d1) test_set.update(d2) test_set.update(d3) test_set.update(d4) print(len(test_set)) print(\"running", "= time.time() runtime = end - start ops = size", "operations with 50% Set and 50% Get: {ops} \\n\\ avg.", "= 7000 FNULL = open(os.devnull, 'w') string_size = 100000 partition", "range(size): min_lc = ord(b'a') len_lc = 26 key = bytearray(random.getrandbits(8*string_size).to_bytes(string_size,", "val if __name__ == \"__main__\": size = 1000 # TODO:", "t1 = threading.Thread(target=generate_string, args = (string_size, partition, d1)) t2 =", "end - start ops = size * 2 throughput =", "= open(os.devnull, 'w') string_size = 100000 partition = int(size/4) print(\"generating", "= threading.Thread(target=generate_string, args = (string_size, partition, d3)) t4 = threading.Thread(target=generate_string,", "1000 # TODO: make is an command line argument port", "test_set.update(d3) test_set.update(d4) print(len(test_set)) print(\"running tests...\") r = redis.StrictRedis(host='localhost', port=port, db=0)", "print(\"testing set\") for k,v in test_set.items(): r.set(k, v) r.wait(3, 0)", "= {} test_set.update(d1) test_set.update(d2) test_set.update(d3) test_set.update(d4) print(len(test_set)) print(\"running tests...\") r", "= key dict[key] = val if __name__ == \"__main__\": size", "d4 = {} t1 = threading.Thread(target=generate_string, args = (string_size, partition,", "= 100000 partition = int(size/4) print(\"generating test sets\") d1 =", "= ord(b'a') len_lc = 26 key = bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big')) for", "len_lc = 26 key = bytearray(random.getrandbits(8*string_size).to_bytes(string_size, 'big')) for i, b", "test sets\") d1 = {} d2 = {} d3 =", "partition = int(size/4) print(\"generating test sets\") d1 = {} d2", "test_set.items(): r.get(k) r.wait(3, 0) end = time.time() runtime = end", "import threading def generate_string(string_size, size, dict): ''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters ''' for", "{} d4 = {} t1 = threading.Thread(target=generate_string, args = (string_size,", "7000 FNULL = open(os.devnull, 'w') string_size = 100000 partition =", "t1.start() t2.start() t3.start() t4.start() t1.join() t1.join() t1.join() t1.join() test_set =", "r.get(k) r.wait(3, 0) end = time.time() runtime = end -", "\\n\\ number of total operations with 50% Set and 50%", "dict[key] = val if __name__ == \"__main__\": size = 1000", "b % len_lc # convert 0..255 to 97..122 key =", "0..255 to 97..122 key = key.decode() val = key dict[key]", "t1.join() t1.join() t1.join() test_set = {} test_set.update(d1) test_set.update(d2) test_set.update(d3) test_set.update(d4)", "t4 = threading.Thread(target=generate_string, args = (string_size, partition, d4)) t1.start() t2.start()", "r.set(k, v) r.wait(3, 0) print(\"testing get\") for k,v in test_set.items():", "i, b in enumerate(key): key[i] = min_lc + b %", "'w') string_size = 100000 partition = int(size/4) print(\"generating test sets\")", "__name__ == \"__main__\": size = 1000 # TODO: make is", "0) end = time.time() runtime = end - start ops", "number of total operations with 50% Set and 50% Get:", "== \"__main__\": size = 1000 # TODO: make is an", "= min_lc + b % len_lc # convert 0..255 to", "{throughput} ops/s \\n\\ avg. latency: {latency} s\".format( runtime=runtime, ops=ops, throughput=throughput,", "in enumerate(key): key[i] = min_lc + b % len_lc #", "threading.Thread(target=generate_string, args = (string_size, partition, d2)) t3 = threading.Thread(target=generate_string, args", "time import subprocess import os import redis import threading def", "if __name__ == \"__main__\": size = 1000 # TODO: make", "size = 1000 # TODO: make is an command line", "partition, d1)) t2 = threading.Thread(target=generate_string, args = (string_size, partition, d2))", "key[i] = min_lc + b % len_lc # convert 0..255", "for i, b in enumerate(key): key[i] = min_lc + b", "subprocess import os import redis import threading def generate_string(string_size, size,", "= threading.Thread(target=generate_string, args = (string_size, partition, d1)) t2 = threading.Thread(target=generate_string,", "= {} d2 = {} d3 = {} d4 =", "= float(1/throughput) print(\"total run time: {runtime}s \\n\\ number of total", "https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters ''' for i in range(size): min_lc = ord(b'a') len_lc", "latency = float(1/throughput) print(\"total run time: {runtime}s \\n\\ number of", "key.decode() val = key dict[key] = val if __name__ ==", "= float(ops/runtime) latency = float(1/throughput) print(\"total run time: {runtime}s \\n\\", "50% Get: {ops} \\n\\ avg. throughput: {throughput} ops/s \\n\\ avg.", "make is an command line argument port = 7000 FNULL", "= int(size/4) print(\"generating test sets\") d1 = {} d2 =", "t3 = threading.Thread(target=generate_string, args = (string_size, partition, d3)) t4 =", "len_lc # convert 0..255 to 97..122 key = key.decode() val", "min_lc + b % len_lc # convert 0..255 to 97..122", "% len_lc # convert 0..255 to 97..122 key = key.decode()", "t2.start() t3.start() t4.start() t1.join() t1.join() t1.join() t1.join() test_set = {}", "t3.start() t4.start() t1.join() t1.join() t1.join() t1.join() test_set = {} test_set.update(d1)", "{runtime}s \\n\\ number of total operations with 50% Set and", "threading.Thread(target=generate_string, args = (string_size, partition, d1)) t2 = threading.Thread(target=generate_string, args", "args = (string_size, partition, d4)) t1.start() t2.start() t3.start() t4.start() t1.join()", "Set and 50% Get: {ops} \\n\\ avg. throughput: {throughput} ops/s", "import redis import threading def generate_string(string_size, size, dict): ''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters", "import random import string import time import subprocess import os", "= (string_size, partition, d1)) t2 = threading.Thread(target=generate_string, args = (string_size,", "k,v in test_set.items(): r.set(k, v) r.wait(3, 0) print(\"testing get\") for", "def generate_string(string_size, size, dict): ''' https://stackoverflow.com/questions/16308989/fastest-method-to-generate-big-random-string-with-lower-latin-letters ''' for i in", "t1.join() t1.join() t1.join() t1.join() test_set = {} test_set.update(d1) test_set.update(d2) test_set.update(d3)", "to 97..122 key = key.decode() val = key dict[key] =", "threading.Thread(target=generate_string, args = (string_size, partition, d3)) t4 = threading.Thread(target=generate_string, args", "key = key.decode() val = key dict[key] = val if", "- start ops = size * 2 throughput = float(ops/runtime)", "for k,v in test_set.items(): r.get(k) r.wait(3, 0) end = time.time()", "t2 = threading.Thread(target=generate_string, args = (string_size, partition, d2)) t3 =", "args = (string_size, partition, d2)) t3 = threading.Thread(target=generate_string, args =", "0) print(\"testing get\") for k,v in test_set.items(): r.get(k) r.wait(3, 0)", "throughput = float(ops/runtime) latency = float(1/throughput) print(\"total run time: {runtime}s", "command line argument port = 7000 FNULL = open(os.devnull, 'w')", "key dict[key] = val if __name__ == \"__main__\": size =", "print(\"total run time: {runtime}s \\n\\ number of total operations with", "is an command line argument port = 7000 FNULL =", "open(os.devnull, 'w') string_size = 100000 partition = int(size/4) print(\"generating test", "test_set.update(d1) test_set.update(d2) test_set.update(d3) test_set.update(d4) print(len(test_set)) print(\"running tests...\") r = redis.StrictRedis(host='localhost',", "with 50% Set and 50% Get: {ops} \\n\\ avg. throughput:", "ops/s \\n\\ avg. latency: {latency} s\".format( runtime=runtime, ops=ops, throughput=throughput, latency=latency", "\\n\\ avg. latency: {latency} s\".format( runtime=runtime, ops=ops, throughput=throughput, latency=latency ))", "string import time import subprocess import os import redis import", "= threading.Thread(target=generate_string, args = (string_size, partition, d4)) t1.start() t2.start() t3.start()", "= key.decode() val = key dict[key] = val if __name__", "import string import time import subprocess import os import redis", "= (string_size, partition, d2)) t3 = threading.Thread(target=generate_string, args = (string_size,", "import time import subprocess import os import redis import threading", "time.time() runtime = end - start ops = size *", "= end - start ops = size * 2 throughput", "\"__main__\": size = 1000 # TODO: make is an command", "get\") for k,v in test_set.items(): r.get(k) r.wait(3, 0) end =", "= val if __name__ == \"__main__\": size = 1000 #", "float(1/throughput) print(\"total run time: {runtime}s \\n\\ number of total operations", "d1)) t2 = threading.Thread(target=generate_string, args = (string_size, partition, d2)) t3", "in range(size): min_lc = ord(b'a') len_lc = 26 key =", "(string_size, partition, d3)) t4 = threading.Thread(target=generate_string, args = (string_size, partition,", "(string_size, partition, d4)) t1.start() t2.start() t3.start() t4.start() t1.join() t1.join() t1.join()" ]
[ "empty new line in case the lists have no intersection.", "4 8,9 \"\"\" ###### IO Boilerplate ###### import sys if", "import sys if len(sys.argv) < 2: input_file_name = \"15-setintersection-in.txt\" else:", "sorted list of numbers (ascending order). The lists themselves are", "have no intersection. E.g. 4 8,9 \"\"\" ###### IO Boilerplate", "line in input_lines: string_sets = line.split(';') sets = [set(string_set.split(',')) for", "out the ascending order sorted intersection of the two lists,", "delimited. Print out the intersection of these two sets. Input", "of these two sets. Input Sample: File containing two lists", "new line in case the lists have no intersection. E.g.", "intersection = sorted(sets[0].intersection(sets[1])) print \",\".join(intersection) if __name__ == '__main__': main()", "with open(input_file_name) as input_file: input_lines = map(lambda x: x.strip(), filter(lambda", "x.strip(), filter(lambda x: x != '', input_file.readlines())) ###### /IO Boilerplate", "sorted integers, comma delimited, one per line. E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47", "line.split(';') sets = [set(string_set.split(',')) for string_set in string_sets] intersection =", "as input_file: input_lines = map(lambda x: x.strip(), filter(lambda x: x", "per line. E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12 Output Sample: Print out", "integers, comma delimited, one per line. E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12", "intersection of the two lists, one per line. Print empty", "comma delimited, one per line. E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12 Output", "Description: You are given two sorted list of numbers (ascending", "7,8,9;8,9,10,11,12 Output Sample: Print out the ascending order sorted intersection", "len(sys.argv) < 2: input_file_name = \"15-setintersection-in.txt\" else: input_file_name = sys.argv[1]", "comma delimited and the two lists are semicolon delimited. Print", "containing two lists of ascending order sorted integers, comma delimited,", "https://www.codeeval.com/browse/30/ Set Intersection Challenge Description: You are given two sorted", "Boilerplate ###### import sys if len(sys.argv) < 2: input_file_name =", "###### IO Boilerplate ###### import sys if len(sys.argv) < 2:", "sets. Input Sample: File containing two lists of ascending order", "= [set(string_set.split(',')) for string_set in string_sets] intersection = sorted(sets[0].intersection(sets[1])) print", "order). The lists themselves are comma delimited and the two", "delimited, one per line. E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12 Output Sample:", "input_lines = map(lambda x: x.strip(), filter(lambda x: x != '',", "these two sets. Input Sample: File containing two lists of", "= sys.argv[1] with open(input_file_name) as input_file: input_lines = map(lambda x:", "in string_sets] intersection = sorted(sets[0].intersection(sets[1])) print \",\".join(intersection) if __name__ ==", "= \"15-setintersection-in.txt\" else: input_file_name = sys.argv[1] with open(input_file_name) as input_file:", "!= '', input_file.readlines())) ###### /IO Boilerplate ###### def main(): for", "Sample: Print out the ascending order sorted intersection of the", "line. E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12 Output Sample: Print out the", "and the two lists are semicolon delimited. Print out the", "8,9 \"\"\" ###### IO Boilerplate ###### import sys if len(sys.argv)", "ascending order sorted intersection of the two lists, one per", "semicolon delimited. Print out the intersection of these two sets.", "20,21,22;45,46,47 7,8,9;8,9,10,11,12 Output Sample: Print out the ascending order sorted", "sorted intersection of the two lists, one per line. Print", "if len(sys.argv) < 2: input_file_name = \"15-setintersection-in.txt\" else: input_file_name =", "The lists themselves are comma delimited and the two lists", "two sorted list of numbers (ascending order). The lists themselves", "\"15-setintersection-in.txt\" else: input_file_name = sys.argv[1] with open(input_file_name) as input_file: input_lines", "of numbers (ascending order). The lists themselves are comma delimited", "intersection of these two sets. Input Sample: File containing two", "delimited and the two lists are semicolon delimited. Print out", "(ascending order). The lists themselves are comma delimited and the", "1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12 Output Sample: Print out the ascending order", "= map(lambda x: x.strip(), filter(lambda x: x != '', input_file.readlines()))", "of the two lists, one per line. Print empty new", "are comma delimited and the two lists are semicolon delimited.", "<reponame>Widdershin/CodeEval \"\"\" https://www.codeeval.com/browse/30/ Set Intersection Challenge Description: You are given", "Boilerplate ###### def main(): for line in input_lines: string_sets =", "for string_set in string_sets] intersection = sorted(sets[0].intersection(sets[1])) print \",\".join(intersection) if", "are semicolon delimited. Print out the intersection of these two", "lists have no intersection. E.g. 4 8,9 \"\"\" ###### IO", "[set(string_set.split(',')) for string_set in string_sets] intersection = sorted(sets[0].intersection(sets[1])) print \",\".join(intersection)", "the intersection of these two sets. Input Sample: File containing", "list of numbers (ascending order). The lists themselves are comma", "string_sets] intersection = sorted(sets[0].intersection(sets[1])) print \",\".join(intersection) if __name__ == '__main__':", "lists are semicolon delimited. Print out the intersection of these", "E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12 Output Sample: Print out the ascending", "def main(): for line in input_lines: string_sets = line.split(';') sets", "IO Boilerplate ###### import sys if len(sys.argv) < 2: input_file_name", "You are given two sorted list of numbers (ascending order).", "Challenge Description: You are given two sorted list of numbers", "File containing two lists of ascending order sorted integers, comma", "of ascending order sorted integers, comma delimited, one per line.", "themselves are comma delimited and the two lists are semicolon", "ascending order sorted integers, comma delimited, one per line. E.g.", "intersection. E.g. 4 8,9 \"\"\" ###### IO Boilerplate ###### import", "the two lists are semicolon delimited. Print out the intersection", "Input Sample: File containing two lists of ascending order sorted", "input_lines: string_sets = line.split(';') sets = [set(string_set.split(',')) for string_set in", "x: x != '', input_file.readlines())) ###### /IO Boilerplate ###### def", "two lists, one per line. Print empty new line in", "the ascending order sorted intersection of the two lists, one", "/IO Boilerplate ###### def main(): for line in input_lines: string_sets", "Set Intersection Challenge Description: You are given two sorted list", "two lists are semicolon delimited. Print out the intersection of", "two sets. Input Sample: File containing two lists of ascending", "one per line. E.g. 1,2,3,4;4,5,6 20,21,22;45,46,47 7,8,9;8,9,10,11,12 Output Sample: Print", "the lists have no intersection. E.g. 4 8,9 \"\"\" ######", "x != '', input_file.readlines())) ###### /IO Boilerplate ###### def main():", "input_file_name = sys.argv[1] with open(input_file_name) as input_file: input_lines = map(lambda", "lists of ascending order sorted integers, comma delimited, one per", "= line.split(';') sets = [set(string_set.split(',')) for string_set in string_sets] intersection", "the two lists, one per line. Print empty new line", "\"\"\" ###### IO Boilerplate ###### import sys if len(sys.argv) <", "Sample: File containing two lists of ascending order sorted integers,", "sys if len(sys.argv) < 2: input_file_name = \"15-setintersection-in.txt\" else: input_file_name", "for line in input_lines: string_sets = line.split(';') sets = [set(string_set.split(','))", "are given two sorted list of numbers (ascending order). The", "in case the lists have no intersection. E.g. 4 8,9", "map(lambda x: x.strip(), filter(lambda x: x != '', input_file.readlines())) ######", "in input_lines: string_sets = line.split(';') sets = [set(string_set.split(',')) for string_set", "open(input_file_name) as input_file: input_lines = map(lambda x: x.strip(), filter(lambda x:", "no intersection. E.g. 4 8,9 \"\"\" ###### IO Boilerplate ######", "Print out the ascending order sorted intersection of the two", "< 2: input_file_name = \"15-setintersection-in.txt\" else: input_file_name = sys.argv[1] with", "per line. Print empty new line in case the lists", "x: x.strip(), filter(lambda x: x != '', input_file.readlines())) ###### /IO", "line. Print empty new line in case the lists have", "else: input_file_name = sys.argv[1] with open(input_file_name) as input_file: input_lines =", "line in case the lists have no intersection. E.g. 4", "given two sorted list of numbers (ascending order). The lists", "input_file: input_lines = map(lambda x: x.strip(), filter(lambda x: x !=", "numbers (ascending order). The lists themselves are comma delimited and", "case the lists have no intersection. E.g. 4 8,9 \"\"\"", "'', input_file.readlines())) ###### /IO Boilerplate ###### def main(): for line", "Print out the intersection of these two sets. Input Sample:", "filter(lambda x: x != '', input_file.readlines())) ###### /IO Boilerplate ######", "out the intersection of these two sets. Input Sample: File", "Print empty new line in case the lists have no", "E.g. 4 8,9 \"\"\" ###### IO Boilerplate ###### import sys", "###### def main(): for line in input_lines: string_sets = line.split(';')", "string_sets = line.split(';') sets = [set(string_set.split(',')) for string_set in string_sets]", "string_set in string_sets] intersection = sorted(sets[0].intersection(sets[1])) print \",\".join(intersection) if __name__", "2: input_file_name = \"15-setintersection-in.txt\" else: input_file_name = sys.argv[1] with open(input_file_name)", "input_file_name = \"15-setintersection-in.txt\" else: input_file_name = sys.argv[1] with open(input_file_name) as", "lists, one per line. Print empty new line in case", "main(): for line in input_lines: string_sets = line.split(';') sets =", "one per line. Print empty new line in case the", "###### /IO Boilerplate ###### def main(): for line in input_lines:", "sets = [set(string_set.split(',')) for string_set in string_sets] intersection = sorted(sets[0].intersection(sets[1]))", "order sorted integers, comma delimited, one per line. E.g. 1,2,3,4;4,5,6", "two lists of ascending order sorted integers, comma delimited, one", "sys.argv[1] with open(input_file_name) as input_file: input_lines = map(lambda x: x.strip(),", "\"\"\" https://www.codeeval.com/browse/30/ Set Intersection Challenge Description: You are given two", "input_file.readlines())) ###### /IO Boilerplate ###### def main(): for line in", "order sorted intersection of the two lists, one per line.", "###### import sys if len(sys.argv) < 2: input_file_name = \"15-setintersection-in.txt\"", "Intersection Challenge Description: You are given two sorted list of", "Output Sample: Print out the ascending order sorted intersection of", "lists themselves are comma delimited and the two lists are" ]
[ "version_control data_table = FateSession.get_instance().table(name=name, namespace=namespace, partition=partition, persistent=persistent, in_place_computing=False, create_if_missing=create_if_missing, error_if_exist=error_if_exist)", "= {} if work_mode == WorkMode.STANDALONE: options['eggroll.session.deploy.mode'] = \"standalone\" elif", "arch.api.utils import version_control data_table = FateSession.get_instance().table(name=name, namespace=namespace, partition=partition, persistent=persistent, in_place_computing=False,", "else: return None @staticmethod def get_data_table_metas(data_table_name, data_table_namespace): \"\"\" get data", "json_dumps(v)) @staticmethod def get_data_table_meta(key, data_table_name, data_table_namespace): \"\"\" get data table", "2.0 (the \"License\"); # you may not use this file", "session @six.add_metaclass(abc.ABCMeta) class FateSession(object): _instance: 'FateSession' = None __lock =", "namespace, persistent, chunk_size, in_place_computing, create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod", "Iterable import six from arch.api import WorkMode, Backend from arch.api.table.table", "data into data table :param version_log: :param in_version: :param kv_data:", "if work_mode == WorkMode.STANDALONE: options['eggroll.session.deploy.mode'] = \"standalone\" elif work_mode ==", "if backend.is_eggroll(): from arch.api.table.eggroll import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id)", "class FateSession(object): _instance: 'FateSession' = None __lock = threading.Lock() @staticmethod", "= eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_eggroll2():", "Copyright 2019 The FATE Authors. All Rights Reserved. # #", "PyPep8Naming @abc.abstractmethod def generateUniqueId(self): pass @abc.abstractmethod def get_session_id(self): pass @abc.abstractmethod", "in_place_computing=False) for k, v in kv.items(): data_meta_table.put(k, json_dumps(v)) @staticmethod def", "arch.api.table.table import Table from eggroll.core.constants import StoreTypes def build_session(job_id=None, work_mode:", "elif work_mode == WorkMode.CLUSTER: options['eggroll.session.deploy.mode'] = \"cluster\" er_session = session_init(session_id=job_id,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "save data at %s.\" % datetime.datetime.now() if not version_log else", "under the License. # import abc import datetime import threading", "get_data_table(name, namespace): \"\"\" return data table instance by table name", "def save_data(kv_data: Iterable, name, namespace, partition=1, persistent: bool = True,", "data_table_name, data_table_namespace): \"\"\" get data table meta information :param key:", "\"\"\" save data table meta information :param kv: v should", "threading from typing import Iterable import six from arch.api import", "def table(self, name, namespace, partition, persistent, in_place_computing, create_if_missing, error_if_exist) ->", "import json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, persistent=True,", "persistent=True, error_if_exist=False, in_place_computing=False, partition=1) @staticmethod def save_data_table_meta(kv, data_table_name, data_table_namespace): \"\"\"", "not supported\") return session @six.add_metaclass(abc.ABCMeta) class FateSession(object): _instance: 'FateSession' =", "work_mode == WorkMode.STANDALONE: options['eggroll.session.deploy.mode'] = \"standalone\" elif work_mode == WorkMode.CLUSTER:", "True, :param create_if_missing: :param error_if_exist: :return: data table instance \"\"\"", "data_meta_table: value_bytes = data_meta_table.get(key, use_serialize=False) if value_bytes: return json_loads(value_bytes) else:", "should be serialized by JSON :param data_table_name: table name of", "in_place_computing, create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod def cleanup(self, name,", "WorkMode.STANDALONE, backend: Backend = Backend.EGGROLL2, persistent_engine: StoreTypes = StoreTypes.ROLLPAIR_LMDB): from", "@staticmethod def save_data_table_meta(kv, data_table_name, data_table_namespace): \"\"\" save data table meta", "instance by table name and table name space :param name:", "= threading.Lock() @staticmethod def set_instance(instance): if not FateSession._instance: with FateSession.__lock:", "Backend from arch.api.table.table import Table from eggroll.core.constants import StoreTypes def", "pass @abc.abstractmethod def stop(self): pass @staticmethod def get_data_table(name, namespace): \"\"\"", "build_session(job_id=None, work_mode: WorkMode = WorkMode.STANDALONE, backend: Backend = Backend.EGGROLL2, persistent_engine:", "def parallelize(self, data: Iterable, include_key, name, partition, namespace, persistent, chunk_size,", "table :return: \"\"\" from arch.api.utils.core import json_dumps data_meta_table = FateSession.get_instance().table(name=\"%s.meta\"", "eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_eggroll2(): from", "use this file except in compliance with the License. #", "Table: pass @abc.abstractmethod def cleanup(self, name, namespace, persistent): pass #", "noinspection PyPep8Naming @abc.abstractmethod def generateUniqueId(self): pass @abc.abstractmethod def get_session_id(self): pass", "arch.api.table.pyspark import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session,", "in_version: :param kv_data: :param name: table name of data table", "data table instance by table name and table name space", "from typing import Iterable import six from arch.api import WorkMode,", "bool = True, create_if_missing=True, error_if_exist=False, in_version: bool = False, version_log=None):", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "persistent=persistent, in_place_computing=False, create_if_missing=create_if_missing, error_if_exist=error_if_exist) data_table.put_all(kv_data) if in_version: version_log = \"[AUTO]", "options = {} if work_mode == WorkMode.STANDALONE: options['eggroll.session.deploy.mode'] = \"standalone\"", "if not version_log else version_log version_control.save_version(name=name, namespace=namespace, version_log=version_log) return data_table", "@abc.abstractmethod def table(self, name, namespace, partition, persistent, in_place_computing, create_if_missing, error_if_exist)", "License. # You may obtain a copy of the License", "eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_spark(): from", "= session_impl.FateSessionImpl(er_session, work_mode, persistent_engine) else: raise ValueError(f\"work_mode: {work_mode} not supported\")", "data table :param namespace: table namespace of data table :param", "name space :param name: table name of data table :param", "namespace=data_table_namespace, create_if_missing=True, error_if_exist=False, in_place_computing=False, persistent=True, partition=1) if data_meta_table: value_bytes =", "Iterable, name, namespace, partition=1, persistent: bool = True, create_if_missing=True, error_if_exist=False,", "under the License is distributed on an \"AS IS\" BASIS,", "@staticmethod def clean_table(namespace, regex_string='*'): try: FateSession.get_instance().cleanup(name=regex_string, namespace=namespace, persistent=False) except Exception", "pass @abc.abstractmethod def cleanup(self, name, namespace, persistent): pass # noinspection", "License for the specific language governing permissions and # limitations", "= instance @staticmethod def get_instance(): return FateSession._instance @abc.abstractmethod def get_persistent_engine(self):", "return FateSession._instance @abc.abstractmethod def get_persistent_engine(self): pass @abc.abstractmethod def table(self, name,", "persistent): pass # noinspection PyPep8Naming @abc.abstractmethod def generateUniqueId(self): pass @abc.abstractmethod", "eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif", "Reserved. # # Licensed under the Apache License, Version 2.0", "metas[k] = json_loads(v) return metas else: return None @staticmethod def", "except Exception as e: print(e) @staticmethod def save_data(kv_data: Iterable, name,", "data table :param namespace: table name space of data table", "table name of data table :param namespace: table name space", "create_if_missing=False, persistent=True, error_if_exist=False, in_place_computing=False, partition=1) @staticmethod def save_data_table_meta(kv, data_table_name, data_table_namespace):", "ValueError(f\"work_mode: {work_mode} not supported\") return session @six.add_metaclass(abc.ABCMeta) class FateSession(object): _instance:", "error_if_exist=False, persistent=True, in_place_computing=False) for k, v in kv.items(): data_meta_table.put(k, json_dumps(v))", "The FATE Authors. All Rights Reserved. # # Licensed under", "set_instance(instance): if not FateSession._instance: with FateSession.__lock: if not FateSession._instance: FateSession._instance", "return session @six.add_metaclass(abc.ABCMeta) class FateSession(object): _instance: 'FateSession' = None __lock", "from arch.api.utils import version_control data_table = FateSession.get_instance().table(name=name, namespace=namespace, partition=partition, persistent=persistent,", "\"\"\" return data table instance by table name and table", "meta information :param data_table_name: table name of this data table", "data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, persistent=True, in_place_computing=False, create_if_missing=True,", "in compliance with the License. # You may obtain a", "data table :param data_table_namespace: table name of this data table", "elif backend.is_spark(): from arch.api.table.pyspark import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id)", "software # distributed under the License is distributed on an", "= session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_spark(): from arch.api.table.pyspark import session_impl", "data_table_name, namespace=data_table_namespace, partition=1, create_if_missing=True, error_if_exist=False, persistent=True, in_place_computing=False) for k, v", "pass # noinspection PyPep8Naming @abc.abstractmethod def generateUniqueId(self): pass @abc.abstractmethod def", "in_version: bool = False, version_log=None): \"\"\" save data into data", "by JSON :param data_table_name: table name of this data table", ":param kv_data: :param name: table name of data table :param", "@abc.abstractmethod def generateUniqueId(self): pass @abc.abstractmethod def get_session_id(self): pass @abc.abstractmethod def", "table instance \"\"\" return FateSession.get_instance().table(name=name, namespace=namespace, create_if_missing=False, persistent=True, error_if_exist=False, in_place_computing=False,", "Table from eggroll.core.constants import StoreTypes def build_session(job_id=None, work_mode: WorkMode =", "<gh_stars>1-10 # # Copyright 2019 The FATE Authors. All Rights", "save data table meta information :param kv: v should be", "at %s.\" % datetime.datetime.now() if not version_log else version_log version_control.save_version(name=name,", ":param create_if_missing: :param error_if_exist: :return: data table instance \"\"\" from", "= True, :param create_if_missing: :param error_if_exist: :return: data table instance", "StoreTypes def build_session(job_id=None, work_mode: WorkMode = WorkMode.STANDALONE, backend: Backend =", "= False, version_log=None): \"\"\" save data into data table :param", "from eggroll.core.constants import StoreTypes def build_session(job_id=None, work_mode: WorkMode = WorkMode.STANDALONE,", "partition, persistent, in_place_computing, create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod def", "pass @staticmethod def get_data_table(name, namespace): \"\"\" return data table instance", "data table meta information :param kv: v should be serialized", "None @staticmethod def get_data_table_metas(data_table_name, data_table_namespace): \"\"\" get data table meta", "create_if_missing=True, error_if_exist=False, in_version: bool = False, version_log=None): \"\"\" save data", "name, namespace, persistent): pass # noinspection PyPep8Naming @abc.abstractmethod def generateUniqueId(self):", "number of partition :param persistent: bool = True, :param create_if_missing:", "FateSession._instance = instance @staticmethod def get_instance(): return FateSession._instance @abc.abstractmethod def", "table :param namespace: table name space of data table :return:", "metas = dict() for k, v in data_meta_table.collect(use_serialize=False): metas[k] =", "information :param kv: v should be serialized by JSON :param", "json_loads(value_bytes) else: return None else: return None @staticmethod def get_data_table_metas(data_table_name,", "persistent_engine) elif backend.is_spark(): from arch.api.table.pyspark import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode,", "import eggroll_util if backend.is_eggroll(): from arch.api.table.eggroll import session_impl eggroll_session =", "= json_loads(v) return metas else: return None @staticmethod def clean_table(namespace,", "= session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_eggroll2(): from eggroll.core.session import session_init", "get data table meta information :param key: :param data_table_name: table", "v should be serialized by JSON :param data_table_name: table name", "be serialized by JSON :param data_table_name: table name of this", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "table meta information :param kv: v should be serialized by", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, persistent=True, in_place_computing=False, create_if_missing=True, error_if_exist=False) if", "@abc.abstractmethod def cleanup(self, name, namespace, persistent): pass # noinspection PyPep8Naming", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "# See the License for the specific language governing permissions", "import six from arch.api import WorkMode, Backend from arch.api.table.table import", "language governing permissions and # limitations under the License. #", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "return None else: return None @staticmethod def get_data_table_metas(data_table_name, data_table_namespace): \"\"\"", "kv_data: :param name: table name of data table :param namespace:", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "error_if_exist=error_if_exist) data_table.put_all(kv_data) if in_version: version_log = \"[AUTO] save data at", "of this data table :return: \"\"\" from arch.api.utils.core import json_dumps", "with the License. # You may obtain a copy of", "% data_table_name, namespace=data_table_namespace, create_if_missing=True, error_if_exist=False, in_place_computing=False, persistent=True, partition=1) if data_meta_table:", "'FateSession' = None __lock = threading.Lock() @staticmethod def set_instance(instance): if", "FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, create_if_missing=True, error_if_exist=False, in_place_computing=False, persistent=True, partition=1) if", "meta information :param kv: v should be serialized by JSON", "in_place_computing=False, partition=1) @staticmethod def save_data_table_meta(kv, data_table_name, data_table_namespace): \"\"\" save data", ":return: \"\"\" from arch.api.utils.core import json_dumps data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" %", "for k, v in kv.items(): data_meta_table.put(k, json_dumps(v)) @staticmethod def get_data_table_meta(key,", "get_session_id(self): pass @abc.abstractmethod def stop(self): pass @staticmethod def get_data_table(name, namespace):", "in data_meta_table.collect(use_serialize=False): metas[k] = json_loads(v) return metas else: return None", "= WorkMode.STANDALONE, backend: Backend = Backend.EGGROLL2, persistent_engine: StoreTypes = StoreTypes.ROLLPAIR_LMDB):", "@staticmethod def set_instance(instance): if not FateSession._instance: with FateSession.__lock: if not", "partition=1, persistent=True, in_place_computing=False, create_if_missing=True, error_if_exist=False) if data_meta_table: metas = dict()", "data table instance \"\"\" from arch.api.utils import version_control data_table =", "compliance with the License. # You may obtain a copy", "table namespace of data table :param partition: number of partition", "All Rights Reserved. # # Licensed under the Apache License,", "agreed to in writing, software # distributed under the License", "FateSession.get_instance().table(name=name, namespace=namespace, create_if_missing=False, persistent=True, error_if_exist=False, in_place_computing=False, partition=1) @staticmethod def save_data_table_meta(kv,", "distributed under the License is distributed on an \"AS IS\"", "import Table from eggroll.core.constants import StoreTypes def build_session(job_id=None, work_mode: WorkMode", "def get_instance(): return FateSession._instance @abc.abstractmethod def get_persistent_engine(self): pass @abc.abstractmethod def", "data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, create_if_missing=True, error_if_exist=False, persistent=True,", "arch.api.table.eggroll import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session,", "k, v in kv.items(): data_meta_table.put(k, json_dumps(v)) @staticmethod def get_data_table_meta(key, data_table_name,", "try: FateSession.get_instance().cleanup(name=regex_string, namespace=namespace, persistent=False) except Exception as e: print(e) @staticmethod", "== WorkMode.STANDALONE: options['eggroll.session.deploy.mode'] = \"standalone\" elif work_mode == WorkMode.CLUSTER: options['eggroll.session.deploy.mode']", "persistent_engine) elif backend.is_eggroll2(): from eggroll.core.session import session_init from arch.api.table.eggroll2 import", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "error_if_exist=False, in_place_computing=False, partition=1) @staticmethod def save_data_table_meta(kv, data_table_name, data_table_namespace): \"\"\" save", "data table :param partition: number of partition :param persistent: bool", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "@six.add_metaclass(abc.ABCMeta) class FateSession(object): _instance: 'FateSession' = None __lock = threading.Lock()", "\"\"\" get data table meta information :param data_table_name: table name", "FateSession.get_instance().cleanup(name=regex_string, namespace=namespace, persistent=False) except Exception as e: print(e) @staticmethod def", "writing, software # distributed under the License is distributed on", "not FateSession._instance: with FateSession.__lock: if not FateSession._instance: FateSession._instance = instance", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "datetime.datetime.now() if not version_log else version_log version_control.save_version(name=name, namespace=namespace, version_log=version_log) return", "from arch.api.utils.core import json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace,", "= \"[AUTO] save data at %s.\" % datetime.datetime.now() if not", "arch.api.table import eggroll_util if backend.is_eggroll(): from arch.api.table.eggroll import session_impl eggroll_session", "permissions and # limitations under the License. # import abc", "@staticmethod def get_data_table_meta(key, data_table_name, data_table_namespace): \"\"\" get data table meta", "namespace: table name space of data table :return: data table", "else: raise ValueError(f\"work_mode: {work_mode} not supported\") return session @six.add_metaclass(abc.ABCMeta) class", "CONDITIONS OF ANY KIND, either express or implied. # See", "def stop(self): pass @staticmethod def get_data_table(name, namespace): \"\"\" return data", "er_session = session_init(session_id=job_id, options=options) session = session_impl.FateSessionImpl(er_session, work_mode, persistent_engine) else:", "get data table meta information :param data_table_name: table name of", "threading.Lock() @staticmethod def set_instance(instance): if not FateSession._instance: with FateSession.__lock: if", "with FateSession.__lock: if not FateSession._instance: FateSession._instance = instance @staticmethod def", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "data_table_name: table name of this data table :param data_table_namespace: table", "= eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_spark():", "import session_init from arch.api.table.eggroll2 import session_impl options = {} if", "as e: print(e) @staticmethod def save_data(kv_data: Iterable, name, namespace, partition=1,", "work_mode, persistent_engine) elif backend.is_eggroll2(): from eggroll.core.session import session_init from arch.api.table.eggroll2", "by table name and table name space :param name: table", "cleanup(self, name, namespace, persistent): pass # noinspection PyPep8Naming @abc.abstractmethod def", ":param persistent: bool = True, :param create_if_missing: :param error_if_exist: :return:", "version_log=None): \"\"\" save data into data table :param version_log: :param", "if data_meta_table: value_bytes = data_meta_table.get(key, use_serialize=False) if value_bytes: return json_loads(value_bytes)", "data_table_namespace): \"\"\" get data table meta information :param key: :param", "Table: pass @abc.abstractmethod def parallelize(self, data: Iterable, include_key, name, partition,", "and # limitations under the License. # import abc import", "else: return None @staticmethod def clean_table(namespace, regex_string='*'): try: FateSession.get_instance().cleanup(name=regex_string, namespace=namespace,", "JSON :param data_table_name: table name of this data table :param", ":return: \"\"\" from arch.api.utils.core import json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" %", "= StoreTypes.ROLLPAIR_LMDB): from arch.api.table import eggroll_util if backend.is_eggroll(): from arch.api.table.eggroll", "return json_loads(value_bytes) else: return None else: return None @staticmethod def", "regex_string='*'): try: FateSession.get_instance().cleanup(name=regex_string, namespace=namespace, persistent=False) except Exception as e: print(e)", "def get_session_id(self): pass @abc.abstractmethod def stop(self): pass @staticmethod def get_data_table(name,", "from eggroll.core.session import session_init from arch.api.table.eggroll2 import session_impl options =", "= session_init(session_id=job_id, options=options) session = session_impl.FateSessionImpl(er_session, work_mode, persistent_engine) else: raise", "raise ValueError(f\"work_mode: {work_mode} not supported\") return session @six.add_metaclass(abc.ABCMeta) class FateSession(object):", "OR CONDITIONS OF ANY KIND, either express or implied. #", "elif backend.is_eggroll2(): from eggroll.core.session import session_init from arch.api.table.eggroll2 import session_impl", "partition=1, create_if_missing=True, error_if_exist=False, persistent=True, in_place_computing=False) for k, v in kv.items():", "persistent=False) except Exception as e: print(e) @staticmethod def save_data(kv_data: Iterable,", "if not FateSession._instance: with FateSession.__lock: if not FateSession._instance: FateSession._instance =", "the License is distributed on an \"AS IS\" BASIS, #", "job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_eggroll2(): from eggroll.core.session", "abc import datetime import threading from typing import Iterable import", "eggroll.core.constants import StoreTypes def build_session(job_id=None, work_mode: WorkMode = WorkMode.STANDALONE, backend:", "chunk_size, in_place_computing, create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod def cleanup(self,", "data_table_namespace): \"\"\" save data table meta information :param kv: v", "__lock = threading.Lock() @staticmethod def set_instance(instance): if not FateSession._instance: with", "import StoreTypes def build_session(job_id=None, work_mode: WorkMode = WorkMode.STANDALONE, backend: Backend", "data at %s.\" % datetime.datetime.now() if not version_log else version_log", "= FateSession.get_instance().table(name=name, namespace=namespace, partition=partition, persistent=persistent, in_place_computing=False, create_if_missing=create_if_missing, error_if_exist=error_if_exist) data_table.put_all(kv_data) if", "data table :return: \"\"\" from arch.api.utils.core import json_dumps data_meta_table =", "k, v in data_meta_table.collect(use_serialize=False): metas[k] = json_loads(v) return metas else:", "get_data_table_metas(data_table_name, data_table_namespace): \"\"\" get data table meta information :param data_table_name:", "table name of data table :param namespace: table namespace of", "this data table :return: \"\"\" from arch.api.utils.core import json_dumps data_meta_table", "generateUniqueId(self): pass @abc.abstractmethod def get_session_id(self): pass @abc.abstractmethod def stop(self): pass", "law or agreed to in writing, software # distributed under", "data_table_name, data_table_namespace): \"\"\" save data table meta information :param kv:", "table name of this data table :param data_table_namespace: table name", "governing permissions and # limitations under the License. # import", "= FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, persistent=True, in_place_computing=False, create_if_missing=True, error_if_exist=False)", "persistent=True, in_place_computing=False, create_if_missing=True, error_if_exist=False) if data_meta_table: metas = dict() for", "def set_instance(instance): if not FateSession._instance: with FateSession.__lock: if not FateSession._instance:", "table instance by table name and table name space :param", "e: print(e) @staticmethod def save_data(kv_data: Iterable, name, namespace, partition=1, persistent:", "data_table = FateSession.get_instance().table(name=name, namespace=namespace, partition=partition, persistent=persistent, in_place_computing=False, create_if_missing=create_if_missing, error_if_exist=error_if_exist) data_table.put_all(kv_data)", "instance @staticmethod def get_instance(): return FateSession._instance @abc.abstractmethod def get_persistent_engine(self): pass", "-> Table: pass @abc.abstractmethod def parallelize(self, data: Iterable, include_key, name,", "partition=1, persistent: bool = True, create_if_missing=True, error_if_exist=False, in_version: bool =", "in kv.items(): data_meta_table.put(k, json_dumps(v)) @staticmethod def get_data_table_meta(key, data_table_name, data_table_namespace): \"\"\"", "create_if_missing: :param error_if_exist: :return: data table instance \"\"\" from arch.api.utils", "partition=partition, persistent=persistent, in_place_computing=False, create_if_missing=create_if_missing, error_if_exist=error_if_exist) data_table.put_all(kv_data) if in_version: version_log =", "kv.items(): data_meta_table.put(k, json_dumps(v)) @staticmethod def get_data_table_meta(key, data_table_name, data_table_namespace): \"\"\" get", "persistent, chunk_size, in_place_computing, create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod def", "data_meta_table: metas = dict() for k, v in data_meta_table.collect(use_serialize=False): metas[k]", "def save_data_table_meta(kv, data_table_name, data_table_namespace): \"\"\" save data table meta information", "data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, create_if_missing=True, error_if_exist=False, in_place_computing=False, persistent=True,", "may obtain a copy of the License at # #", "def get_data_table(name, namespace): \"\"\" return data table instance by table", "partition :param persistent: bool = True, :param create_if_missing: :param error_if_exist:", "FateSession.__lock: if not FateSession._instance: FateSession._instance = instance @staticmethod def get_instance():", "bool = False, version_log=None): \"\"\" save data into data table", "options=options) session = session_impl.FateSessionImpl(er_session, work_mode, persistent_engine) else: raise ValueError(f\"work_mode: {work_mode}", "create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod def cleanup(self, name, namespace,", "create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod def parallelize(self, data: Iterable,", "for k, v in data_meta_table.collect(use_serialize=False): metas[k] = json_loads(v) return metas", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Backend = Backend.EGGROLL2, persistent_engine: StoreTypes = StoreTypes.ROLLPAIR_LMDB): from arch.api.table import", "json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, create_if_missing=True, error_if_exist=False, in_place_computing=False,", ":param data_table_name: table name of this data table :param data_table_namespace:", "None else: return None @staticmethod def get_data_table_metas(data_table_name, data_table_namespace): \"\"\" get", "work_mode: WorkMode = WorkMode.STANDALONE, backend: Backend = Backend.EGGROLL2, persistent_engine: StoreTypes", "table name and table name space :param name: table name", "may not use this file except in compliance with the", "save_data_table_meta(kv, data_table_name, data_table_namespace): \"\"\" save data table meta information :param", "import datetime import threading from typing import Iterable import six", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "in_place_computing=False, create_if_missing=create_if_missing, error_if_exist=error_if_exist) data_table.put_all(kv_data) if in_version: version_log = \"[AUTO] save", "= None __lock = threading.Lock() @staticmethod def set_instance(instance): if not", "this file except in compliance with the License. # You", "error_if_exist=False, in_place_computing=False, persistent=True, partition=1) if data_meta_table: value_bytes = data_meta_table.get(key, use_serialize=False)", "session_impl options = {} if work_mode == WorkMode.STANDALONE: options['eggroll.session.deploy.mode'] =", "table meta information :param data_table_name: table name of this data", "save data into data table :param version_log: :param in_version: :param", "this data table :param data_table_namespace: table name of this data", "of partition :param persistent: bool = True, :param create_if_missing: :param", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "data_table.put_all(kv_data) if in_version: version_log = \"[AUTO] save data at %s.\"", "# # Licensed under the Apache License, Version 2.0 (the", "None __lock = threading.Lock() @staticmethod def set_instance(instance): if not FateSession._instance:", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "table :param namespace: table namespace of data table :param partition:", "name of this data table :param data_table_namespace: table name of", "arch.api.table.eggroll2 import session_impl options = {} if work_mode == WorkMode.STANDALONE:", "persistent: bool = True, create_if_missing=True, error_if_exist=False, in_version: bool = False,", "data_table_namespace): \"\"\" get data table meta information :param data_table_name: table", ":param error_if_exist: :return: data table instance \"\"\" from arch.api.utils import", "partition=1) @staticmethod def save_data_table_meta(kv, data_table_name, data_table_namespace): \"\"\" save data table", "datetime import threading from typing import Iterable import six from", "arch.api.utils.core import json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, create_if_missing=True,", "= True, create_if_missing=True, error_if_exist=False, in_version: bool = False, version_log=None): \"\"\"", "json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, persistent=True, in_place_computing=False,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "namespace, persistent): pass # noinspection PyPep8Naming @abc.abstractmethod def generateUniqueId(self): pass", ":return: data table instance \"\"\" return FateSession.get_instance().table(name=name, namespace=namespace, create_if_missing=False, persistent=True,", "of this data table :param data_table_namespace: table name of this", "\"\"\" from arch.api.utils import version_control data_table = FateSession.get_instance().table(name=name, namespace=namespace, partition=partition,", "this data table :return: \"\"\" from arch.api.utils.core import json_loads data_meta_table", "from arch.api.table.eggroll2 import session_impl options = {} if work_mode ==", "_instance: 'FateSession' = None __lock = threading.Lock() @staticmethod def set_instance(instance):", "None @staticmethod def clean_table(namespace, regex_string='*'): try: FateSession.get_instance().cleanup(name=regex_string, namespace=namespace, persistent=False) except", "meta information :param key: :param data_table_name: table name of this", "data table :return: data table instance \"\"\" return FateSession.get_instance().table(name=name, namespace=namespace,", "create_if_missing=True, error_if_exist=False) if data_meta_table: metas = dict() for k, v", "error_if_exist=False) if data_meta_table: metas = dict() for k, v in", "\"\"\" get data table meta information :param key: :param data_table_name:", "persistent: bool = True, :param create_if_missing: :param error_if_exist: :return: data", "bool = True, :param create_if_missing: :param error_if_exist: :return: data table", "StoreTypes = StoreTypes.ROLLPAIR_LMDB): from arch.api.table import eggroll_util if backend.is_eggroll(): from", "typing import Iterable import six from arch.api import WorkMode, Backend", "v in kv.items(): data_meta_table.put(k, json_dumps(v)) @staticmethod def get_data_table_meta(key, data_table_name, data_table_namespace):", "== WorkMode.CLUSTER: options['eggroll.session.deploy.mode'] = \"cluster\" er_session = session_init(session_id=job_id, options=options) session", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "eggroll_util if backend.is_eggroll(): from arch.api.table.eggroll import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode,", "in_place_computing=False, create_if_missing=True, error_if_exist=False) if data_meta_table: metas = dict() for k,", "backend: Backend = Backend.EGGROLL2, persistent_engine: StoreTypes = StoreTypes.ROLLPAIR_LMDB): from arch.api.table", "from arch.api.utils.core import json_dumps data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace,", "from arch.api import WorkMode, Backend from arch.api.table.table import Table from", "value_bytes: return json_loads(value_bytes) else: return None else: return None @staticmethod", "information :param data_table_name: table name of this data table :param", "% data_table_name, namespace=data_table_namespace, partition=1, create_if_missing=True, error_if_exist=False, persistent=True, in_place_computing=False) for k,", "or implied. # See the License for the specific language", "def clean_table(namespace, regex_string='*'): try: FateSession.get_instance().cleanup(name=regex_string, namespace=namespace, persistent=False) except Exception as", "Rights Reserved. # # Licensed under the Apache License, Version", "table :return: data table instance \"\"\" return FateSession.get_instance().table(name=name, namespace=namespace, create_if_missing=False,", "namespace=data_table_namespace, partition=1, create_if_missing=True, error_if_exist=False, persistent=True, in_place_computing=False) for k, v in", "options['eggroll.session.deploy.mode'] = \"standalone\" elif work_mode == WorkMode.CLUSTER: options['eggroll.session.deploy.mode'] = \"cluster\"", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "eggroll.core.session import session_init from arch.api.table.eggroll2 import session_impl options = {}", "of data table :return: data table instance \"\"\" return FateSession.get_instance().table(name=name,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "into data table :param version_log: :param in_version: :param kv_data: :param", ":param name: table name of data table :param namespace: table", "import json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, create_if_missing=True, error_if_exist=False,", "limitations under the License. # import abc import datetime import", "table instance \"\"\" from arch.api.utils import version_control data_table = FateSession.get_instance().table(name=name,", "= dict() for k, v in data_meta_table.collect(use_serialize=False): metas[k] = json_loads(v)", "@abc.abstractmethod def stop(self): pass @staticmethod def get_data_table(name, namespace): \"\"\" return", "create_if_missing=create_if_missing, error_if_exist=error_if_exist) data_table.put_all(kv_data) if in_version: version_log = \"[AUTO] save data", "backend.is_eggroll(): from arch.api.table.eggroll import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session", "import WorkMode, Backend from arch.api.table.table import Table from eggroll.core.constants import", "metas else: return None @staticmethod def clean_table(namespace, regex_string='*'): try: FateSession.get_instance().cleanup(name=regex_string,", "\"\"\" save data into data table :param version_log: :param in_version:", "namespace=namespace, create_if_missing=False, persistent=True, error_if_exist=False, in_place_computing=False, partition=1) @staticmethod def save_data_table_meta(kv, data_table_name,", ":param namespace: table namespace of data table :param partition: number", "(the \"License\"); # you may not use this file except", "# you may not use this file except in compliance", "partition: number of partition :param persistent: bool = True, :param", "data table :return: \"\"\" from arch.api.utils.core import json_loads data_meta_table =", "session = session_impl.FateSessionImpl(er_session, work_mode, persistent_engine) else: raise ValueError(f\"work_mode: {work_mode} not", "value_bytes = data_meta_table.get(key, use_serialize=False) if value_bytes: return json_loads(value_bytes) else: return", "the License. # import abc import datetime import threading from", "def generateUniqueId(self): pass @abc.abstractmethod def get_session_id(self): pass @abc.abstractmethod def stop(self):", "arch.api.utils.core import json_dumps data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1,", "error_if_exist) -> Table: pass @abc.abstractmethod def parallelize(self, data: Iterable, include_key,", "backend.is_spark(): from arch.api.table.pyspark import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session", "get_instance(): return FateSession._instance @abc.abstractmethod def get_persistent_engine(self): pass @abc.abstractmethod def table(self,", "if in_version: version_log = \"[AUTO] save data at %s.\" %", "% data_table_name, namespace=data_table_namespace, partition=1, persistent=True, in_place_computing=False, create_if_missing=True, error_if_exist=False) if data_meta_table:", "json_dumps data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, create_if_missing=True, error_if_exist=False,", "work_mode == WorkMode.CLUSTER: options['eggroll.session.deploy.mode'] = \"cluster\" er_session = session_init(session_id=job_id, options=options)", "# # Unless required by applicable law or agreed to", "error_if_exist=False, in_version: bool = False, version_log=None): \"\"\" save data into", "from arch.api.table.table import Table from eggroll.core.constants import StoreTypes def build_session(job_id=None,", "name of this data table :return: \"\"\" from arch.api.utils.core import", "get_persistent_engine(self): pass @abc.abstractmethod def table(self, name, namespace, partition, persistent, in_place_computing,", "@staticmethod def save_data(kv_data: Iterable, name, namespace, partition=1, persistent: bool =", "= \"cluster\" er_session = session_init(session_id=job_id, options=options) session = session_impl.FateSessionImpl(er_session, work_mode,", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_eggroll2(): from eggroll.core.session import session_init from", "serialized by JSON :param data_table_name: table name of this data", "key: :param data_table_name: table name of this data table :param", "FATE Authors. All Rights Reserved. # # Licensed under the", "and table name space :param name: table name of data", "Version 2.0 (the \"License\"); # you may not use this", "Exception as e: print(e) @staticmethod def save_data(kv_data: Iterable, name, namespace,", ":param partition: number of partition :param persistent: bool = True,", "namespace of data table :param partition: number of partition :param", "persistent=True, in_place_computing=False) for k, v in kv.items(): data_meta_table.put(k, json_dumps(v)) @staticmethod", "persistent_engine: StoreTypes = StoreTypes.ROLLPAIR_LMDB): from arch.api.table import eggroll_util if backend.is_eggroll():", "name space of data table :return: data table instance \"\"\"", "session_init from arch.api.table.eggroll2 import session_impl options = {} if work_mode", "table name of this data table :return: \"\"\" from arch.api.utils.core", "-> Table: pass @abc.abstractmethod def cleanup(self, name, namespace, persistent): pass", "implied. # See the License for the specific language governing", "get_data_table_meta(key, data_table_name, data_table_namespace): \"\"\" get data table meta information :param", "under the Apache License, Version 2.0 (the \"License\"); # you", "return data table instance by table name and table name", ":param kv: v should be serialized by JSON :param data_table_name:", "create_if_missing=True, error_if_exist=False, persistent=True, in_place_computing=False) for k, v in kv.items(): data_meta_table.put(k,", "WorkMode.STANDALONE: options['eggroll.session.deploy.mode'] = \"standalone\" elif work_mode == WorkMode.CLUSTER: options['eggroll.session.deploy.mode'] =", "session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine)", "by applicable law or agreed to in writing, software #", "of data table :param namespace: table name space of data", "name and table name space :param name: table name of", "work_mode, persistent_engine) elif backend.is_spark(): from arch.api.table.pyspark import session_impl eggroll_session =", "= data_meta_table.get(key, use_serialize=False) if value_bytes: return json_loads(value_bytes) else: return None", "namespace, partition=1, persistent: bool = True, create_if_missing=True, error_if_exist=False, in_version: bool", "def build_session(job_id=None, work_mode: WorkMode = WorkMode.STANDALONE, backend: Backend = Backend.EGGROLL2,", "FateSession._instance: FateSession._instance = instance @staticmethod def get_instance(): return FateSession._instance @abc.abstractmethod", "of data table :param partition: number of partition :param persistent:", "# limitations under the License. # import abc import datetime", "import json_dumps data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, create_if_missing=True,", "@staticmethod def get_instance(): return FateSession._instance @abc.abstractmethod def get_persistent_engine(self): pass @abc.abstractmethod", "save_data(kv_data: Iterable, name, namespace, partition=1, persistent: bool = True, create_if_missing=True,", "WorkMode, Backend from arch.api.table.table import Table from eggroll.core.constants import StoreTypes", "= Backend.EGGROLL2, persistent_engine: StoreTypes = StoreTypes.ROLLPAIR_LMDB): from arch.api.table import eggroll_util", "@staticmethod def get_data_table_metas(data_table_name, data_table_namespace): \"\"\" get data table meta information", "Backend.EGGROLL2, persistent_engine: StoreTypes = StoreTypes.ROLLPAIR_LMDB): from arch.api.table import eggroll_util if", "{work_mode} not supported\") return session @six.add_metaclass(abc.ABCMeta) class FateSession(object): _instance: 'FateSession'", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "def get_persistent_engine(self): pass @abc.abstractmethod def table(self, name, namespace, partition, persistent,", "table meta information :param key: :param data_table_name: table name of", "Unless required by applicable law or agreed to in writing,", "pass @abc.abstractmethod def parallelize(self, data: Iterable, include_key, name, partition, namespace,", "table :param partition: number of partition :param persistent: bool =", "from arch.api.table.pyspark import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session =", "\"\"\" from arch.api.utils.core import json_dumps data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name,", "\"standalone\" elif work_mode == WorkMode.CLUSTER: options['eggroll.session.deploy.mode'] = \"cluster\" er_session =", "# Copyright 2019 The FATE Authors. All Rights Reserved. #", "the specific language governing permissions and # limitations under the", "= \"standalone\" elif work_mode == WorkMode.CLUSTER: options['eggroll.session.deploy.mode'] = \"cluster\" er_session", "session_init(session_id=job_id, options=options) session = session_impl.FateSessionImpl(er_session, work_mode, persistent_engine) else: raise ValueError(f\"work_mode:", "True, create_if_missing=True, error_if_exist=False, in_version: bool = False, version_log=None): \"\"\" save", "False, version_log=None): \"\"\" save data into data table :param version_log:", ":param namespace: table name space of data table :return: data", "applicable law or agreed to in writing, software # distributed", ":param in_version: :param kv_data: :param name: table name of data", "options['eggroll.session.deploy.mode'] = \"cluster\" er_session = session_init(session_id=job_id, options=options) session = session_impl.FateSessionImpl(er_session,", "instance \"\"\" from arch.api.utils import version_control data_table = FateSession.get_instance().table(name=name, namespace=namespace,", "data_meta_table.collect(use_serialize=False): metas[k] = json_loads(v) return metas else: return None @staticmethod", "version_log = \"[AUTO] save data at %s.\" % datetime.datetime.now() if", "pass @abc.abstractmethod def table(self, name, namespace, partition, persistent, in_place_computing, create_if_missing,", "stop(self): pass @staticmethod def get_data_table(name, namespace): \"\"\" return data table", "import threading from typing import Iterable import six from arch.api", "version_log: :param in_version: :param kv_data: :param name: table name of", "else: return None else: return None @staticmethod def get_data_table_metas(data_table_name, data_table_namespace):", "in writing, software # distributed under the License is distributed", "{} if work_mode == WorkMode.STANDALONE: options['eggroll.session.deploy.mode'] = \"standalone\" elif work_mode", "# import abc import datetime import threading from typing import", "persistent, in_place_computing, create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod def parallelize(self,", "def get_data_table_meta(key, data_table_name, data_table_namespace): \"\"\" get data table meta information", "in_version: version_log = \"[AUTO] save data at %s.\" % datetime.datetime.now()", "data table meta information :param key: :param data_table_name: table name", "name, namespace, partition=1, persistent: bool = True, create_if_missing=True, error_if_exist=False, in_version:", "name, partition, namespace, persistent, chunk_size, in_place_computing, create_if_missing, error_if_exist) -> Table:", "Iterable, include_key, name, partition, namespace, persistent, chunk_size, in_place_computing, create_if_missing, error_if_exist)", "of this data table :return: \"\"\" from arch.api.utils.core import json_loads", "FateSession.get_instance().table(name=name, namespace=namespace, partition=partition, persistent=persistent, in_place_computing=False, create_if_missing=create_if_missing, error_if_exist=error_if_exist) data_table.put_all(kv_data) if in_version:", "\"\"\" from arch.api.utils.core import json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name,", "\"\"\" return FateSession.get_instance().table(name=name, namespace=namespace, create_if_missing=False, persistent=True, error_if_exist=False, in_place_computing=False, partition=1) @staticmethod", "table name space :param name: table name of data table", "session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_spark(): from arch.api.table.pyspark import", "%s.\" % datetime.datetime.now() if not version_log else version_log version_control.save_version(name=name, namespace=namespace,", "\"cluster\" er_session = session_init(session_id=job_id, options=options) session = session_impl.FateSessionImpl(er_session, work_mode, persistent_engine)", "namespace): \"\"\" return data table instance by table name and", "name: table name of data table :param namespace: table name", "% datetime.datetime.now() if not version_log else version_log version_control.save_version(name=name, namespace=namespace, version_log=version_log)", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "name, namespace, partition, persistent, in_place_computing, create_if_missing, error_if_exist) -> Table: pass", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "return FateSession.get_instance().table(name=name, namespace=namespace, create_if_missing=False, persistent=True, error_if_exist=False, in_place_computing=False, partition=1) @staticmethod def", "not FateSession._instance: FateSession._instance = instance @staticmethod def get_instance(): return FateSession._instance", "import session_impl options = {} if work_mode == WorkMode.STANDALONE: options['eggroll.session.deploy.mode']", "data_table_name, namespace=data_table_namespace, partition=1, persistent=True, in_place_computing=False, create_if_missing=True, error_if_exist=False) if data_meta_table: metas", "@staticmethod def get_data_table(name, namespace): \"\"\" return data table instance by", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "# noinspection PyPep8Naming @abc.abstractmethod def generateUniqueId(self): pass @abc.abstractmethod def get_session_id(self):", ":param version_log: :param in_version: :param kv_data: :param name: table name", "return None @staticmethod def clean_table(namespace, regex_string='*'): try: FateSession.get_instance().cleanup(name=regex_string, namespace=namespace, persistent=False)", "Authors. All Rights Reserved. # # Licensed under the Apache", "job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_spark(): from arch.api.table.pyspark", "return metas else: return None @staticmethod def clean_table(namespace, regex_string='*'): try:", "name: table name of data table :param namespace: table namespace", "error_if_exist: :return: data table instance \"\"\" from arch.api.utils import version_control", "@abc.abstractmethod def parallelize(self, data: Iterable, include_key, name, partition, namespace, persistent,", "namespace=namespace, persistent=False) except Exception as e: print(e) @staticmethod def save_data(kv_data:", "import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session = session_impl.FateSessionImpl(eggroll_session, work_mode,", "table name space of data table :return: data table instance", "kv: v should be serialized by JSON :param data_table_name: table", "if data_meta_table: metas = dict() for k, v in data_meta_table.collect(use_serialize=False):", "def get_data_table_metas(data_table_name, data_table_namespace): \"\"\" get data table meta information :param", "the License for the specific language governing permissions and #", "License. # import abc import datetime import threading from typing", "FateSession._instance: with FateSession.__lock: if not FateSession._instance: FateSession._instance = instance @staticmethod", "information :param key: :param data_table_name: table name of this data", "error_if_exist) -> Table: pass @abc.abstractmethod def cleanup(self, name, namespace, persistent):", "Apache License, Version 2.0 (the \"License\"); # you may not", "session = session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_eggroll2(): from eggroll.core.session import", "either express or implied. # See the License for the", "namespace: table namespace of data table :param partition: number of", "WorkMode.CLUSTER: options['eggroll.session.deploy.mode'] = \"cluster\" er_session = session_init(session_id=job_id, options=options) session =", "data_table_namespace: table name of this data table :return: \"\"\" from", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "clean_table(namespace, regex_string='*'): try: FateSession.get_instance().cleanup(name=regex_string, namespace=namespace, persistent=False) except Exception as e:", "six from arch.api import WorkMode, Backend from arch.api.table.table import Table", "2019 The FATE Authors. All Rights Reserved. # # Licensed", "data table meta information :param data_table_name: table name of this", "import abc import datetime import threading from typing import Iterable", "supported\") return session @six.add_metaclass(abc.ABCMeta) class FateSession(object): _instance: 'FateSession' = None", "use_serialize=False) if value_bytes: return json_loads(value_bytes) else: return None else: return", "= FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, create_if_missing=True, error_if_exist=False, persistent=True, in_place_computing=False)", "@abc.abstractmethod def get_session_id(self): pass @abc.abstractmethod def stop(self): pass @staticmethod def", "json_loads(v) return metas else: return None @staticmethod def clean_table(namespace, regex_string='*'):", "WorkMode = WorkMode.STANDALONE, backend: Backend = Backend.EGGROLL2, persistent_engine: StoreTypes =", "session_impl.FateSessionImpl(er_session, work_mode, persistent_engine) else: raise ValueError(f\"work_mode: {work_mode} not supported\") return", "parallelize(self, data: Iterable, include_key, name, partition, namespace, persistent, chunk_size, in_place_computing,", "name of data table :param namespace: table namespace of data", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "persistent=True, partition=1) if data_meta_table: value_bytes = data_meta_table.get(key, use_serialize=False) if value_bytes:", "FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1, create_if_missing=True, error_if_exist=False, persistent=True, in_place_computing=False) for", "v in data_meta_table.collect(use_serialize=False): metas[k] = json_loads(v) return metas else: return", "space of data table :return: data table instance \"\"\" return", "namespace, partition, persistent, in_place_computing, create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod", "= FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, create_if_missing=True, error_if_exist=False, in_place_computing=False, persistent=True, partition=1)", "# # Copyright 2019 The FATE Authors. All Rights Reserved.", "return None @staticmethod def get_data_table_metas(data_table_name, data_table_namespace): \"\"\" get data table", "data table :param version_log: :param in_version: :param kv_data: :param name:", "space :param name: table name of data table :param namespace:", "\"[AUTO] save data at %s.\" % datetime.datetime.now() if not version_log", "session_impl.FateSessionImpl(eggroll_session, work_mode, persistent_engine) elif backend.is_spark(): from arch.api.table.pyspark import session_impl eggroll_session", ":param key: :param data_table_name: table name of this data table", "data_meta_table.get(key, use_serialize=False) if value_bytes: return json_loads(value_bytes) else: return None else:", "create_if_missing=True, error_if_exist=False, in_place_computing=False, persistent=True, partition=1) if data_meta_table: value_bytes = data_meta_table.get(key,", "table :return: \"\"\" from arch.api.utils.core import json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\"", "from arch.api.table import eggroll_util if backend.is_eggroll(): from arch.api.table.eggroll import session_impl", "data_table_name, namespace=data_table_namespace, create_if_missing=True, error_if_exist=False, in_place_computing=False, persistent=True, partition=1) if data_meta_table: value_bytes", "partition=1) if data_meta_table: value_bytes = data_meta_table.get(key, use_serialize=False) if value_bytes: return", "\"License\"); # you may not use this file except in", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "pass @abc.abstractmethod def get_session_id(self): pass @abc.abstractmethod def stop(self): pass @staticmethod", "work_mode, persistent_engine) else: raise ValueError(f\"work_mode: {work_mode} not supported\") return session", "partition, namespace, persistent, chunk_size, in_place_computing, create_if_missing, error_if_exist) -> Table: pass", "StoreTypes.ROLLPAIR_LMDB): from arch.api.table import eggroll_util if backend.is_eggroll(): from arch.api.table.eggroll import", "dict() for k, v in data_meta_table.collect(use_serialize=False): metas[k] = json_loads(v) return", "# distributed under the License is distributed on an \"AS", "data table instance \"\"\" return FateSession.get_instance().table(name=name, namespace=namespace, create_if_missing=False, persistent=True, error_if_exist=False,", "# Unless required by applicable law or agreed to in", "@abc.abstractmethod def get_persistent_engine(self): pass @abc.abstractmethod def table(self, name, namespace, partition,", "include_key, name, partition, namespace, persistent, chunk_size, in_place_computing, create_if_missing, error_if_exist) ->", "FateSession._instance @abc.abstractmethod def get_persistent_engine(self): pass @abc.abstractmethod def table(self, name, namespace,", "arch.api.utils.core import json_loads data_meta_table = FateSession.get_instance().table(name=\"%s.meta\" % data_table_name, namespace=data_table_namespace, partition=1,", "data: Iterable, include_key, name, partition, namespace, persistent, chunk_size, in_place_computing, create_if_missing,", "if value_bytes: return json_loads(value_bytes) else: return None else: return None", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "in_place_computing, create_if_missing, error_if_exist) -> Table: pass @abc.abstractmethod def parallelize(self, data:", ":return: data table instance \"\"\" from arch.api.utils import version_control data_table", "import Iterable import six from arch.api import WorkMode, Backend from", "arch.api import WorkMode, Backend from arch.api.table.table import Table from eggroll.core.constants", "You may obtain a copy of the License at #", "backend.is_eggroll2(): from eggroll.core.session import session_init from arch.api.table.eggroll2 import session_impl options", "instance \"\"\" return FateSession.get_instance().table(name=name, namespace=namespace, create_if_missing=False, persistent=True, error_if_exist=False, in_place_computing=False, partition=1)", "import version_control data_table = FateSession.get_instance().table(name=name, namespace=namespace, partition=partition, persistent=persistent, in_place_computing=False, create_if_missing=create_if_missing,", "print(e) @staticmethod def save_data(kv_data: Iterable, name, namespace, partition=1, persistent: bool", "table(self, name, namespace, partition, persistent, in_place_computing, create_if_missing, error_if_exist) -> Table:", "if not FateSession._instance: FateSession._instance = instance @staticmethod def get_instance(): return", "namespace=data_table_namespace, partition=1, persistent=True, in_place_computing=False, create_if_missing=True, error_if_exist=False) if data_meta_table: metas =", "def cleanup(self, name, namespace, persistent): pass # noinspection PyPep8Naming @abc.abstractmethod", "in_place_computing=False, persistent=True, partition=1) if data_meta_table: value_bytes = data_meta_table.get(key, use_serialize=False) if", "data_meta_table.put(k, json_dumps(v)) @staticmethod def get_data_table_meta(key, data_table_name, data_table_namespace): \"\"\" get data", "the Apache License, Version 2.0 (the \"License\"); # you may", "name of data table :param namespace: table name space of", "of data table :param namespace: table namespace of data table", "FateSession(object): _instance: 'FateSession' = None __lock = threading.Lock() @staticmethod def", "from arch.api.table.eggroll import session_impl eggroll_session = eggroll_util.build_eggroll_session(work_mode=work_mode, job_id=job_id) session =", "persistent_engine) else: raise ValueError(f\"work_mode: {work_mode} not supported\") return session @six.add_metaclass(abc.ABCMeta)", "table :param version_log: :param in_version: :param kv_data: :param name: table", ":param data_table_namespace: table name of this data table :return: \"\"\"", "table :param data_table_namespace: table name of this data table :return:", "namespace=namespace, partition=partition, persistent=persistent, in_place_computing=False, create_if_missing=create_if_missing, error_if_exist=error_if_exist) data_table.put_all(kv_data) if in_version: version_log" ]
[ "1], '.') estimated_means = t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:, 0], estimated_means[:, 1],", "Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() if __name__ == '__main__': train_alternating()", "nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) decoder", "nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) #", "plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.') plt.title(\"Generated Samples\")", "log std_prior = 0 - 1 # d = 1", "plt.plot(np.array(log_probs)) plt.title(\"Log Probs\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1],", "the prior isn't very good and/or because the learning signal", "1000 HIDDEN_SIZE = 32 VERBOSE = False def swirl_data(batch_size): t", "that didn't seem to help. \"\"\" from torch.distributions import Normal", "decoder_opt): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents =", "nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) encoder_losses = [] decoder_losses", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt =", "HIDDEN_SIZE = 32 VERBOSE = False def swirl_data(batch_size): t =", "output[:, 0:1], output[:, 1:2] ) stds = log_stds.exp() epsilon =", "elbo.mean() loss = - reconstruction_log_prob.mean() # This is the second", "len(t.shape) == 2: t = t[:, 0] x = t", "encode(self, x): return self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self, x): output = self(x)", "- y) ** 2).mean() opt.zero_grad() loss.backward() opt.step() losses.append(loss.data.numpy()) if VERBOSE:", "t[:, 0] x = t * np.cos(t * SWIRL_RATE) /", "- kl + reconstruction_log_prob loss = - elbo.mean() # This", "= t * np.cos(t * SWIRL_RATE) / T y =", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) encoder_losses = []", "import torch import numpy as np import matplotlib.pyplot as plt", "'.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() if __name__ ==", "encoder_opt = Adam(encoder.parameters()) # This is the first place that", "Adam import torch import numpy as np import matplotlib.pyplot as", "loss.backward() encoder_opt.step() return loss def train_decoder(encoder, decoder, decoder_opt): batch, true_latents", "decoder, encoder_opt): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents,", "train_alternating(*_): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(),", "plt.title(\"Decoder Loss\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.')", "decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) elbo", "opt): losses = [] for _ in range(1000): x_np, y_np", "ptu.np_to_var(x_np) y = ptu.np_to_var(y_np) y_hat = encoder.encode(x) loss = ((y_hat", "from torch import nn as nn import railrl.torch.pytorch_util as ptu", "for _ in range(1000): x_np, y_np = swirl_data(BS) x =", "= t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") #", "decoder_means = decoder_output[:, 0:2] decoder_log_stds = decoder_output[:, 2:4] distribution =", "reconstruction_log_prob # loss = - elbo.mean() loss = - reconstruction_log_prob.mean()", "2 ) class Encoder(nn.Sequential): def encode(self, x): return self.get_encoding_and_suff_stats(x)[0] def", "help. \"\"\" from torch.distributions import Normal from torch.optim import Adam", "encoder_opt.zero_grad() loss.backward() encoder_opt.step() return loss def train_decoder(encoder, decoder, decoder_opt): batch,", "decoder, decoder_opt): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents", "latents = epsilon * stds + means latents = latents", "means latents = latents return latents, means, log_stds, stds class", "1], '.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.') plt.title(\"Original Samples\") plt.legend([\"Original\",", "** 2).mean() loss = loss# + latent_loss encoder_opt.zero_grad() loss.backward() encoder_opt.step()", "decoder_losses = [] for _ in range(100): for _ in", "true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents = encoder.encode(batch) decoder_output", "KL between a Gaussian and a standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\"", "2, 1) plt.plot(np.array(encoder_losses)) plt.title(\"Encoder Loss\") plt.subplot(2, 2, 2) plt.plot(np.array(decoder_losses)) plt.title(\"Decoder", "def train_decoder(encoder, decoder, decoder_opt): batch, true_latents = swirl_data(BS) batch =", "ptu.Variable(torch.randn(*means.size())) latents = epsilon * stds + means latents =", "= decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds = decoder_output[:, 2:4]", "ptu.np_to_var(batch) latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means = decoder_output[:,", "plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"])", "Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) loss = - reconstruction_log_prob.mean() decoder_opt.zero_grad()", "2).mean() opt.zero_grad() loss.backward() opt.step() losses.append(loss.data.numpy()) if VERBOSE: x_np, y_np =", "kl + reconstruction_log_prob # loss = - elbo.mean() loss =", "_ in range(100): for _ in range(N_BATCHES): encoder_losses.append( train_encoder(encoder, decoder,", "= - reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward() decoder_opt.step() return loss def train_alternating(*_):", "= ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np) latents = encoder.encode(vis_samples) reconstructed_samples =", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) decoder = Decoder(", "we cheat: latent_loss = ((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss", "2: t = t[:, 0] x = t * np.cos(t", "plt.title(\"KLs\") plt.subplot(2, 3, 3) plt.plot(np.array(log_probs)) plt.title(\"Log Probs\") plt.subplot(2, 3, 4)", "- elbo.mean() # This is the second place where we", "N_BATCHES = 2000 N_VIS = 1000 HIDDEN_SIZE = 32 VERBOSE", "torch.distributions import Normal from torch.optim import Adam import torch import", "= encoder.encode(batch) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds", "elbo = - kl + reconstruction_log_prob loss = - elbo.mean()", "However, this pretraining isn't # needed if you just add", "Loss\") plt.subplot(2, 3, 2) plt.plot(np.array(kls)) plt.title(\"KLs\") plt.subplot(2, 3, 3) plt.plot(np.array(log_probs))", "true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents, means, log_stds, stds", "means, log_stds = output[:, 0:2], output[:, 2:4] distribution = Normal(means,", "= ptu.np_to_var(batch) latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means =", "x_np, y_np = swirl_data(BS) x = ptu.np_to_var(x_np) y = ptu.np_to_var(y_np)", "VERBOSE: x_np, y_np = swirl_data(N_VIS) x = ptu.np_to_var(x_np) y_hat =", "** 2).mean() loss = loss + latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward()", "estimated_means[:, 1], '.') plt.title(\"Reconstruction\") # plt.legend([\"Samples\", \"Projected Latents\"]) plt.subplot(2, 3,", "as nn import railrl.torch.pytorch_util as ptu SWIRL_RATE = 1 T", "def train_alternating(*_): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE),", "plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.') plt.title(\"Generated Samples\") plt.subplot(2, 3, 5)", "kl_to_prior(means, log_stds, stds): \"\"\" KL between a Gaussian and a", "decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize vis_samples_np, true_latents_np =", "= distribution.log_prob(batch).sum(dim=1) loss = - reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward() decoder_opt.step() return", "if VERBOSE: x_np, y_np = swirl_data(N_VIS) x = ptu.np_to_var(x_np) y_hat", "log_probs = [] for _ in range(N_BATCHES): batch, true_latents =", "output[:, 1:2] ) stds = log_stds.exp() epsilon = ptu.Variable(torch.randn(*means.size())) latents", "stds ** 2 + means ** 2 ) class Encoder(nn.Sequential):", "plt.title(\"Encoder Loss\") plt.subplot(2, 2, 2) plt.plot(np.array(decoder_losses)) plt.title(\"Decoder Loss\") plt.subplot(2, 3,", "reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:, 0], estimated_means[:,", "encoder.encode(batch) # decoder_output = decoder(latents.detach()) decoder_output = decoder(latents) decoder_means =", "5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:,", "t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") # plt.legend([\"Samples\",", "0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0],", "= epsilon * stds + means latents = latents return", "log_stds = output[:, 0:2], output[:, 2:4] distribution = Normal(means, log_stds.exp())", "place that we cheat. However, this pretraining isn't # needed", "/ T data = np.array([x, y]).T noise = np.random.randn(batch_size, 2)", "nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) encoder_losses", "loss = - reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward() decoder_opt.step() return loss def", "= [] for _ in range(100): for _ in range(N_BATCHES):", "output = self(latents) means, log_stds = output[:, 0:2], output[:, 2:4]", "np.sin(t * SWIRL_RATE) / T return np.array([x, y]).T def kl_to_prior(means,", "train(): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(),", "reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) # elbo = - kl + reconstruction_log_prob", "plt.legend([\"Original\", \"True means\"]) plt.show() if __name__ == '__main__': train_alternating() #", "= kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) decoder_output = decoder(latents)", "kl = kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) decoder_output =", "'.') plt.title(\"Reconstruction\") plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.')", "* SWIRL_RATE) / T data = np.array([x, y]).T noise =", "log_stds, stds): \"\"\" KL between a Gaussian and a standard", "decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) loss", "t = np.random.uniform(size=batch_size, low=0, high=T) x = t * np.cos(t", "= log_stds.exp() epsilon = ptu.Variable(torch.randn(*means.size())) latents = epsilon * stds", "= ptu.np_to_var(y_np) y_hat = encoder.encode(x) loss = ((y_hat - y)", "log_stds, stds) latents = encoder.encode(batch) # decoder_output = decoder(latents.detach()) decoder_output", "+ latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward() decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy())", "np.array([x, y]).T def pretrain_encoder(encoder, opt): losses = [] for _", "prior isn't very good and/or because the learning signal is", "# needed if you just add the loss to the", "\"\"\" from torch.distributions import Normal from torch.optim import Adam import", "import numpy as np import matplotlib.pyplot as plt from torch", "2).mean() loss = loss# + latent_loss encoder_opt.zero_grad() loss.backward() encoder_opt.step() return", "reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) elbo = - kl + reconstruction_log_prob loss", "the second place where we cheat: latent_loss = ((ptu.np_to_var(true_latents) -", "/ T return np.array([x, y]).T def pretrain_encoder(encoder, opt): losses =", "train_encoder(encoder, decoder, encoder_opt).data.numpy() ) for _ in range(N_BATCHES): decoder_losses.append( train_decoder(encoder,", "5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) #", "SWIRL_RATE) / T y = t * np.sin(t * SWIRL_RATE)", "= decoder(latents.detach()) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds", "cheat: latent_loss = ((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss =", "and/or because the learning signal is pretty weak when both", "distribution.log_prob(batch).sum(dim=1) elbo = - kl + reconstruction_log_prob loss = -", "False def swirl_data(batch_size): t = np.random.uniform(size=batch_size, low=0, high=T) x =", "= output[:, 0:2], output[:, 2:4] distribution = Normal(means, log_stds.exp()) return", "+ means latents = latents return latents, means, log_stds, stds", "y_np = swirl_data(BS) x = ptu.np_to_var(x_np) y = ptu.np_to_var(y_np) y_hat", "loss.backward() decoder_opt.step() return loss def train_alternating(*_): encoder = Encoder( nn.Linear(2,", "This is the first place that we cheat. However, this", "/ T return np.array([x, y]).T def kl_to_prior(means, log_stds, stds): \"\"\"", "= 0 - 1 # d = 1 + stds", "- 1 # d = 1 + stds ** 2", "latent_loss = ((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss = loss", "decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 3, 1) plt.plot(np.array(losses))", "((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss = loss + latent_loss", "estimated_means = t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\")", "return np.array([x, y]).T def pretrain_encoder(encoder, opt): losses = [] for", "= encoder.encode(x) y_hat_np = y_hat.data.numpy() x_hat_np = t_to_xy(y_hat_np[:, 0]) plt.subplot(2,", "true_xy_mean_np[:, 1], '.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() if", "data + noise, t.reshape(-1, 1) def swirl_t_to_data(t): x = t", "= swirl_data(N_VIS) x = ptu.np_to_var(x_np) y_hat = encoder.encode(x) y_hat_np =", "- kl + reconstruction_log_prob # loss = - elbo.mean() loss", "= Adam(encoder.parameters()) # This is the first place that we", "because the learning signal is pretty weak when both the", "_ in range(N_BATCHES): decoder_losses.append( train_decoder(encoder, decoder, decoder_opt).data.numpy() ) # Visualize", "= decoder_output[:, 0:2] decoder_log_stds = decoder_output[:, 2:4] distribution = Normal(decoder_means,", "decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) # elbo = - kl +", "decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) elbo = - kl + reconstruction_log_prob", "= ((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss = loss +", "pretrain_encoder(encoder, encoder_opt) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE),", "encoder.get_encoding_and_suff_stats( batch ) kl = kl_to_prior(means, log_stds, stds) latents =", "SWIRL_RATE) / T return np.array([x, y]).T def pretrain_encoder(encoder, opt): losses", "nn as nn import railrl.torch.pytorch_util as ptu SWIRL_RATE = 1", "batch = ptu.np_to_var(batch) latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means", "Adam(encoder.parameters()) # This is the first place that we cheat.", "estimated_means = t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") plt.subplot(2,", "[] decoder_losses = [] for _ in range(100): for _", "2 + means ** 2 ) class Encoder(nn.Sequential): def encode(self,", "= - elbo.mean() loss = - reconstruction_log_prob.mean() # This is", "* SWIRL_RATE) / T y = t * np.sin(t *", "in range(100): for _ in range(N_BATCHES): encoder_losses.append( train_encoder(encoder, decoder, encoder_opt).data.numpy()", "0], true_xy_mean_np[:, 1], '.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show()", "\"True means\"]) plt.show() def train(): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE),", "+ noise, t.reshape(-1, 1) def swirl_t_to_data(t): x = t *", "= np.array([x, y]).T noise = np.random.randn(batch_size, 2) / (T *", "loss = - reconstruction_log_prob.mean() # This is the second place", "= decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1)", "y = ptu.np_to_var(y_np) y_hat = encoder.encode(x) loss = ((y_hat -", "decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) #", "range(N_BATCHES): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents, means,", "SWIRL_RATE) / T data = np.array([x, y]).T noise = np.random.randn(batch_size,", "y]).T def pretrain_encoder(encoder, opt): losses = [] for _ in", "\"\"\" return 0.5 * ( - 2 * log_stds #", "true_latents_np = swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np) latents", "T y = t * np.sin(t * SWIRL_RATE) / T", "didn't seem to help. \"\"\" from torch.distributions import Normal from", "np import matplotlib.pyplot as plt from torch import nn as", "0] x = t * np.cos(t * SWIRL_RATE) / T", "np.sin(t * SWIRL_RATE) / T return np.array([x, y]).T def pretrain_encoder(encoder,", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) print(\"Done training encoder\")", "3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.') plt.title(\"Generated Samples\") plt.subplot(2,", "1], '.') estimated_means = t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.')", "loss def train_decoder(encoder, decoder, decoder_opt): batch, true_latents = swirl_data(BS) batch", "self(latents) means, log_stds = output[:, 0:2], output[:, 2:4] distribution =", "SWIRL_RATE) / T return np.array([x, y]).T def kl_to_prior(means, log_stds, stds):", "# This is the second place where we cheat: latent_loss", "don't work. It's probably because the prior isn't very good", "between the two, and that didn't seem to help. \"\"\"", "decoder_opt).data.numpy() ) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples =", "return loss def train_decoder(encoder, decoder, decoder_opt): batch, true_latents = swirl_data(BS)", "= t_to_xy(true_latents_np) latents = encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples =", "= ((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss = loss# +", "'.') plt.title(\"Reconstruction\") # plt.legend([\"Samples\", \"Projected Latents\"]) plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:,", "vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np) latents = encoder.encode(vis_samples) reconstructed_samples", "plt.show() def train(): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "latent_loss = ((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss = loss#", "= False def swirl_data(batch_size): t = np.random.uniform(size=batch_size, low=0, high=T) x", "T = 10 BS = 128 N_BATCHES = 2000 N_VIS", "_ in range(N_BATCHES): encoder_losses.append( train_encoder(encoder, decoder, encoder_opt).data.numpy() ) for _", "2000 N_VIS = 1000 HIDDEN_SIZE = 32 VERBOSE = False", "torch import numpy as np import matplotlib.pyplot as plt from", "y) ** 2).mean() opt.zero_grad() loss.backward() opt.step() losses.append(loss.data.numpy()) if VERBOSE: x_np,", "decoder_log_stds = decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob =", "def decode(self, latents): output = self(latents) means, log_stds = output[:,", "= encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy()", "1], '.') plt.title(\"Generated Samples\") plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:,", "nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt", "epsilon * stds + means latents = latents return latents,", "((y_hat - y) ** 2).mean() opt.zero_grad() loss.backward() opt.step() losses.append(loss.data.numpy()) if", "= - reconstruction_log_prob.mean() # This is the second place where", "_ in range(N_BATCHES): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch)", "def pretrain_encoder(encoder, opt): losses = [] for _ in range(1000):", "log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np)", "nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "= t[:, 0] x = t * np.cos(t * SWIRL_RATE)", "decoder, decoder_opt).data.numpy() ) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples", "1], '.') plt.title(\"Samples\") plt.legend([\"Samples\", \"Estimates\"]) plt.show() def train_encoder(encoder, decoder, encoder_opt):", "x = ptu.np_to_var(x_np) y_hat = encoder.encode(x) y_hat_np = y_hat.data.numpy() x_hat_np", "Normal from torch.optim import Adam import torch import numpy as", "* stds + means latents = latents return latents, means,", "1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 1, 2) plt.plot(x_np[:, 0], x_np[:,", "BS = 128 N_BATCHES = 2000 N_VIS = 1000 HIDDEN_SIZE", "both the encoder and decoder change quickly. However, I tried", "kl + reconstruction_log_prob loss = - elbo.mean() # This is", "2).mean() loss = loss + latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward() decoder_opt.step()", "generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 3, 1) plt.plot(np.array(losses)) plt.title(\"Training", "as plt from torch import nn as nn import railrl.torch.pytorch_util", "log_stds # log std_prior = 0 - 1 # d", "quickly. However, I tried also alternating between the two, and", "Gaussian and a standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\" return 0.5 *", "= Adam(decoder.parameters()) print(\"Done training encoder\") losses = [] kls =", "= kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) # decoder_output =", "signal is pretty weak when both the encoder and decoder", "swirl_data(batch_size): t = np.random.uniform(size=batch_size, low=0, high=T) x = t *", "latents = latents return latents, means, log_stds, stds class Decoder(nn.Sequential):", "y_hat = encoder.encode(x) y_hat_np = y_hat.data.numpy() x_hat_np = t_to_xy(y_hat_np[:, 0])", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt =", "range(N_BATCHES): decoder_losses.append( train_decoder(encoder, decoder, decoder_opt).data.numpy() ) # Visualize vis_samples_np, true_latents_np", "Samples\") plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means", "3, 5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy())", "= decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 2, 1)", "weak when both the encoder and decoder change quickly. However,", "[] for _ in range(N_BATCHES): batch, true_latents = swirl_data(BS) batch", "(T * 2) return data + noise, t.reshape(-1, 1) def", "for _ in range(N_BATCHES): batch, true_latents = swirl_data(BS) batch =", "plt.subplot(2, 1, 2) plt.plot(x_np[:, 0], x_np[:, 1], '.') plt.plot(x_hat_np[:, 0],", "1:2] ) stds = log_stds.exp() epsilon = ptu.Variable(torch.randn(*means.size())) latents =", "- elbo.mean() loss = - reconstruction_log_prob.mean() # This is the", "x_np[:, 1], '.') plt.plot(x_hat_np[:, 0], x_hat_np[:, 1], '.') plt.title(\"Samples\") plt.legend([\"Samples\",", "the encoder and decoder change quickly. However, I tried also", "plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") # plt.legend([\"Samples\", \"Projected Latents\"])", "decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "Adam(decoder.parameters()) print(\"Done training encoder\") losses = [] kls = []", "- reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward() decoder_opt.step() return loss def train_alternating(*_): encoder", "x): return self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self, x): output = self(x) means,", "plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 3, 2) plt.plot(np.array(kls)) plt.title(\"KLs\") plt.subplot(2, 3,", "** 2).mean() opt.zero_grad() loss.backward() opt.step() losses.append(loss.data.numpy()) if VERBOSE: x_np, y_np", "'.') estimated_means = t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.')", "is the first place that we cheat. However, this pretraining", "stds + means latents = latents return latents, means, log_stds,", "if len(t.shape) == 2: t = t[:, 0] x =", "0]) plt.subplot(2, 1, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 1, 2)", "latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward() decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) #", "However, I tried also alternating between the two, and that", "stds): \"\"\" KL between a Gaussian and a standard Gaussian.", "torch.optim import Adam import torch import numpy as np import", "stds) latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means = decoder_output[:,", "y_hat_np = y_hat.data.numpy() x_hat_np = t_to_xy(y_hat_np[:, 0]) plt.subplot(2, 1, 1)", "is pretty weak when both the encoder and decoder change", "train_encoder(encoder, decoder, encoder_opt): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch)", "encoder_opt).data.numpy() ) for _ in range(N_BATCHES): decoder_losses.append( train_decoder(encoder, decoder, decoder_opt).data.numpy()", "= - kl + reconstruction_log_prob loss = - elbo.mean() #", "ptu.np_to_var(x_np) y_hat = encoder.encode(x) y_hat_np = y_hat.data.numpy() x_hat_np = t_to_xy(y_hat_np[:,", "Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(),", "needed if you just add the loss to the training", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) # This", "y_hat.data.numpy() x_hat_np = t_to_xy(y_hat_np[:, 0]) plt.subplot(2, 1, 1) plt.plot(np.array(losses)) plt.title(\"Training", "* 2) return data + noise, t.reshape(-1, 1) def swirl_t_to_data(t):", "if you just add the loss to the training (see", "below) # pretrain_encoder(encoder, encoder_opt) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(),", "distribution = Normal(means, log_stds.exp()) return distribution.sample() def t_to_xy(t): if len(t.shape)", "# Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np", "0.5 * ( - 2 * log_stds # log std_prior", "0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") # plt.legend([\"Samples\", \"Projected Latents\"]) plt.subplot(2,", "we cheat. However, this pretraining isn't # needed if you", "\"\"\" VAE on the swirl task. Basically, VAEs don't work.", "range(N_BATCHES): encoder_losses.append( train_encoder(encoder, decoder, encoder_opt).data.numpy() ) for _ in range(N_BATCHES):", "ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 2, 1) plt.plot(np.array(encoder_losses)) plt.title(\"Encoder Loss\") plt.subplot(2, 2,", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters())", "[] log_probs = [] for _ in range(N_BATCHES): batch, true_latents", "[] for _ in range(1000): x_np, y_np = swirl_data(BS) x", "loss = ((y_hat - y) ** 2).mean() opt.zero_grad() loss.backward() opt.step()", "VAEs don't work. It's probably because the prior isn't very", "(see below) # pretrain_encoder(encoder, encoder_opt) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE),", "between a Gaussian and a standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\" return", "= np.random.randn(batch_size, 2) / (T * 2) return data +", "class Decoder(nn.Sequential): def decode(self, latents): output = self(latents) means, log_stds", "high=T) x = t * np.cos(t * SWIRL_RATE) / T", "and that didn't seem to help. \"\"\" from torch.distributions import", "= Normal(means, log_stds.exp()) return distribution.sample() def t_to_xy(t): if len(t.shape) ==", "+ stds ** 2 + means ** 2 ) class", "nn import railrl.torch.pytorch_util as ptu SWIRL_RATE = 1 T =", "y = t * np.sin(t * SWIRL_RATE) / T data", "the learning signal is pretty weak when both the encoder", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) decoder =", "np.array([x, y]).T def kl_to_prior(means, log_stds, stds): \"\"\" KL between a", "= ptu.np_to_var(x_np) y_hat = encoder.encode(x) y_hat_np = y_hat.data.numpy() x_hat_np =", "plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:,", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2),", "= 1 T = 10 BS = 128 N_BATCHES =", "log_stds = ( output[:, 0:1], output[:, 1:2] ) stds =", "encoder_losses.append( train_encoder(encoder, decoder, encoder_opt).data.numpy() ) for _ in range(N_BATCHES): decoder_losses.append(", "return 0.5 * ( - 2 * log_stds # log", "pretty weak when both the encoder and decoder change quickly.", "= Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) elbo = - kl", "plt.subplot(2, 1, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 1, 2) plt.plot(x_np[:,", "return latents, means, log_stds, stds class Decoder(nn.Sequential): def decode(self, latents):", "as ptu SWIRL_RATE = 1 T = 10 BS =", "1) plt.plot(np.array(encoder_losses)) plt.title(\"Encoder Loss\") plt.subplot(2, 2, 2) plt.plot(np.array(decoder_losses)) plt.title(\"Decoder Loss\")", "\"True means\"]) plt.show() if __name__ == '__main__': train_alternating() # train()", "128 N_BATCHES = 2000 N_VIS = 1000 HIDDEN_SIZE = 32", "distribution.log_prob(batch).sum(dim=1) # elbo = - kl + reconstruction_log_prob # loss", "isn't # needed if you just add the loss to", "2) plt.plot(np.array(decoder_losses)) plt.title(\"Decoder Loss\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:,", "t_to_xy(y_hat_np[:, 0]) plt.subplot(2, 1, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 1,", "2), ) encoder_opt = Adam(encoder.parameters()) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE),", ") encoder_opt = Adam(encoder.parameters()) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(),", "d = 1 + stds ** 2 + means **", "# pretrain_encoder(encoder, encoder_opt) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "encoder_opt) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(),", "1], '.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() if __name__", "= self(latents) means, log_stds = output[:, 0:2], output[:, 2:4] distribution", "https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\" return 0.5 * ( - 2 * log_stds", "= Adam(encoder.parameters()) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE),", "'.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() def train(): encoder", "Encoder(nn.Sequential): def encode(self, x): return self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self, x): output", "np.cos(t * SWIRL_RATE) / T y = t * np.sin(t", "generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 2, 1) plt.plot(np.array(encoder_losses)) plt.title(\"Encoder", "Loss\") plt.subplot(2, 1, 2) plt.plot(x_np[:, 0], x_np[:, 1], '.') plt.plot(x_hat_np[:,", "train_decoder(encoder, decoder, decoder_opt): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch)", "torch import nn as nn import railrl.torch.pytorch_util as ptu SWIRL_RATE", "= [] decoder_losses = [] for _ in range(100): for", "kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) # decoder_output = decoder(latents.detach())", "decoder_output[:, 0:2] decoder_log_stds = decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp())", "elbo = - kl + reconstruction_log_prob # loss = -", "the training (see below) # pretrain_encoder(encoder, encoder_opt) decoder = Decoder(", "you just add the loss to the training (see below)", "t.reshape(-1, 1) def swirl_t_to_data(t): x = t * np.cos(t *", "means\"]) plt.show() def train(): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(),", "plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:,", "= swirl_data(BS) x = ptu.np_to_var(x_np) y = ptu.np_to_var(y_np) y_hat =", "swirl_t_to_data(t): x = t * np.cos(t * SWIRL_RATE) / T", "cheat. However, this pretraining isn't # needed if you just", "plt.title(\"Generated Samples\") plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.')", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) # This is", "* np.sin(t * SWIRL_RATE) / T return np.array([x, y]).T def", "stds = encoder.get_encoding_and_suff_stats( batch ) kl = kl_to_prior(means, log_stds, stds)", "y = t * np.sin(t * SWIRL_RATE) / T return", "a Gaussian and a standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\" return 0.5", "return distribution.sample() def t_to_xy(t): if len(t.shape) == 2: t =", "plt.plot(x_np[:, 0], x_np[:, 1], '.') plt.plot(x_hat_np[:, 0], x_hat_np[:, 1], '.')", "and decoder change quickly. However, I tried also alternating between", "4), ) decoder_opt = Adam(decoder.parameters()) print(\"Done training encoder\") losses =", "t * np.cos(t * SWIRL_RATE) / T y = t", "= Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) # elbo = -", "Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) # elbo = - kl", "from torch.distributions import Normal from torch.optim import Adam import torch", "place where we cheat: latent_loss = ((ptu.np_to_var(true_latents) - latents) **", "[] kls = [] log_probs = [] for _ in", "the swirl task. Basically, VAEs don't work. It's probably because", "import Adam import torch import numpy as np import matplotlib.pyplot", "work. It's probably because the prior isn't very good and/or", "return np.array([x, y]).T def kl_to_prior(means, log_stds, stds): \"\"\" KL between", "decoder_opt.step() return loss def train_alternating(*_): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE),", "first place that we cheat. However, this pretraining isn't #", "- 2 * log_stds # log std_prior = 0 -", "** 2 ) class Encoder(nn.Sequential): def encode(self, x): return self.get_encoding_and_suff_stats(x)[0]", "Adam(decoder.parameters()) encoder_losses = [] decoder_losses = [] for _ in", "self(x) means, log_stds = ( output[:, 0:1], output[:, 1:2] )", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(),", "* np.sin(t * SWIRL_RATE) / T data = np.array([x, y]).T", "encoder_opt = Adam(encoder.parameters()) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "= Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE),", "opt.zero_grad() loss.backward() opt.step() losses.append(loss.data.numpy()) if VERBOSE: x_np, y_np = swirl_data(N_VIS)", "= swirl_data(BS) batch = ptu.np_to_var(batch) latents = encoder.encode(batch) decoder_output =", "2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) # elbo", "x): output = self(x) means, log_stds = ( output[:, 0:1],", ") class Encoder(nn.Sequential): def encode(self, x): return self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self,", "x = ptu.np_to_var(x_np) y = ptu.np_to_var(y_np) y_hat = encoder.encode(x) loss", "= Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) loss = - reconstruction_log_prob.mean()", "= [] log_probs = [] for _ in range(N_BATCHES): batch,", "encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS)", "swirl_data(BS) batch = ptu.np_to_var(batch) latents = encoder.encode(batch) decoder_output = decoder(latents)", "2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) elbo =", "the first place that we cheat. However, this pretraining isn't", "/ (T * 2) return data + noise, t.reshape(-1, 1)", "train_decoder(encoder, decoder, decoder_opt).data.numpy() ) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS)", "and a standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\" return 0.5 * (", "encoder_opt.step() return loss def train_decoder(encoder, decoder, decoder_opt): batch, true_latents =", "decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds = decoder_output[:,", "seem to help. \"\"\" from torch.distributions import Normal from torch.optim", "range(100): for _ in range(N_BATCHES): encoder_losses.append( train_encoder(encoder, decoder, encoder_opt).data.numpy() )", "log_stds, stds class Decoder(nn.Sequential): def decode(self, latents): output = self(latents)", ") for _ in range(N_BATCHES): decoder_losses.append( train_decoder(encoder, decoder, decoder_opt).data.numpy() )", "10 BS = 128 N_BATCHES = 2000 N_VIS = 1000", "plt.subplot(2, 3, 3) plt.plot(np.array(log_probs)) plt.title(\"Log Probs\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:,", "pretrain_encoder(encoder, opt): losses = [] for _ in range(1000): x_np,", "Normal(means, log_stds.exp()) return distribution.sample() def t_to_xy(t): if len(t.shape) == 2:", "Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(),", "t_to_xy(true_latents_np) latents = encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples = decoder.decode(", "2) plt.plot(np.array(kls)) plt.title(\"KLs\") plt.subplot(2, 3, 3) plt.plot(np.array(log_probs)) plt.title(\"Log Probs\") plt.subplot(2,", "a standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\" return 0.5 * ( -", "means, log_stds = ( output[:, 0:1], output[:, 1:2] ) stds", "np.random.randn(batch_size, 2) / (T * 2) return data + noise,", "to the training (see below) # pretrain_encoder(encoder, encoder_opt) decoder =", "y_hat = encoder.encode(x) loss = ((y_hat - y) ** 2).mean()", "swirl task. Basically, VAEs don't work. It's probably because the", "T return np.array([x, y]).T def pretrain_encoder(encoder, opt): losses = []", "1) def swirl_t_to_data(t): x = t * np.cos(t * SWIRL_RATE)", "reconstruction_log_prob.mean() # This is the second place where we cheat:", "plt.title(\"Samples\") plt.legend([\"Samples\", \"Estimates\"]) plt.show() def train_encoder(encoder, decoder, encoder_opt): batch, true_latents", "distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) elbo = -", "kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means", "reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 3,", "ptu SWIRL_RATE = 1 T = 10 BS = 128", "where we cheat: latent_loss = ((ptu.np_to_var(true_latents) - latents) ** 2).mean()", "- latents) ** 2).mean() loss = loss + latent_loss decoder_opt.zero_grad()", "1, 2) plt.plot(x_np[:, 0], x_np[:, 1], '.') plt.plot(x_hat_np[:, 0], x_hat_np[:,", "t_to_xy(t): if len(t.shape) == 2: t = t[:, 0] x", "stds = log_stds.exp() epsilon = ptu.Variable(torch.randn(*means.size())) latents = epsilon *", "nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) decoder = Decoder( nn.Linear(1,", "1], '.') plt.plot(x_hat_np[:, 0], x_hat_np[:, 1], '.') plt.title(\"Samples\") plt.legend([\"Samples\", \"Estimates\"])", "4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.') plt.title(\"Generated Samples\") plt.subplot(2, 3,", "ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 3, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 3,", "/ T y = t * np.sin(t * SWIRL_RATE) /", "= - kl + reconstruction_log_prob # loss = - elbo.mean()", "# elbo = - kl + reconstruction_log_prob # loss =", "import nn as nn import railrl.torch.pytorch_util as ptu SWIRL_RATE =", "= ptu.Variable(torch.randn(*means.size())) latents = epsilon * stds + means latents", "= latents return latents, means, log_stds, stds class Decoder(nn.Sequential): def", "decoder_opt.zero_grad() loss.backward() decoder_opt.step() return loss def train_alternating(*_): encoder = Encoder(", "32 VERBOSE = False def swirl_data(batch_size): t = np.random.uniform(size=batch_size, low=0,", "= [] for _ in range(1000): x_np, y_np = swirl_data(BS)", "1 # d = 1 + stds ** 2 +", "plt.legend([\"Samples\", \"Estimates\"]) plt.show() def train_encoder(encoder, decoder, encoder_opt): batch, true_latents =", "log_stds, stds) latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means =", "latents = encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape))", "4), ) decoder_opt = Adam(decoder.parameters()) encoder_losses = [] decoder_losses =", "= loss + latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward() decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy())", "((ptu.np_to_var(true_latents) - latents) ** 2).mean() loss = loss# + latent_loss", ") decoder_opt = Adam(decoder.parameters()) encoder_losses = [] decoder_losses = []", "3) plt.plot(np.array(log_probs)) plt.title(\"Log Probs\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:,", "encoder and decoder change quickly. However, I tried also alternating", "batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents, means, log_stds,", "'.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True", "swirl_data(N_VIS) x = ptu.np_to_var(x_np) y_hat = encoder.encode(x) y_hat_np = y_hat.data.numpy()", "reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 2,", ") # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np)", "y]).T def kl_to_prior(means, log_stds, stds): \"\"\" KL between a Gaussian", "plt.title(\"Reconstruction\") # plt.legend([\"Samples\", \"Projected Latents\"]) plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0],", "= swirl_data(BS) batch = ptu.np_to_var(batch) latents, means, log_stds, stds =", "= Adam(decoder.parameters()) encoder_losses = [] decoder_losses = [] for _", "swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np) latents = encoder.encode(vis_samples)", "nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters()) # This is the", "noise = np.random.randn(batch_size, 2) / (T * 2) return data", "ptu.np_to_var(y_np) y_hat = encoder.encode(x) loss = ((y_hat - y) **", "= decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 3, 1)", "opt.step() losses.append(loss.data.numpy()) if VERBOSE: x_np, y_np = swirl_data(N_VIS) x =", "= t * np.sin(t * SWIRL_RATE) / T return np.array([x,", "batch = ptu.np_to_var(batch) latents, means, log_stds, stds = encoder.get_encoding_and_suff_stats( batch", "tried also alternating between the two, and that didn't seem", "latents = encoder.encode(batch) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2]", "plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means =", "true_xy_mean_np = t_to_xy(true_latents_np) latents = encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples", "plt from torch import nn as nn import railrl.torch.pytorch_util as", "Probs\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.') plt.title(\"Generated", "It's probably because the prior isn't very good and/or because", "Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\" return 0.5 * ( - 2 *", "kls = [] log_probs = [] for _ in range(N_BATCHES):", "decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) loss = - reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward()", "np.sin(t * SWIRL_RATE) / T data = np.array([x, y]).T noise", "ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np) latents = encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy()", "= t * np.sin(t * SWIRL_RATE) / T data =", "swirl_data(BS) batch = ptu.np_to_var(batch) latents, means, log_stds, stds = encoder.get_encoding_and_suff_stats(", "Latents\"]) plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:,", "latents = encoder.encode(batch) # decoder_output = decoder(latents.detach()) decoder_output = decoder(latents)", "( output[:, 0:1], output[:, 1:2] ) stds = log_stds.exp() epsilon", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) print(\"Done training", "# This is the first place that we cheat. However,", "Adam(encoder.parameters()) decoder = Decoder( nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(),", "6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1],", "noise, t.reshape(-1, 1) def swirl_t_to_data(t): x = t * np.cos(t", "3, 3) plt.plot(np.array(log_probs)) plt.title(\"Log Probs\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0],", "def swirl_t_to_data(t): x = t * np.cos(t * SWIRL_RATE) /", "2) plt.plot(x_np[:, 0], x_np[:, 1], '.') plt.plot(x_hat_np[:, 0], x_hat_np[:, 1],", "return self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self, x): output = self(x) means, log_stds", "stds class Decoder(nn.Sequential): def decode(self, latents): output = self(latents) means,", "distribution.log_prob(batch).sum(dim=1) loss = - reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward() decoder_opt.step() return loss", ") kl = kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) #", "+ reconstruction_log_prob loss = - elbo.mean() # This is the", "t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") plt.subplot(2, 3, 6)", "= 1000 HIDDEN_SIZE = 32 VERBOSE = False def swirl_data(batch_size):", "latents) ** 2).mean() loss = loss + latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad()", "2), ) encoder_opt = Adam(encoder.parameters()) # This is the first", "as np import matplotlib.pyplot as plt from torch import nn", "return data + noise, t.reshape(-1, 1) def swirl_t_to_data(t): x =", "= t_to_xy(y_hat_np[:, 0]) plt.subplot(2, 1, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2,", "x = t * np.cos(t * SWIRL_RATE) / T y", "* np.cos(t * SWIRL_RATE) / T y = t *", "range(1000): x_np, y_np = swirl_data(BS) x = ptu.np_to_var(x_np) y =", "# d = 1 + stds ** 2 + means", "plt.title(\"Log Probs\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.')", "means, log_stds, stds class Decoder(nn.Sequential): def decode(self, latents): output =", "latents, means, log_stds, stds = encoder.get_encoding_and_suff_stats( batch ) kl =", "decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 2, 1) plt.plot(np.array(encoder_losses))", "elbo.mean() # This is the second place where we cheat:", "0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0], estimated_means[:,", "t * np.sin(t * SWIRL_RATE) / T return np.array([x, y]).T", "stds) latents = encoder.encode(batch) # decoder_output = decoder(latents.detach()) decoder_output =", "plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() def train(): encoder =", "encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "np.array([x, y]).T noise = np.random.randn(batch_size, 2) / (T * 2)", "SWIRL_RATE = 1 T = 10 BS = 128 N_BATCHES", "that we cheat. However, this pretraining isn't # needed if", ") decoder_opt = Adam(decoder.parameters()) print(\"Done training encoder\") losses = []", "= encoder.get_encoding_and_suff_stats( batch ) kl = kl_to_prior(means, log_stds, stds) latents", "plt.plot(np.array(encoder_losses)) plt.title(\"Encoder Loss\") plt.subplot(2, 2, 2) plt.plot(np.array(decoder_losses)) plt.title(\"Decoder Loss\") plt.subplot(2,", "0:1], output[:, 1:2] ) stds = log_stds.exp() epsilon = ptu.Variable(torch.randn(*means.size()))", "* SWIRL_RATE) / T return np.array([x, y]).T def pretrain_encoder(encoder, opt):", "def get_encoding_and_suff_stats(self, x): output = self(x) means, log_stds = (", "def kl_to_prior(means, log_stds, stds): \"\"\" KL between a Gaussian and", "y]).T noise = np.random.randn(batch_size, 2) / (T * 2) return", "def train_encoder(encoder, decoder, encoder_opt): batch, true_latents = swirl_data(BS) batch =", "encoder.encode(x) loss = ((y_hat - y) ** 2).mean() opt.zero_grad() loss.backward()", "vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np)", "plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0],", "kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples =", "= [] for _ in range(N_BATCHES): batch, true_latents = swirl_data(BS)", "= 128 N_BATCHES = 2000 N_VIS = 1000 HIDDEN_SIZE =", "plt.subplot(2, 3, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 3, 2) plt.plot(np.array(kls))", "plt.subplot(2, 3, 2) plt.plot(np.array(kls)) plt.title(\"KLs\") plt.subplot(2, 3, 3) plt.plot(np.array(log_probs)) plt.title(\"Log", "= y_hat.data.numpy() x_hat_np = t_to_xy(y_hat_np[:, 0]) plt.subplot(2, 1, 1) plt.plot(np.array(losses))", "encoder\") losses = [] kls = [] log_probs = []", "I tried also alternating between the two, and that didn't", "0], x_np[:, 1], '.') plt.plot(x_hat_np[:, 0], x_hat_np[:, 1], '.') plt.title(\"Samples\")", "plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 1, 2) plt.plot(x_np[:, 0], x_np[:, 1],", "1], '.') plt.title(\"Reconstruction\") plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1],", "for _ in range(N_BATCHES): encoder_losses.append( train_encoder(encoder, decoder, encoder_opt).data.numpy() ) for", "plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.')", "= ( output[:, 0:1], output[:, 1:2] ) stds = log_stds.exp()", "Decoder(nn.Sequential): def decode(self, latents): output = self(latents) means, log_stds =", "x_hat_np[:, 1], '.') plt.title(\"Samples\") plt.legend([\"Samples\", \"Estimates\"]) plt.show() def train_encoder(encoder, decoder,", "loss def train_alternating(*_): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "in range(N_BATCHES): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents,", "Basically, VAEs don't work. It's probably because the prior isn't", "loss = - elbo.mean() # This is the second place", "get_encoding_and_suff_stats(self, x): output = self(x) means, log_stds = ( output[:,", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4),", "= loss# + latent_loss encoder_opt.zero_grad() loss.backward() encoder_opt.step() return loss def", "import Normal from torch.optim import Adam import torch import numpy", "= self(x) means, log_stds = ( output[:, 0:1], output[:, 1:2]", "matplotlib.pyplot as plt from torch import nn as nn import", "def train(): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE),", "2) return data + noise, t.reshape(-1, 1) def swirl_t_to_data(t): x", "Loss\") plt.subplot(2, 2, 2) plt.plot(np.array(decoder_losses)) plt.title(\"Decoder Loss\") plt.subplot(2, 3, 4)", "N_VIS = 1000 HIDDEN_SIZE = 32 VERBOSE = False def", "This is the second place where we cheat: latent_loss =", "decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward() decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize", "0:2] decoder_log_stds = decoder_output[:, 2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob", "distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) loss = -", "nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "generated_samples[:, 1], '.') plt.title(\"Generated Samples\") plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:, 0],", ") encoder_opt = Adam(encoder.parameters()) # This is the first place", "return loss def train_alternating(*_): encoder = Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(),", "# log std_prior = 0 - 1 # d =", "because the prior isn't very good and/or because the learning", "0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.') plt.title(\"Original", "0 - 1 # d = 1 + stds **", "plt.legend([\"Original\", \"True means\"]) plt.show() def train(): encoder = Encoder( nn.Linear(2,", "= [] kls = [] log_probs = [] for _", "latents return latents, means, log_stds, stds class Decoder(nn.Sequential): def decode(self,", "encoder.encode(batch) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds =", "# plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") # plt.legend([\"Samples\", \"Projected", "np.random.uniform(size=batch_size, low=0, high=T) x = t * np.cos(t * SWIRL_RATE)", "log_stds, stds = encoder.get_encoding_and_suff_stats( batch ) kl = kl_to_prior(means, log_stds,", "Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np =", "also alternating between the two, and that didn't seem to", "t = t[:, 0] x = t * np.cos(t *", "just add the loss to the training (see below) #", "nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) print(\"Done", "in range(1000): x_np, y_np = swirl_data(BS) x = ptu.np_to_var(x_np) y", "= ((y_hat - y) ** 2).mean() opt.zero_grad() loss.backward() opt.step() losses.append(loss.data.numpy())", "+ latent_loss encoder_opt.zero_grad() loss.backward() encoder_opt.step() return loss def train_decoder(encoder, decoder,", "def t_to_xy(t): if len(t.shape) == 2: t = t[:, 0]", "+ reconstruction_log_prob # loss = - elbo.mean() loss = -", "second place where we cheat: latent_loss = ((ptu.np_to_var(true_latents) - latents)", "decoder, encoder_opt).data.numpy() ) for _ in range(N_BATCHES): decoder_losses.append( train_decoder(encoder, decoder,", "2:4] distribution = Normal(means, log_stds.exp()) return distribution.sample() def t_to_xy(t): if", "in range(N_BATCHES): encoder_losses.append( train_encoder(encoder, decoder, encoder_opt).data.numpy() ) for _ in", "the two, and that didn't seem to help. \"\"\" from", "\"Projected Latents\"]) plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.')", "plt.title(\"Reconstruction\") plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:,", "distribution.sample() def t_to_xy(t): if len(t.shape) == 2: t = t[:,", "is the second place where we cheat: latent_loss = ((ptu.np_to_var(true_latents)", "for _ in range(N_BATCHES): decoder_losses.append( train_decoder(encoder, decoder, decoder_opt).data.numpy() ) #", "losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize vis_samples_np, true_latents_np = swirl_data(N_VIS) vis_samples", "class Encoder(nn.Sequential): def encode(self, x): return self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self, x):", "batch ) kl = kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch)", "\"\"\" KL between a Gaussian and a standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians", "== 2: t = t[:, 0] x = t *", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), )", "standard Gaussian. https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians \"\"\" return 0.5 * ( - 2", "pretraining isn't # needed if you just add the loss", "# plt.legend([\"Samples\", \"Projected Latents\"]) plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:,", "T data = np.array([x, y]).T noise = np.random.randn(batch_size, 2) /", "* SWIRL_RATE) / T return np.array([x, y]).T def kl_to_prior(means, log_stds,", "[] for _ in range(100): for _ in range(N_BATCHES): encoder_losses.append(", "\"Estimates\"]) plt.show() def train_encoder(encoder, decoder, encoder_opt): batch, true_latents = swirl_data(BS)", "def swirl_data(batch_size): t = np.random.uniform(size=batch_size, low=0, high=T) x = t", "reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward() decoder_opt.step() return loss def train_alternating(*_): encoder =", "means, log_stds, stds = encoder.get_encoding_and_suff_stats( batch ) kl = kl_to_prior(means,", "loss# + latent_loss encoder_opt.zero_grad() loss.backward() encoder_opt.step() return loss def train_decoder(encoder,", "= 32 VERBOSE = False def swirl_data(batch_size): t = np.random.uniform(size=batch_size,", "1 + stds ** 2 + means ** 2 )", "= swirl_data(N_VIS) vis_samples = ptu.np_to_var(vis_samples_np) true_xy_mean_np = t_to_xy(true_latents_np) latents =", "= decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 2, 1) plt.plot(np.array(encoder_losses)) plt.title(\"Encoder Loss\")", "0], x_hat_np[:, 1], '.') plt.title(\"Samples\") plt.legend([\"Samples\", \"Estimates\"]) plt.show() def train_encoder(encoder,", "print(\"Done training encoder\") losses = [] kls = [] log_probs", ").data.numpy() plt.subplot(2, 2, 1) plt.plot(np.array(encoder_losses)) plt.title(\"Encoder Loss\") plt.subplot(2, 2, 2)", "0], reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) # plt.plot(estimated_means[:, 0],", "plt.subplot(2, 2, 1) plt.plot(np.array(encoder_losses)) plt.title(\"Encoder Loss\") plt.subplot(2, 2, 2) plt.plot(np.array(decoder_losses))", "latents, means, log_stds, stds class Decoder(nn.Sequential): def decode(self, latents): output", "on the swirl task. Basically, VAEs don't work. It's probably", "2:4] distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) loss =", "( - 2 * log_stds # log std_prior = 0", "3, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 3, 2) plt.plot(np.array(kls)) plt.title(\"KLs\")", "y_np = swirl_data(N_VIS) x = ptu.np_to_var(x_np) y_hat = encoder.encode(x) y_hat_np", "self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self, x): output = self(x) means, log_stds =", "log_stds.exp()) return distribution.sample() def t_to_xy(t): if len(t.shape) == 2: t", "encoder_losses = [] decoder_losses = [] for _ in range(100):", "losses.append(loss.data.numpy()) if VERBOSE: x_np, y_np = swirl_data(N_VIS) x = ptu.np_to_var(x_np)", "latents) ** 2).mean() loss = loss# + latent_loss encoder_opt.zero_grad() loss.backward()", "plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:, 0],", "output[:, 0:2], output[:, 2:4] distribution = Normal(means, log_stds.exp()) return distribution.sample()", "nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) print(\"Done training encoder\") losses", "ptu.np_to_var(batch) latents, means, log_stds, stds = encoder.get_encoding_and_suff_stats( batch ) kl", "plt.title(\"Training Loss\") plt.subplot(2, 3, 2) plt.plot(np.array(kls)) plt.title(\"KLs\") plt.subplot(2, 3, 3)", "loss.backward() opt.step() losses.append(loss.data.numpy()) if VERBOSE: x_np, y_np = swirl_data(N_VIS) x", "distribution = Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) # elbo =", "# loss = - elbo.mean() loss = - reconstruction_log_prob.mean() #", "= 1 + stds ** 2 + means ** 2", "plt.subplot(2, 2, 2) plt.plot(np.array(decoder_losses)) plt.title(\"Decoder Loss\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:,", "= decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 3, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\")", "= distribution.log_prob(batch).sum(dim=1) # elbo = - kl + reconstruction_log_prob #", "loss = - elbo.mean() loss = - reconstruction_log_prob.mean() # This", "log_stds.exp() epsilon = ptu.Variable(torch.randn(*means.size())) latents = epsilon * stds +", "plt.title(\"Training Loss\") plt.subplot(2, 1, 2) plt.plot(x_np[:, 0], x_np[:, 1], '.')", "data = np.array([x, y]).T noise = np.random.randn(batch_size, 2) / (T", "1 T = 10 BS = 128 N_BATCHES = 2000", "decoder_opt = Adam(decoder.parameters()) print(\"Done training encoder\") losses = [] kls", "0:2], output[:, 2:4] distribution = Normal(means, log_stds.exp()) return distribution.sample() def", "VERBOSE = False def swirl_data(batch_size): t = np.random.uniform(size=batch_size, low=0, high=T)", "decoder_output = decoder(latents.detach()) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2]", "nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt", "learning signal is pretty weak when both the encoder and", "latents): output = self(latents) means, log_stds = output[:, 0:2], output[:,", "loss to the training (see below) # pretrain_encoder(encoder, encoder_opt) decoder", "= 2000 N_VIS = 1000 HIDDEN_SIZE = 32 VERBOSE =", "swirl_data(BS) x = ptu.np_to_var(x_np) y = ptu.np_to_var(y_np) y_hat = encoder.encode(x)", "= distribution.log_prob(batch).sum(dim=1) elbo = - kl + reconstruction_log_prob loss =", "- latents) ** 2).mean() loss = loss# + latent_loss encoder_opt.zero_grad()", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), )", "training (see below) # pretrain_encoder(encoder, encoder_opt) decoder = Decoder( nn.Linear(1,", "vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:, 1], '.') plt.title(\"Original Samples\")", "nn.Linear(1, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE,", "2 * log_stds # log std_prior = 0 - 1", "when both the encoder and decoder change quickly. However, I", "Loss\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1], '.') plt.title(\"Generated", "change quickly. However, I tried also alternating between the two,", "encoder.encode(x) y_hat_np = y_hat.data.numpy() x_hat_np = t_to_xy(y_hat_np[:, 0]) plt.subplot(2, 1,", "decoder change quickly. However, I tried also alternating between the", "task. Basically, VAEs don't work. It's probably because the prior", "= np.random.uniform(size=batch_size, low=0, high=T) x = t * np.cos(t *", "import railrl.torch.pytorch_util as ptu SWIRL_RATE = 1 T = 10", "decoder_losses.append( train_decoder(encoder, decoder, decoder_opt).data.numpy() ) # Visualize vis_samples_np, true_latents_np =", "= - elbo.mean() # This is the second place where", "very good and/or because the learning signal is pretty weak", "import matplotlib.pyplot as plt from torch import nn as nn", "plt.plot(np.array(kls)) plt.title(\"KLs\") plt.subplot(2, 3, 3) plt.plot(np.array(log_probs)) plt.title(\"Log Probs\") plt.subplot(2, 3,", "= ptu.np_to_var(x_np) y = ptu.np_to_var(y_np) y_hat = encoder.encode(x) loss =", "true_xy_mean_np[:, 1], '.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() def", "0], generated_samples[:, 1], '.') plt.title(\"Generated Samples\") plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:,", "losses = [] kls = [] log_probs = [] for", "decoder_opt = Adam(decoder.parameters()) encoder_losses = [] decoder_losses = [] for", "def encode(self, x): return self.get_encoding_and_suff_stats(x)[0] def get_encoding_and_suff_stats(self, x): output =", "decoder(latents.detach()) decoder_output = decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds =", "epsilon = ptu.Variable(torch.randn(*means.size())) latents = epsilon * stds + means", ").data.numpy() plt.subplot(2, 3, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 3, 2)", "plt.show() def train_encoder(encoder, decoder, encoder_opt): batch, true_latents = swirl_data(BS) batch", "VAE on the swirl task. Basically, VAEs don't work. It's", "latent_loss encoder_opt.zero_grad() loss.backward() encoder_opt.step() return loss def train_decoder(encoder, decoder, decoder_opt):", "= encoder.encode(batch) # decoder_output = decoder(latents.detach()) decoder_output = decoder(latents) decoder_means", "'.') plt.title(\"Samples\") plt.legend([\"Samples\", \"Estimates\"]) plt.show() def train_encoder(encoder, decoder, encoder_opt): batch,", "= t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\") plt.subplot(2, 3,", "probably because the prior isn't very good and/or because the", "plt.plot(np.array(decoder_losses)) plt.title(\"Decoder Loss\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0], generated_samples[:, 1],", "= Encoder( nn.Linear(2, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE),", "decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 2, 1) plt.plot(np.array(encoder_losses)) plt.title(\"Encoder Loss\") plt.subplot(2,", "losses = [] for _ in range(1000): x_np, y_np =", "encoder_opt.zero_grad() loss.backward() decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize vis_samples_np,", "decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2, 3, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2,", "loss + latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward() decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy())", "* ( - 2 * log_stds # log std_prior =", "Normal(decoder_means, decoder_log_stds.exp()) reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) elbo = - kl +", "1, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 1, 2) plt.plot(x_np[:, 0],", "3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1], '.') plt.plot(true_xy_mean_np[:, 0], true_xy_mean_np[:,", "* log_stds # log std_prior = 0 - 1 #", "add the loss to the training (see below) # pretrain_encoder(encoder,", "good and/or because the learning signal is pretty weak when", "loss = loss# + latent_loss encoder_opt.zero_grad() loss.backward() encoder_opt.step() return loss", "in range(N_BATCHES): decoder_losses.append( train_decoder(encoder, decoder, decoder_opt).data.numpy() ) # Visualize vis_samples_np,", "+ means ** 2 ) class Encoder(nn.Sequential): def encode(self, x):", "estimated_means[:, 1], '.') plt.title(\"Reconstruction\") plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:,", "** 2 + means ** 2 ) class Encoder(nn.Sequential): def", "from torch.optim import Adam import torch import numpy as np", "the loss to the training (see below) # pretrain_encoder(encoder, encoder_opt)", "'.') estimated_means = t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0], estimated_means[:, 1], '.') plt.title(\"Reconstruction\")", "'.') plt.title(\"Generated Samples\") plt.subplot(2, 3, 5) plt.plot(reconstructed_samples[:, 0], reconstructed_samples[:, 1],", "plt.legend([\"Samples\", \"Projected Latents\"]) plt.subplot(2, 3, 6) plt.plot(vis_samples_np[:, 0], vis_samples_np[:, 1],", "decode(self, latents): output = self(latents) means, log_stds = output[:, 0:2],", "output = self(x) means, log_stds = ( output[:, 0:1], output[:,", "decoder(latents) decoder_means = decoder_output[:, 0:2] decoder_log_stds = decoder_output[:, 2:4] distribution", "encoder_opt): batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents, means,", "this pretraining isn't # needed if you just add the", "3, 2) plt.plot(np.array(kls)) plt.title(\"KLs\") plt.subplot(2, 3, 3) plt.plot(np.array(log_probs)) plt.title(\"Log Probs\")", "2) / (T * 2) return data + noise, t.reshape(-1,", "reconstruction_log_prob loss = - elbo.mean() # This is the second", "to help. \"\"\" from torch.distributions import Normal from torch.optim import", "= 10 BS = 128 N_BATCHES = 2000 N_VIS =", "x_np, y_np = swirl_data(N_VIS) x = ptu.np_to_var(x_np) y_hat = encoder.encode(x)", "kl = kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) # decoder_output", "alternating between the two, and that didn't seem to help.", "numpy as np import matplotlib.pyplot as plt from torch import", ") stds = log_stds.exp() epsilon = ptu.Variable(torch.randn(*means.size())) latents = epsilon", "reconstruction_log_prob = distribution.log_prob(batch).sum(dim=1) loss = - reconstruction_log_prob.mean() decoder_opt.zero_grad() loss.backward() decoder_opt.step()", "'.') plt.plot(x_hat_np[:, 0], x_hat_np[:, 1], '.') plt.title(\"Samples\") plt.legend([\"Samples\", \"Estimates\"]) plt.show()", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE),", "nn.ReLU(), nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 2), ) encoder_opt = Adam(encoder.parameters())", "t * np.sin(t * SWIRL_RATE) / T data = np.array([x,", "HIDDEN_SIZE), nn.ReLU(), nn.Linear(HIDDEN_SIZE, 4), ) decoder_opt = Adam(decoder.parameters()) encoder_losses =", "for _ in range(100): for _ in range(N_BATCHES): encoder_losses.append( train_encoder(encoder,", "training encoder\") losses = [] kls = [] log_probs =", "encoder.encode(vis_samples) reconstructed_samples = decoder.decode(latents).data.numpy() generated_samples = decoder.decode( ptu.Variable(torch.randn(*latents.shape)) ).data.numpy() plt.subplot(2,", "1], '.') plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() def train():", "loss = loss + latent_loss decoder_opt.zero_grad() encoder_opt.zero_grad() loss.backward() decoder_opt.step() encoder_opt.step()", "reconstructed_samples[:, 1], '.') estimated_means = t_to_xy(latents.data.numpy()) plt.plot(estimated_means[:, 0], estimated_means[:, 1],", "plt.plot(x_hat_np[:, 0], x_hat_np[:, 1], '.') plt.title(\"Samples\") plt.legend([\"Samples\", \"Estimates\"]) plt.show() def", "_ in range(1000): x_np, y_np = swirl_data(BS) x = ptu.np_to_var(x_np)", "means ** 2 ) class Encoder(nn.Sequential): def encode(self, x): return", "= encoder.encode(x) loss = ((y_hat - y) ** 2).mean() opt.zero_grad()", "railrl.torch.pytorch_util as ptu SWIRL_RATE = 1 T = 10 BS", "1) plt.plot(np.array(losses)) plt.title(\"Training Loss\") plt.subplot(2, 3, 2) plt.plot(np.array(kls)) plt.title(\"KLs\") plt.subplot(2,", "T return np.array([x, y]).T def kl_to_prior(means, log_stds, stds): \"\"\" KL", "- reconstruction_log_prob.mean() # This is the second place where we", "Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() def train(): encoder = Encoder(", "plt.title(\"Original Samples\") plt.legend([\"Original\", \"True means\"]) plt.show() if __name__ == '__main__':", "output[:, 2:4] distribution = Normal(means, log_stds.exp()) return distribution.sample() def t_to_xy(t):", "isn't very good and/or because the learning signal is pretty", "1], '.') plt.title(\"Reconstruction\") # plt.legend([\"Samples\", \"Projected Latents\"]) plt.subplot(2, 3, 6)", "low=0, high=T) x = t * np.cos(t * SWIRL_RATE) /", "loss.backward() decoder_opt.step() encoder_opt.step() losses.append(loss.data.numpy()) kls.append(kl.mean().data.numpy()) log_probs.append(reconstruction_log_prob.mean().data.numpy()) # Visualize vis_samples_np, true_latents_np", "# decoder_output = decoder(latents.detach()) decoder_output = decoder(latents) decoder_means = decoder_output[:,", "x_hat_np = t_to_xy(y_hat_np[:, 0]) plt.subplot(2, 1, 1) plt.plot(np.array(losses)) plt.title(\"Training Loss\")", "two, and that didn't seem to help. \"\"\" from torch.distributions", "std_prior = 0 - 1 # d = 1 +", ") kl = kl_to_prior(means, log_stds, stds) latents = encoder.encode(batch) decoder_output", "batch, true_latents = swirl_data(BS) batch = ptu.np_to_var(batch) latents = encoder.encode(batch)", "2, 2) plt.plot(np.array(decoder_losses)) plt.title(\"Decoder Loss\") plt.subplot(2, 3, 4) plt.plot(generated_samples[:, 0],", "= ptu.np_to_var(batch) latents, means, log_stds, stds = encoder.get_encoding_and_suff_stats( batch )" ]
[ "board def load_bitstream(self, bitstream_file): cmd = [\"openFPGALoader\", \"--board\", self.board, \"--bitstream\",", "flash(self, address, data_file): cmd = [\"openFPGALoader\", \"--board\", self.board, \"--write-flash\", \"--bitstream\",", "file is part of LiteX. # # Copyright (c) 2020", "class OpenFPGALoader(GenericProgrammer): needs_bitreverse = False def __init__(self, board): self.board =", "BSD-2-Clause from litex.build.tools import write_to_file from litex.build.generic_programmer import GenericProgrammer #", "False def __init__(self, board): self.board = board def load_bitstream(self, bitstream_file):", "bitstream_file] self.call(cmd) def flash(self, address, data_file): cmd = [\"openFPGALoader\", \"--board\",", "def flash(self, address, data_file): cmd = [\"openFPGALoader\", \"--board\", self.board, \"--write-flash\",", "<<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.tools import write_to_file from litex.build.generic_programmer", "address, data_file): cmd = [\"openFPGALoader\", \"--board\", self.board, \"--write-flash\", \"--bitstream\", data_file]", "self.call(cmd) def flash(self, address, data_file): cmd = [\"openFPGALoader\", \"--board\", self.board,", "import write_to_file from litex.build.generic_programmer import GenericProgrammer # openFPGAloader ------------------------------------------------------------------------------------------ class", "GenericProgrammer # openFPGAloader ------------------------------------------------------------------------------------------ class OpenFPGALoader(GenericProgrammer): needs_bitreverse = False def", "from litex.build.generic_programmer import GenericProgrammer # openFPGAloader ------------------------------------------------------------------------------------------ class OpenFPGALoader(GenericProgrammer): needs_bitreverse", "def __init__(self, board): self.board = board def load_bitstream(self, bitstream_file): cmd", "board): self.board = board def load_bitstream(self, bitstream_file): cmd = [\"openFPGALoader\",", "load_bitstream(self, bitstream_file): cmd = [\"openFPGALoader\", \"--board\", self.board, \"--bitstream\", bitstream_file] self.call(cmd)", "part of LiteX. # # Copyright (c) 2020 <NAME> <<EMAIL>>", "def load_bitstream(self, bitstream_file): cmd = [\"openFPGALoader\", \"--board\", self.board, \"--bitstream\", bitstream_file]", "SPDX-License-Identifier: BSD-2-Clause from litex.build.tools import write_to_file from litex.build.generic_programmer import GenericProgrammer", "from litex.build.tools import write_to_file from litex.build.generic_programmer import GenericProgrammer # openFPGAloader", "cmd = [\"openFPGALoader\", \"--board\", self.board, \"--bitstream\", bitstream_file] self.call(cmd) def flash(self,", "This file is part of LiteX. # # Copyright (c)", "is part of LiteX. # # Copyright (c) 2020 <NAME>", "bitstream_file): cmd = [\"openFPGALoader\", \"--board\", self.board, \"--bitstream\", bitstream_file] self.call(cmd) def", "openFPGAloader ------------------------------------------------------------------------------------------ class OpenFPGALoader(GenericProgrammer): needs_bitreverse = False def __init__(self, board):", "= [\"openFPGALoader\", \"--board\", self.board, \"--write-flash\", \"--bitstream\", data_file] if address: cmd.append(\"--offset\")", "= board def load_bitstream(self, bitstream_file): cmd = [\"openFPGALoader\", \"--board\", self.board,", "[\"openFPGALoader\", \"--board\", self.board, \"--bitstream\", bitstream_file] self.call(cmd) def flash(self, address, data_file):", "= [\"openFPGALoader\", \"--board\", self.board, \"--bitstream\", bitstream_file] self.call(cmd) def flash(self, address,", "litex.build.generic_programmer import GenericProgrammer # openFPGAloader ------------------------------------------------------------------------------------------ class OpenFPGALoader(GenericProgrammer): needs_bitreverse =", "\"--board\", self.board, \"--bitstream\", bitstream_file] self.call(cmd) def flash(self, address, data_file): cmd", "Copyright (c) 2020 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.tools", "data_file): cmd = [\"openFPGALoader\", \"--board\", self.board, \"--write-flash\", \"--bitstream\", data_file] if", "# Copyright (c) 2020 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from", "cmd = [\"openFPGALoader\", \"--board\", self.board, \"--write-flash\", \"--bitstream\", data_file] if address:", "OpenFPGALoader(GenericProgrammer): needs_bitreverse = False def __init__(self, board): self.board = board", "\"--bitstream\", bitstream_file] self.call(cmd) def flash(self, address, data_file): cmd = [\"openFPGALoader\",", "LiteX. # # Copyright (c) 2020 <NAME> <<EMAIL>> # SPDX-License-Identifier:", "of LiteX. # # Copyright (c) 2020 <NAME> <<EMAIL>> #", "\"--board\", self.board, \"--write-flash\", \"--bitstream\", data_file] if address: cmd.append(\"--offset\") cmd.append(address) self.call(cmd)", "2020 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.tools import write_to_file", "needs_bitreverse = False def __init__(self, board): self.board = board def", "__init__(self, board): self.board = board def load_bitstream(self, bitstream_file): cmd =", "self.board = board def load_bitstream(self, bitstream_file): cmd = [\"openFPGALoader\", \"--board\",", "self.board, \"--bitstream\", bitstream_file] self.call(cmd) def flash(self, address, data_file): cmd =", "[\"openFPGALoader\", \"--board\", self.board, \"--write-flash\", \"--bitstream\", data_file] if address: cmd.append(\"--offset\") cmd.append(address)", "# # Copyright (c) 2020 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause", "------------------------------------------------------------------------------------------ class OpenFPGALoader(GenericProgrammer): needs_bitreverse = False def __init__(self, board): self.board", "# # This file is part of LiteX. # #", "# openFPGAloader ------------------------------------------------------------------------------------------ class OpenFPGALoader(GenericProgrammer): needs_bitreverse = False def __init__(self,", "litex.build.tools import write_to_file from litex.build.generic_programmer import GenericProgrammer # openFPGAloader ------------------------------------------------------------------------------------------", "= False def __init__(self, board): self.board = board def load_bitstream(self,", "(c) 2020 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.tools import", "import GenericProgrammer # openFPGAloader ------------------------------------------------------------------------------------------ class OpenFPGALoader(GenericProgrammer): needs_bitreverse = False", "write_to_file from litex.build.generic_programmer import GenericProgrammer # openFPGAloader ------------------------------------------------------------------------------------------ class OpenFPGALoader(GenericProgrammer):", "<NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.tools import write_to_file from", "# This file is part of LiteX. # # Copyright", "# SPDX-License-Identifier: BSD-2-Clause from litex.build.tools import write_to_file from litex.build.generic_programmer import" ]
[ "label(s) predIdx = np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return \"\" else: return self.labels[predIdx]", "img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = resnet.predict(x) import numpy", "from time import time from keras.applications.resnet50 import ResNet50 from keras.models", "os.path import exists if(exists(labels)): f = open(labels,'r') x = f.readlines()", "with softmax activation. from time import time from keras.applications.resnet50 import", "target_size = (224,224), batch_size = 32, class_mode=None) #use ResNet50 to", "= self.extModel.predict(features) #get max of predictions and return label(s) predIdx", "features = model.predict_generator(generator,target_image_count/32) #features = np.reshape(features,(features.shape[0],features.shape[3])) #save the features in", "if(isinstance(labels,str)): #its a file path from os.path import exists if(exists(labels)):", "#check if image is a filepath if(isinstance(img,str)): if(not os.path.exists(img)): print(\"Error:", "model = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the data generation datagen = ImageDataGenerator()", "Dense from sklearn.utils import shuffle from keras.callbacks import EarlyStopping, ModelCheckpoint", "with open(output_folder+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n' for label in", "i in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y = np.vstack([l for l in", "classes #Outputs: #training array and training labels #label array is", "the features features = model.predict_generator(generator,target_image_count/32) #features = np.reshape(features,(features.shape[0],features.shape[3])) #save the", "their respective labels #INPUTS: #a directory containing npy fils of", "find location: \" + location) return for label in listdir(location):", "for i in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y = np.vstack([l for l", "numpy as np #check if image is a filepath if(isinstance(img,str)):", "return self.extModel def set_labels(self,labels): self.labels = labels def get_labels(self): return", "as input a 2048-vector of feature maps and outputs #a", "way to concatenate data arrays = [] sizes = []", "import load_model from keras.applications.resnet50 import ResNet50 self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel", "verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1) early = EarlyStopping(monitor='val_acc', min_delta=0, patience=10,", "\"\" else: return self.labels[predIdx] def set_extModel(self,model): self.extModel = model def", "layers of ResNet50 using all #images from the directory #INPUT:", "containing the 2048-dimensional feature vector #produced by ResNet50's convolutional layers", "image img = Image.open(image) shape = resnet.input_shape imgr = img.resize(shape[1:3])", "= resnet.predict(x) import numpy as np npyname = train_dir+'/'+label+'.npy' if(not", "validation class #OUTPUTS #A model that takes as input a", "= np.vstack([arr for arr in arrays]) #load the labels into", "numpy as np npyname = train_dir+'/'+label+'.npy' if(not exists(npyname)): np.save(npyname,features) else:", "= listdir(data_path) for f in data_contents: if(f.endswith('.npy')): num_classes +=1 label_names.append(f.split('.')[0])", "on either a high ram machine #or find another way", "ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel = load_model(modelpath) if(isinstance(labels,str)): #its a file path from", "predictions and return label(s) predIdx = np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return \"\"", "in batches of 32 import numpy as np from keras.preprocessing.image", "neuron. #Labels must be the same size as the output", "#a directory containing npy fils of all different classes #Outputs:", "if(f.endswith('.npy')): num_classes +=1 label_names.append(f.split('.')[0]) if(num_classes==0): print(\"Could not find any data", "output neuron. #Labels must be the same size as the", "the directory containig the training images #test_dir is the directory", "is returned as a one hot encoding #label names from", "softmax activation. from time import time from keras.applications.resnet50 import ResNet50", "memory labelcodes = [] for i in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y", "= shuffle(X_train,y_train) num_classes = len(labels) #create the extension model print(\"Creating", "ResNet50's convolutional layers #data is generated in batches of 32", "train_dir+'/'+label+'.npy' if(not exists(npyname)): np.save(npyname,features) else: fullset = np.load(npyname) newset =", "#its a file path from os.path import exists if(exists(labels)): f", "Sequential from keras.optimizers import SGD from keras.regularizers import l2 from", "img = Image.open(img) #resize image #shape from model input shape", "import listdir from os.path import isdir #create the model, if", "from PIL import Image from os.path import exists from keras.preprocessing.image", "and training labels #label array is returned as a one", "import img_to_array import numpy as np #check if image is", "keras.models import load_model from keras.applications.resnet50 import ResNet50 self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3))", "images. (Very Important) #the number of feature maps to generate", "array is returned as a one hot encoding #label names", "from keras.applications.resnet50 import ResNet50 from os import listdir from os.path", "into memory. #In the future, might need to do this", "= load_model(modelpath) if(isinstance(labels,str)): #its a file path from os.path import", "an image with those features might be. #The labels file", "in if(not isdir(location)): print(\"could not find location: \" + location)", "to generate for each image class #OUTPUT: #a npy file", "= img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = self.resnet.predict(x) prediction = self.extModel.predict(features) #get", "ResNet50 from os import listdir from os.path import isdir #create", "= Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks checkpoint = ModelCheckpoint(output_dir", "numpy binary np.save(location+'/'+label+'.npy', features) def create_data_set(data_path,output_folder,save_to_file=True): #combines all npy files", "generate for each validation class #OUTPUTS #A model that takes", "model input shape = self.resnet.input_shape imgr = img.resize(shape[1:3]) x =", "+ label + \"...\") generator = datagen.flow_from_directory( label_path, target_size =", "print(\"Creating extension model...\") extModel = Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"])", "import Image from keras.preprocessing.image import img_to_array import numpy as np", "create_data_set(data_path,output_folder,save_to_file=True): #combines all npy files into one large file with", "generate_features_from_directory(location,target_image_count,model=None): #generates feature maps from the convolutional layers of ResNet50", "return extModel def add_to_train(train_dir,image,label, resnet): #INPUTS #Train_dir - the directory", "import exists from keras.preprocessing.image import img_to_array if(isinstance(image,str)): if(not exists(image)): print(\"Error:", "if(not isdir(data_path)): print(\"Could not find directory: \"+ data_path) return data_contents", "created is an SVM with softmax activation. from time import", "l in labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with open(output_folder+\"/labels.txt\",\"w\") as output:", "filepath if(isinstance(img,str)): if(not os.path.exists(img)): print(\"Error: Invalid File Path\") return \"\"", "save_weights_only=False, mode='auto', period=1) early = EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode='auto')", "layer of the neural network. def __init__(self, modelpath, labels, min_confidence", "labelcodes.append(np.vstack([labels[i]]*sizes[i])) y = np.vstack([l for l in labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X)", "file containing the 2048-dimensional feature vector #produced by ResNet50's convolutional", "= [] if(not isdir(data_path)): print(\"Could not find directory: \"+ data_path)", "keras.preprocessing.image import ImageDataGenerator from keras.applications.resnet50 import ResNet50 from os import", "monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1) early = EarlyStopping(monitor='val_acc', min_delta=0,", "#resize image #shape from model input shape = self.resnet.input_shape imgr", "layers #data is generated in batches of 32 import numpy", "and validation datasets for each class print(\"Generating Training Set...\") generate_features_from_directory(train_dir,train_size,model=resnet)", "generate for each training class #val_size is the number of", "#train model print(\"Training...\") extModel.fit(X_train,y_train, batch_size=32, epochs=50, validation_data=(X_val,y_val), callbacks = [checkpoint,early])", "directory in if(not isdir(location)): print(\"could not find location: \" +", "#test_dir is the directory containing the validation images #output_dir is", "generation datagen = ImageDataGenerator() #for each directory in if(not isdir(location)):", "#The model created is an SVM with softmax activation. from", "= [] for f in data_contents: if(f.endswith('.npy')): arr = np.load(data_path+'/'+f)", "for each training class #val_size is the number of images", "takes as input a 2048-vector of feature maps and outputs", "min_delta=0, patience=10, verbose=1, mode='auto') with open(output_dir+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label +", "#combines all npy files into one large file with their", "labels #INPUTS: #a directory containing npy fils of all different", "#create the extension model print(\"Creating extension model...\") extModel = Sequential()", "#label - the name of the item #Appends the features", "print(\"Could not find any data files in directory: \"+data_path) return", "import ResNet50 from os import listdir from os.path import isdir", "self.num_classes = len(labels) self.min_confidence=min_confidence def predict(self,img): import os from PIL", "numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.applications.resnet50 import", "num_classes = len(labels) #create the extension model print(\"Creating extension model...\")", "not find directory: \"+ data_path) return data_contents = listdir(data_path) for", "32, class_mode=None) #use ResNet50 to create the features features =", "np #find out how many classes num_classes = 0 label_names", "#INPUT: #directory containing NESTED DIRECTORIES of images. (Very Important) #the", "sizes.append(arr.shape[0]) arrays.append(arr) X = np.vstack([arr for arr in arrays]) #load", "class FoodClassifier: #Class Attributes: #model - the underlying keras model", "l2 from keras.layers import Dense from sklearn.utils import shuffle from", "return #generate one-hot label vectors labels = np.zeros([num_classes,num_classes]) for i", "of ResNet50 using all #images from the directory #INPUT: #directory", "class #OUTPUT: #a npy file containing the 2048-dimensional feature vector", "#the number of feature maps to generate for each image", "return self.min_confidence def generate_features_from_directory(location,target_image_count,model=None): #generates feature maps from the convolutional", "training and validation datasets for each class print(\"Generating Training Set...\")", "#INPUTS: #a directory containing npy fils of all different classes", "directory #The model created is an SVM with softmax activation.", "= len(labels) #create the extension model print(\"Creating extension model...\") extModel", "fils of all different classes #Outputs: #training array and training", "exists(npyname)): np.save(npyname,features) else: fullset = np.load(npyname) newset = np.append(fullset,features,axis=0) np.save(npyname,newset)", "if(not exists(image)): print(\"Error: Invalid File Path\") return \"\" else: #if", "= self.resnet.predict(x) prediction = self.extModel.predict(features) #get max of predictions and", "in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y = np.vstack([l for l in labelcodes])", "output.write(\"\".join([label + '\\n' for label in labels])) #train model print(\"Training...\")", "to be associated with the activation of each output neuron.", "#The labels file is also placed in this directory #The", "print(\"could not find location: \" + location) return for label", "EarlyStopping, ModelCheckpoint #import ResNet50 without top layer print(\"Loading the ResNet50", "the features of the new item to the training set", "the convolutional layers of ResNet50 using all #images from the", "ResNet50 self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel = load_model(modelpath) if(isinstance(labels,str)): #its a", "#a npy file containing the 2048-dimensional feature vector #produced by", "from keras.preprocessing.image import ImageDataGenerator from keras.applications.resnet50 import ResNet50 from os", "class #val_size is the number of images to generate for", "features features = model.predict_generator(generator,target_image_count/32) #features = np.reshape(features,(features.shape[0],features.shape[3])) #save the features", "= model.predict_generator(generator,target_image_count/32) #features = np.reshape(features,(features.shape[0],features.shape[3])) #save the features in a", "listdir import numpy as np #find out how many classes", "model print(\"Creating extension model...\") extModel = Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01)))", "X_train,y_train,labels = create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels = create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle the train data", "to generate for each validation class #OUTPUTS #A model that", "each output neuron. #Labels must be the same size as", "from keras.layers import Dense from sklearn.utils import shuffle from keras.callbacks", "range(0,num_classes): labels[i][i]=1 #load all arrays into memory. #In the future,", "create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle the train data X_train,y_train = shuffle(X_train,y_train) num_classes =", "as np #check if image is a filepath if(isinstance(img,str)): if(not", "= np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return \"\" else: return self.labels[predIdx] def set_extModel(self,model):", "#find out how many classes num_classes = 0 label_names =", "y else: self.labels = labels self.num_classes = len(labels) self.min_confidence=min_confidence def", "of images to generate for each training class #val_size is", "the neural network. def __init__(self, modelpath, labels, min_confidence = 0.6):", "= img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = resnet.predict(x) import numpy as np", "classes num_classes = 0 label_names = [] if(not isdir(data_path)): print(\"Could", "isdir #create the model, if not defined if model==None: model", "#predict features = self.resnet.predict(x) prediction = self.extModel.predict(features) #get max of", "labels def get_labels(self): return self.labels def set_min_confidence(self,conf): self.min_confidence=conf def get_min_confidence(self):", "isdir(location)): print(\"could not find location: \" + location) return for", "keras.preprocessing.image import img_to_array import numpy as np #check if image", "from keras.applications.resnet50 import ResNet50 self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel = load_model(modelpath)", "as output: output.write(\"\".join([label + '\\n' for label in labels])) #train", "each image class #OUTPUT: #a npy file containing the 2048-dimensional", "import Image from os.path import exists from keras.preprocessing.image import img_to_array", "filepath, convert to PIL image img = Image.open(image) shape =", "labels = np.zeros([num_classes,num_classes]) for i in range(0,num_classes): labels[i][i]=1 #load all", "as np from keras.preprocessing.image import ImageDataGenerator from keras.applications.resnet50 import ResNet50", "feature maps and outputs #a prediction of what an image", "#training array and training labels #label array is returned as", "SVM with softmax activation. from time import time from keras.applications.resnet50", "model to be used for feature determination #label - the", "img_to_array import numpy as np #check if image is a", "that all npy files are contained #image - the path", "arr = np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr) X = np.vstack([arr for arr", "as the output layer of the neural network. def __init__(self,", "File Path\") return \"\" else: #if its a filepath, convert", "import listdir import numpy as np #find out how many", "training images #test_dir is the directory containing the validation images", "def set_labels(self,labels): self.labels = labels def get_labels(self): return self.labels def", "listdir from os.path import isdir #create the model, if not", "to fit the ResNet50 print(\"Generating feature maps for \" +", "datasets...\") X_train,y_train,labels = create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels = create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle the train", "#Appends the features of the new item to the training", "of the new item to the training set data for", "def set_extModel(self,model): self.extModel = model def get_extModel(self): return self.extModel def", "feature maps from the convolutional layers of ResNet50 using all", "is the directory containig the training images #test_dir is the", "the training set data for that label from PIL import", "model created is an SVM with softmax activation. from time", "= ResNet50(weights='imagenet',include_top=False,pooling='max') #create the data generation datagen = ImageDataGenerator() #for", "self.min_confidence def generate_features_from_directory(location,target_image_count,model=None): #generates feature maps from the convolutional layers", "epochs=50, validation_data=(X_val,y_val), callbacks = [checkpoint,early]) return extModel def add_to_train(train_dir,image,label, resnet):", "features in a numpy binary np.save(location+'/'+label+'.npy', features) def create_data_set(data_path,output_folder,save_to_file=True): #combines", "might need to do this on either a high ram", "convolutional layers #data is generated in batches of 32 import", "= 0 label_names = [] if(not isdir(data_path)): print(\"Could not find", "def add_to_train(train_dir,image,label, resnet): #INPUTS #Train_dir - the directory that all", "as a one hot encoding #label names from os.path import", "determination #label - the name of the item #Appends the", "max of predictions and return label(s) predIdx = np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence):", "set_labels(self,labels): self.labels = labels def get_labels(self): return self.labels def set_min_confidence(self,conf):", "shuffle from keras.callbacks import EarlyStopping, ModelCheckpoint #import ResNet50 without top", "open(output_dir+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n' for label in labels]))", "label in labels])) #train model print(\"Training...\") extModel.fit(X_train,y_train, batch_size=32, epochs=50, validation_data=(X_val,y_val),", "that label from PIL import Image from os.path import exists", "that takes as input a 2048-vector of feature maps and", "listdir(data_path) for f in data_contents: if(f.endswith('.npy')): num_classes +=1 label_names.append(f.split('.')[0]) if(num_classes==0):", "in listdir(location): #first check that its a directory label_path =", "another way to concatenate data arrays = [] sizes =", "i in x: y.append(i.split('\\n')[0]) self.labels = y else: self.labels =", "features = self.resnet.predict(x) prediction = self.extModel.predict(features) #get max of predictions", "PIL import Image from os.path import exists from keras.preprocessing.image import", "directory #INPUT: #directory containing NESTED DIRECTORIES of images. (Very Important)", "- the name of the item #Appends the features of", "output.write(\"\".join([label + '\\n' for label in label_names])) return X,y,label_names def", "exists if(exists(labels)): f = open(labels,'r') x = f.readlines() y =", "for i in x: y.append(i.split('\\n')[0]) self.labels = y else: self.labels", "+=1 label_names.append(f.split('.')[0]) if(num_classes==0): print(\"Could not find any data files in", "is the directory to save the trained model #train_size is", "from keras.preprocessing.image import img_to_array if(isinstance(image,str)): if(not exists(image)): print(\"Error: Invalid File", "create the features features = model.predict_generator(generator,target_image_count/32) #features = np.reshape(features,(features.shape[0],features.shape[3])) #save", "are contained #image - the path to the image being", "is 256x256 to fit the ResNet50 print(\"Generating feature maps for", "binary np.save(location+'/'+label+'.npy', features) def create_data_set(data_path,output_folder,save_to_file=True): #combines all npy files into", "x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = resnet.predict(x) import numpy as", "mode='auto') with open(output_dir+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n' for label", "from PIL import Image from keras.preprocessing.image import img_to_array import numpy", "of all different classes #Outputs: #training array and training labels", "= [] for i in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y = np.vstack([l", "as output: output.write(\"\".join([label + '\\n' for label in label_names])) return", "by ResNet50's convolutional layers #data is generated in batches of", "many classes num_classes = 0 label_names = [] if(not isdir(data_path)):", "#create the data generator #Output size is 256x256 to fit", "resnet): #INPUTS #Train_dir - the directory that all npy files", "self.labels[predIdx] def set_extModel(self,model): self.extModel = model def get_extModel(self): return self.extModel", "model, if not defined if model==None: model = ResNet50(weights='imagenet',include_top=False,pooling='max') #create", "out how many classes num_classes = 0 label_names = []", "W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks checkpoint = ModelCheckpoint(output_dir + \"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc', verbose=1,", "(Very Important) #the number of feature maps to generate for", "label in label_names])) return X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir is", "a 2048-vector of feature maps and outputs #a prediction of", "files in directory: \"+data_path) return #generate one-hot label vectors labels", "npy fils of all different classes #Outputs: #training array and", "x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = self.resnet.predict(x) prediction = self.extModel.predict(features)", "= labels def get_labels(self): return self.labels def set_min_confidence(self,conf): self.min_confidence=conf def", "exists(image)): print(\"Error: Invalid File Path\") return \"\" else: #if its", "ResNet50(weights='imagenet',include_top=False,pooling='max') #create the data generation datagen = ImageDataGenerator() #for each", "fit the ResNet50 print(\"Generating feature maps for \" + label", "output layer of the neural network. def __init__(self, modelpath, labels,", "[] for i in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y = np.vstack([l for", "names from os.path import isdir from os import listdir import", "import isdir #create the model, if not defined if model==None:", "filepath, convert to PIL image img = Image.open(img) #resize image", "each class print(\"Generating Training Set...\") generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating Testing Set...\") generate_features_from_directory(val_dir,val_size,model=resnet)", "high ram machine #or find another way to concatenate data", "else: #if its a filepath, convert to PIL image img", "all different classes #Outputs: #training array and training labels #label", "PIL image img = Image.open(img) #resize image #shape from model", "= Image.open(img) #resize image #shape from model input shape =", "the ResNet50 Network...\") resnet = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the training and", "#Train_dir - the directory that all npy files are contained", "feature maps to generate for each image class #OUTPUT: #a", "generate for each image class #OUTPUT: #a npy file containing", "labels self.num_classes = len(labels) self.min_confidence=min_confidence def predict(self,img): import os from", "import ResNet50 self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel = load_model(modelpath) if(isinstance(labels,str)): #its", "y.append(i.split('\\n')[0]) self.labels = y else: self.labels = labels self.num_classes =", "for each image class #OUTPUT: #a npy file containing the", "if(not isdir(location)): print(\"could not find location: \" + location) return", "for f in data_contents: if(f.endswith('.npy')): num_classes +=1 label_names.append(f.split('.')[0]) if(num_classes==0): print(\"Could", "npy files into one large file with their respective labels", "as np npyname = train_dir+'/'+label+'.npy' if(not exists(npyname)): np.save(npyname,features) else: fullset", "i in range(0,num_classes): labels[i][i]=1 #load all arrays into memory. #In", "self.resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features =", "if image is a filepath if(isinstance(img,str)): if(not os.path.exists(img)): print(\"Error: Invalid", "item #Appends the features of the new item to the", "generated in batches of 32 import numpy as np from", "from os import listdir from os.path import isdir #create the", "of images to generate for each validation class #OUTPUTS #A", "the 2048-dimensional feature vector #produced by ResNet50's convolutional layers #data", "keras model #labels - the labels to be associated with", "images to generate for each training class #val_size is the", "continue #create the data generator #Output size is 256x256 to", "img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = self.resnet.predict(x) prediction = self.extModel.predict(features) #get max", "same size as the output layer of the neural network.", "data_path) return data_contents = listdir(data_path) for f in data_contents: if(f.endswith('.npy')):", "keras.applications.resnet50 import ResNet50 from os import listdir from os.path import", "a filepath, convert to PIL image img = Image.open(image) shape", "self.extModel.predict(features) #get max of predictions and return label(s) predIdx =", "x: y.append(i.split('\\n')[0]) self.labels = y else: self.labels = labels self.num_classes", "the number of images to generate for each validation class", "the image being added #resnet - the resnet model to", "ResNet50 Network...\") resnet = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the training and validation", "def create_data_set(data_path,output_folder,save_to_file=True): #combines all npy files into one large file", "np.zeros([num_classes,num_classes]) for i in range(0,num_classes): labels[i][i]=1 #load all arrays into", "input shape = self.resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3]))", "= [checkpoint,early]) return extModel def add_to_train(train_dir,image,label, resnet): #INPUTS #Train_dir -", "arrays]) #load the labels into memory labelcodes = [] for", "layer print(\"Loading the ResNet50 Network...\") resnet = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the", "if(isinstance(img,str)): if(not os.path.exists(img)): print(\"Error: Invalid File Path\") return \"\" else:", "ImageDataGenerator() #for each directory in if(not isdir(location)): print(\"could not find", "from keras.regularizers import l2 from keras.layers import Dense from sklearn.utils", "data generation datagen = ImageDataGenerator() #for each directory in if(not", "def get_labels(self): return self.labels def set_min_confidence(self,conf): self.min_confidence=conf def get_min_confidence(self): return", "the path to the image being added #resnet - the", "#save the features in a numpy binary np.save(location+'/'+label+'.npy', features) def", "from keras.applications.resnet50 import ResNet50 from keras.models import Sequential from keras.optimizers", "data for that label from PIL import Image from os.path", "the name of the item #Appends the features of the", "import ResNet50 from keras.models import Sequential from keras.optimizers import SGD", "= self.resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features", "model that takes as input a 2048-vector of feature maps", "import SGD from keras.regularizers import l2 from keras.layers import Dense", "= train_dir+'/'+label+'.npy' if(not exists(npyname)): np.save(npyname,features) else: fullset = np.load(npyname) newset", "import l2 from keras.layers import Dense from sklearn.utils import shuffle", "image class #OUTPUT: #a npy file containing the 2048-dimensional feature", "return for label in listdir(location): #first check that its a", "y = np.vstack([l for l in labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y)", "to do this on either a high ram machine #or", "npy file containing the 2048-dimensional feature vector #produced by ResNet50's", "is the number of images to generate for each training", "return \"\" else: #if its a filepath, convert to PIL", "for f in data_contents: if(f.endswith('.npy')): arr = np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr)", "[] sizes = [] for f in data_contents: if(f.endswith('.npy')): arr", "= open(labels,'r') x = f.readlines() y = [] for i", "activation of each output neuron. #Labels must be the same", "feature maps for \" + label + \"...\") generator =", "f.readlines() y = [] for i in x: y.append(i.split('\\n')[0]) self.labels", "for each class print(\"Generating Training Set...\") generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating Testing Set...\")", "#INPUTS #Train_dir - the directory that all npy files are", "data arrays = [] sizes = [] for f in", "= img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = resnet.predict(x) import", "without top layer print(\"Loading the ResNet50 Network...\") resnet = ResNet50(weights='imagenet',include_top=False,pooling='max')", "len(labels) self.min_confidence=min_confidence def predict(self,img): import os from PIL import Image", "#load the labels into memory labelcodes = [] for i", "be. #The labels file is also placed in this directory", "np from keras.preprocessing.image import ImageDataGenerator from keras.applications.resnet50 import ResNet50 from", "generator #Output size is 256x256 to fit the ResNet50 print(\"Generating", "set data for that label from PIL import Image from", "validation datasets for each class print(\"Generating Training Set...\") generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating", "to the training set data for that label from PIL", "= img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = self.resnet.predict(x) prediction", "features of the new item to the training set data", "from keras.models import load_model from keras.applications.resnet50 import ResNet50 self.resnet =", "self.min_confidence=min_confidence def predict(self,img): import os from PIL import Image from", "Image.open(img) #resize image #shape from model input shape = self.resnet.input_shape", "not defined if model==None: model = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the data", "import numpy as np #check if image is a filepath", "is generated in batches of 32 import numpy as np", "for label in labels])) #train model print(\"Training...\") extModel.fit(X_train,y_train, batch_size=32, epochs=50,", "import shuffle from keras.callbacks import EarlyStopping, ModelCheckpoint #import ResNet50 without", "= 0.6): from keras.models import load_model from keras.applications.resnet50 import ResNet50", "PIL import Image from keras.preprocessing.image import img_to_array import numpy as", "- the path to the image being added #resnet -", "print(\"Generating Training Set...\") generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating Testing Set...\") generate_features_from_directory(val_dir,val_size,model=resnet) #create the", "future, might need to do this on either a high", "prediction of what an image with those features might be.", "what an image with those features might be. #The labels", "#for each directory in if(not isdir(location)): print(\"could not find location:", "os import listdir from os.path import isdir #create the model,", "#predict features = resnet.predict(x) import numpy as np npyname =", "Network...\") resnet = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the training and validation datasets", "keras.models import Sequential from keras.optimizers import SGD from keras.regularizers import", "underlying keras model #labels - the labels to be associated", "for label in listdir(location): #first check that its a directory", "labels[i][i]=1 #load all arrays into memory. #In the future, might", "the labels to be associated with the activation of each", "SGD from keras.regularizers import l2 from keras.layers import Dense from", "in labels])) #train model print(\"Training...\") extModel.fit(X_train,y_train, batch_size=32, epochs=50, validation_data=(X_val,y_val), callbacks", "self.extModel = load_model(modelpath) if(isinstance(labels,str)): #its a file path from os.path", "shape = self.resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict", "for l in labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with open(output_folder+\"/labels.txt\",\"w\") as", "resnet model to be used for feature determination #label -", "in x: y.append(i.split('\\n')[0]) self.labels = y else: self.labels = labels", "images to generate for each validation class #OUTPUTS #A model", "with the activation of each output neuron. #Labels must be", "with their respective labels #INPUTS: #a directory containing npy fils", "(224,224), batch_size = 32, class_mode=None) #use ResNet50 to create the", "return self.labels[predIdx] def set_extModel(self,model): self.extModel = model def get_extModel(self): return", "class_mode=None) #use ResNet50 to create the features features = model.predict_generator(generator,target_image_count/32)", "is an SVM with softmax activation. from time import time", "model...\") extModel = Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks checkpoint", "from model input shape = self.resnet.input_shape imgr = img.resize(shape[1:3]) x", "hot encoding #label names from os.path import isdir from os", "#or find another way to concatenate data arrays = []", "array and training labels #label array is returned as a", "- the directory that all npy files are contained #image", "min_confidence = 0.6): from keras.models import load_model from keras.applications.resnet50 import", "resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features =", "is a filepath if(isinstance(img,str)): if(not os.path.exists(img)): print(\"Error: Invalid File Path\")", "arr in arrays]) #load the labels into memory labelcodes =", "#shuffle the train data X_train,y_train = shuffle(X_train,y_train) num_classes = len(labels)", "+ location) return for label in listdir(location): #first check that", "load_model from keras.applications.resnet50 import ResNet50 self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel =", "datagen.flow_from_directory( label_path, target_size = (224,224), batch_size = 32, class_mode=None) #use", "be associated with the activation of each output neuron. #Labels", "used for feature determination #label - the name of the", "data X_train,y_train = shuffle(X_train,y_train) num_classes = len(labels) #create the extension", "dataset print(\"Combining datasets...\") X_train,y_train,labels = create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels = create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle", "import Dense from sklearn.utils import shuffle from keras.callbacks import EarlyStopping,", "label_names])) return X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir is the directory", "print(\"Error: Invalid File Path\") return \"\" else: #if its a", "Set...\") generate_features_from_directory(val_dir,val_size,model=resnet) #create the combined dataset print(\"Combining datasets...\") X_train,y_train,labels =", "for each validation class #OUTPUTS #A model that takes as", "the train data X_train,y_train = shuffle(X_train,y_train) num_classes = len(labels) #create", "+ \"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1) early =", "extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks checkpoint = ModelCheckpoint(output_dir + \"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc', verbose=1, save_best_only=True,", "f = open(labels,'r') x = f.readlines() y = [] for", "#Labels must be the same size as the output layer", "self.labels = y else: self.labels = labels self.num_classes = len(labels)", "must be the same size as the output layer of", "labelcodes = [] for i in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y =", "set_min_confidence(self,conf): self.min_confidence=conf def get_min_confidence(self): return self.min_confidence def generate_features_from_directory(location,target_image_count,model=None): #generates feature", "img = Image.open(image) shape = resnet.input_shape imgr = img.resize(shape[1:3]) x", "new item to the training set data for that label", "features = resnet.predict(x) import numpy as np npyname = train_dir+'/'+label+'.npy'", "to concatenate data arrays = [] sizes = [] for", "+ \"...\") generator = datagen.flow_from_directory( label_path, target_size = (224,224), batch_size", "training class #val_size is the number of images to generate", "print(\"Training...\") extModel.fit(X_train,y_train, batch_size=32, epochs=50, validation_data=(X_val,y_val), callbacks = [checkpoint,early]) return extModel", "directory containing the validation images #output_dir is the directory to", "of each output neuron. #Labels must be the same size", "os.path import isdir from os import listdir import numpy as", "np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with open(output_folder+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n' for", "do this on either a high ram machine #or find", "isdir from os import listdir import numpy as np #find", "input a 2048-vector of feature maps and outputs #a prediction", "keras.layers import Dense from sklearn.utils import shuffle from keras.callbacks import", "def generate_features_from_directory(location,target_image_count,model=None): #generates feature maps from the convolutional layers of", "all npy files into one large file with their respective", "data generator #Output size is 256x256 to fit the ResNet50", "img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = resnet.predict(x) import numpy as np npyname", "class print(\"Generating Training Set...\") generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating Testing Set...\") generate_features_from_directory(val_dir,val_size,model=resnet) #create", "#create the model, if not defined if model==None: model =", "def get_extModel(self): return self.extModel def set_labels(self,labels): self.labels = labels def", "model==None: model = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the data generation datagen =", "into memory labelcodes = [] for i in range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i]))", "#resnet - the resnet model to be used for feature", "return \"\" else: return self.labels[predIdx] def set_extModel(self,model): self.extModel = model", "labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with open(output_folder+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label +", "#OUTPUT: #a npy file containing the 2048-dimensional feature vector #produced", "#if its a filepath, convert to PIL image img =", "def get_min_confidence(self): return self.min_confidence def generate_features_from_directory(location,target_image_count,model=None): #generates feature maps from", "shuffle(X_train,y_train) num_classes = len(labels) #create the extension model print(\"Creating extension", "callbacks = [checkpoint,early]) return extModel def add_to_train(train_dir,image,label, resnet): #INPUTS #Train_dir", "= np.vstack([l for l in labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with", "defined if model==None: model = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the data generation", "label_path, target_size = (224,224), batch_size = 32, class_mode=None) #use ResNet50", "#train_size is the number of images to generate for each", "model print(\"Training...\") extModel.fit(X_train,y_train, batch_size=32, epochs=50, validation_data=(X_val,y_val), callbacks = [checkpoint,early]) return", "add_to_train(train_dir,image,label, resnet): #INPUTS #Train_dir - the directory that all npy", "the training and validation datasets for each class print(\"Generating Training", "checkpoint = ModelCheckpoint(output_dir + \"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto',", "the training images #test_dir is the directory containing the validation", "else: self.labels = labels self.num_classes = len(labels) self.min_confidence=min_confidence def predict(self,img):", "np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return \"\" else: return self.labels[predIdx] def set_extModel(self,model): self.extModel", "labels to be associated with the activation of each output", "label + \"...\") generator = datagen.flow_from_directory( label_path, target_size = (224,224),", "training labels #label array is returned as a one hot", "isdir(data_path)): print(\"Could not find directory: \"+ data_path) return data_contents =", "#train_dir is the directory containig the training images #test_dir is", "#callbacks checkpoint = ModelCheckpoint(output_dir + \"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False,", "label vectors labels = np.zeros([num_classes,num_classes]) for i in range(0,num_classes): labels[i][i]=1", "import isdir from os import listdir import numpy as np", "sizes = [] for f in data_contents: if(f.endswith('.npy')): arr =", "def __init__(self, modelpath, labels, min_confidence = 0.6): from keras.models import", "#first check that its a directory label_path = location+'/'+label if(not", "prediction = self.extModel.predict(features) #get max of predictions and return label(s)", "self.labels = labels def get_labels(self): return self.labels def set_min_confidence(self,conf): self.min_confidence=conf", "for \" + label + \"...\") generator = datagen.flow_from_directory( label_path,", "label_names = [] if(not isdir(data_path)): print(\"Could not find directory: \"+", "item to the training set data for that label from", "of the neural network. def __init__(self, modelpath, labels, min_confidence =", "#output_dir is the directory to save the trained model #train_size", "self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel = load_model(modelpath) if(isinstance(labels,str)): #its a file", "#directory containing NESTED DIRECTORIES of images. (Very Important) #the number", "[] for i in x: y.append(i.split('\\n')[0]) self.labels = y else:", "Image from keras.preprocessing.image import img_to_array import numpy as np #check", "#A model that takes as input a 2048-vector of feature", "np.save(location+'/'+label+'.npy', features) def create_data_set(data_path,output_folder,save_to_file=True): #combines all npy files into one", "get_min_confidence(self): return self.min_confidence def generate_features_from_directory(location,target_image_count,model=None): #generates feature maps from the", "batch_size=32, epochs=50, validation_data=(X_val,y_val), callbacks = [checkpoint,early]) return extModel def add_to_train(train_dir,image,label,", "= location+'/'+label if(not isdir(label_path)): continue #create the data generator #Output", "train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir is the directory containig the training images", "self.labels = labels self.num_classes = len(labels) self.min_confidence=min_confidence def predict(self,img): import", "activation. from time import time from keras.applications.resnet50 import ResNet50 from", "in label_names])) return X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir is the", "if(isinstance(image,str)): if(not exists(image)): print(\"Error: Invalid File Path\") return \"\" else:", "import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.applications.resnet50", "machine #or find another way to concatenate data arrays =", "directory label_path = location+'/'+label if(not isdir(label_path)): continue #create the data", "maps for \" + label + \"...\") generator = datagen.flow_from_directory(", "of what an image with those features might be. #The", "from the directory #INPUT: #directory containing NESTED DIRECTORIES of images.", "time from keras.applications.resnet50 import ResNet50 from keras.models import Sequential from", "np #check if image is a filepath if(isinstance(img,str)): if(not os.path.exists(img)):", "isdir(label_path)): continue #create the data generator #Output size is 256x256", "this directory #The model created is an SVM with softmax", "top layer print(\"Loading the ResNet50 Network...\") resnet = ResNet50(weights='imagenet',include_top=False,pooling='max') #create", "Training Set...\") generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating Testing Set...\") generate_features_from_directory(val_dir,val_size,model=resnet) #create the combined", "data_contents = listdir(data_path) for f in data_contents: if(f.endswith('.npy')): num_classes +=1", "Set...\") generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating Testing Set...\") generate_features_from_directory(val_dir,val_size,model=resnet) #create the combined dataset", "location+'/'+label if(not isdir(label_path)): continue #create the data generator #Output size", "labels])) #train model print(\"Training...\") extModel.fit(X_train,y_train, batch_size=32, epochs=50, validation_data=(X_val,y_val), callbacks =", "the model, if not defined if model==None: model = ResNet50(weights='imagenet',include_top=False,pooling='max')", "the item #Appends the features of the new item to", "from sklearn.utils import shuffle from keras.callbacks import EarlyStopping, ModelCheckpoint #import", "from keras.optimizers import SGD from keras.regularizers import l2 from keras.layers", "DIRECTORIES of images. (Very Important) #the number of feature maps", "is the number of images to generate for each validation", "ram machine #or find another way to concatenate data arrays", "#import ResNet50 without top layer print(\"Loading the ResNet50 Network...\") resnet", "path from os.path import exists if(exists(labels)): f = open(labels,'r') x", "Testing Set...\") generate_features_from_directory(val_dir,val_size,model=resnet) #create the combined dataset print(\"Combining datasets...\") X_train,y_train,labels", "in range(0,num_classes): labels[i][i]=1 #load all arrays into memory. #In the", "Image.open(image) shape = resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3]))", "if(exists(labels)): f = open(labels,'r') x = f.readlines() y = []", "of images. (Very Important) #the number of feature maps to", "vectors labels = np.zeros([num_classes,num_classes]) for i in range(0,num_classes): labels[i][i]=1 #load", "\"...\") generator = datagen.flow_from_directory( label_path, target_size = (224,224), batch_size =", "def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir is the directory containig the training", "Image from os.path import exists from keras.preprocessing.image import img_to_array if(isinstance(image,str)):", "f in data_contents: if(f.endswith('.npy')): num_classes +=1 label_names.append(f.split('.')[0]) if(num_classes==0): print(\"Could not", "img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = self.resnet.predict(x) prediction =", "extModel = Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks checkpoint =", "np npyname = train_dir+'/'+label+'.npy' if(not exists(npyname)): np.save(npyname,features) else: fullset =", "import img_to_array if(isinstance(image,str)): if(not exists(image)): print(\"Error: Invalid File Path\") return", "= f.readlines() y = [] for i in x: y.append(i.split('\\n')[0])", "contained #image - the path to the image being added", "predIdx = np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return \"\" else: return self.labels[predIdx] def", "import EarlyStopping, ModelCheckpoint #import ResNet50 without top layer print(\"Loading the", "2048-vector of feature maps and outputs #a prediction of what", "#load all arrays into memory. #In the future, might need", "ImageDataGenerator from keras.applications.resnet50 import ResNet50 from os import listdir from", "Path\") return \"\" else: #if its a filepath, convert to", "x = f.readlines() y = [] for i in x:", "\" + label + \"...\") generator = datagen.flow_from_directory( label_path, target_size", "each validation class #OUTPUTS #A model that takes as input", "= labels self.num_classes = len(labels) self.min_confidence=min_confidence def predict(self,img): import os", "all #images from the directory #INPUT: #directory containing NESTED DIRECTORIES", "its a filepath, convert to PIL image img = Image.open(img)", "if not defined if model==None: model = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the", "not find any data files in directory: \"+data_path) return #generate", "in data_contents: if(f.endswith('.npy')): arr = np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr) X =", "generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating Testing Set...\") generate_features_from_directory(val_dir,val_size,model=resnet) #create the combined dataset print(\"Combining", "print(\"Combining datasets...\") X_train,y_train,labels = create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels = create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle the", "= (224,224), batch_size = 32, class_mode=None) #use ResNet50 to create", "for label in label_names])) return X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir", "label in listdir(location): #first check that its a directory label_path", "and outputs #a prediction of what an image with those", "[] for f in data_contents: if(f.endswith('.npy')): arr = np.load(data_path+'/'+f) sizes.append(arr.shape[0])", "images #test_dir is the directory containing the validation images #output_dir", "time import time from keras.applications.resnet50 import ResNet50 from keras.models import", "arrays = [] sizes = [] for f in data_contents:", "data_contents: if(f.endswith('.npy')): arr = np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr) X = np.vstack([arr", "concatenate data arrays = [] sizes = [] for f", "with open(output_dir+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n' for label in", "the data generator #Output size is 256x256 to fit the", "batch_size = 32, class_mode=None) #use ResNet50 to create the features", "period=1) early = EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode='auto') with open(output_dir+\"/labels.txt\",\"w\")", "files are contained #image - the path to the image", "if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with open(output_folder+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n'", "npyname = train_dir+'/'+label+'.npy' if(not exists(npyname)): np.save(npyname,features) else: fullset = np.load(npyname)", "a directory label_path = location+'/'+label if(not isdir(label_path)): continue #create the", "to create the features features = model.predict_generator(generator,target_image_count/32) #features = np.reshape(features,(features.shape[0],features.shape[3]))", "save the trained model #train_size is the number of images", "keras.applications.resnet50 import ResNet50 from keras.models import Sequential from keras.optimizers import", "f in data_contents: if(f.endswith('.npy')): arr = np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr) X", "image with those features might be. #The labels file is", "activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks checkpoint = ModelCheckpoint(output_dir + \"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc',", "training set data for that label from PIL import Image", "os.path.exists(img)): print(\"Error: Invalid File Path\") return \"\" else: #if its", "import exists if(exists(labels)): f = open(labels,'r') x = f.readlines() y", "+ '\\n' for label in labels])) #train model print(\"Training...\") extModel.fit(X_train,y_train,", "#get max of predictions and return label(s) predIdx = np.argmax(prediction)", "'\\n' for label in labels])) #train model print(\"Training...\") extModel.fit(X_train,y_train, batch_size=32,", "name of the item #Appends the features of the new", "is the directory containing the validation images #output_dir is the", "extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks checkpoint = ModelCheckpoint(output_dir + \"/extModel\"+str(int(time()))+\".h5\",", "shape = resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict", "X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir is the directory containig the", "the ResNet50 print(\"Generating feature maps for \" + label +", "number of images to generate for each training class #val_size", "= np.zeros([num_classes,num_classes]) for i in range(0,num_classes): labels[i][i]=1 #load all arrays", "= create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle the train data X_train,y_train = shuffle(X_train,y_train) num_classes", "set_extModel(self,model): self.extModel = model def get_extModel(self): return self.extModel def set_labels(self,labels):", "the directory to save the trained model #train_size is the", "len(labels) #create the extension model print(\"Creating extension model...\") extModel =", "get_labels(self): return self.labels def set_min_confidence(self,conf): self.min_confidence=conf def get_min_confidence(self): return self.min_confidence", "find another way to concatenate data arrays = [] sizes", "print(\"Loading the ResNet50 Network...\") resnet = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the training", "- the underlying keras model #labels - the labels to", "- the resnet model to be used for feature determination", "#create the data generation datagen = ImageDataGenerator() #for each directory", "in data_contents: if(f.endswith('.npy')): num_classes +=1 label_names.append(f.split('.')[0]) if(num_classes==0): print(\"Could not find", "ModelCheckpoint #import ResNet50 without top layer print(\"Loading the ResNet50 Network...\")", "keras.callbacks import EarlyStopping, ModelCheckpoint #import ResNet50 without top layer print(\"Loading", "and return label(s) predIdx = np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return \"\" else:", "returned as a one hot encoding #label names from os.path", "the data generation datagen = ImageDataGenerator() #for each directory in", "the future, might need to do this on either a", "a file path from os.path import exists if(exists(labels)): f =", "added #resnet - the resnet model to be used for", "of 32 import numpy as np from keras.preprocessing.image import ImageDataGenerator", "from the convolutional layers of ResNet50 using all #images from", "np.reshape(features,(features.shape[0],features.shape[3])) #save the features in a numpy binary np.save(location+'/'+label+'.npy', features)", "containing npy fils of all different classes #Outputs: #training array", "\"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1) early = EarlyStopping(monitor='val_acc',", "def set_min_confidence(self,conf): self.min_confidence=conf def get_min_confidence(self): return self.min_confidence def generate_features_from_directory(location,target_image_count,model=None): #generates", "mode='auto', period=1) early = EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode='auto') with", "#model - the underlying keras model #labels - the labels", "from os.path import exists if(exists(labels)): f = open(labels,'r') x =", "using all #images from the directory #INPUT: #directory containing NESTED", "np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr) X = np.vstack([arr for arr in arrays])", "keras.optimizers import SGD from keras.regularizers import l2 from keras.layers import", "to save the trained model #train_size is the number of", "in labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with open(output_folder+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label", "keras.applications.resnet50 import ResNet50 self.resnet = ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel = load_model(modelpath) if(isinstance(labels,str)):", "np.save(output_folder+'/label_codes.npy',y) with open(output_folder+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n' for label", "labels #label array is returned as a one hot encoding", "label_names.append(f.split('.')[0]) if(num_classes==0): print(\"Could not find any data files in directory:", "batches of 32 import numpy as np from keras.preprocessing.image import", "exists from keras.preprocessing.image import img_to_array if(isinstance(image,str)): if(not exists(image)): print(\"Error: Invalid", "an SVM with softmax activation. from time import time from", "keras.regularizers import l2 from keras.layers import Dense from sklearn.utils import", "model def get_extModel(self): return self.extModel def set_labels(self,labels): self.labels = labels", "= ModelCheckpoint(output_dir + \"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)", "for that label from PIL import Image from os.path import", "= datagen.flow_from_directory( label_path, target_size = (224,224), batch_size = 32, class_mode=None)", "open(output_folder+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n' for label in label_names]))", "os from PIL import Image from keras.preprocessing.image import img_to_array import", "#OUTPUTS #A model that takes as input a 2048-vector of", "directory to save the trained model #train_size is the number", "sklearn.utils import shuffle from keras.callbacks import EarlyStopping, ModelCheckpoint #import ResNet50", "EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode='auto') with open(output_dir+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label", "verbose=1, mode='auto') with open(output_dir+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n' for", "a high ram machine #or find another way to concatenate", "convert to PIL image img = Image.open(img) #resize image #shape", "#data is generated in batches of 32 import numpy as", "modelpath, labels, min_confidence = 0.6): from keras.models import load_model from", "might be. #The labels file is also placed in this", "location: \" + location) return for label in listdir(location): #first", "labels into memory labelcodes = [] for i in range(0,num_classes):", "output: output.write(\"\".join([label + '\\n' for label in label_names])) return X,y,label_names", "if(not exists(npyname)): np.save(npyname,features) else: fullset = np.load(npyname) newset = np.append(fullset,features,axis=0)", "of feature maps to generate for each image class #OUTPUT:", "any data files in directory: \"+data_path) return #generate one-hot label", "file with their respective labels #INPUTS: #a directory containing npy", "#label array is returned as a one hot encoding #label", "img_to_array if(isinstance(image,str)): if(not exists(image)): print(\"Error: Invalid File Path\") return \"\"", "save_best_only=True, save_weights_only=False, mode='auto', period=1) early = EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1,", "#images from the directory #INPUT: #directory containing NESTED DIRECTORIES of", "256x256 to fit the ResNet50 print(\"Generating feature maps for \"", "number of images to generate for each validation class #OUTPUTS", "in directory: \"+data_path) return #generate one-hot label vectors labels =", "of the item #Appends the features of the new item", "#In the future, might need to do this on either", "be used for feature determination #label - the name of", "a filepath, convert to PIL image img = Image.open(img) #resize", "else: return self.labels[predIdx] def set_extModel(self,model): self.extModel = model def get_extModel(self):", "ResNet50 using all #images from the directory #INPUT: #directory containing", "if(not isdir(label_path)): continue #create the data generator #Output size is", "label from PIL import Image from os.path import exists from", "self.labels def set_min_confidence(self,conf): self.min_confidence=conf def get_min_confidence(self): return self.min_confidence def generate_features_from_directory(location,target_image_count,model=None):", "#INPUTS: #train_dir is the directory containig the training images #test_dir", "ResNet50(weights='imagenet',include_top=False,pooling='max') #create the training and validation datasets for each class", "#create the combined dataset print(\"Combining datasets...\") X_train,y_train,labels = create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels", "directory: \"+data_path) return #generate one-hot label vectors labels = np.zeros([num_classes,num_classes])", "validation_data=(X_val,y_val), callbacks = [checkpoint,early]) return extModel def add_to_train(train_dir,image,label, resnet): #INPUTS", "the labels into memory labelcodes = [] for i in", "be the same size as the output layer of the", "find any data files in directory: \"+data_path) return #generate one-hot", "num_classes = 0 label_names = [] if(not isdir(data_path)): print(\"Could not", "in arrays]) #load the labels into memory labelcodes = []", "this on either a high ram machine #or find another", "its a filepath, convert to PIL image img = Image.open(image)", "numpy as np #find out how many classes num_classes =", "feature vector #produced by ResNet50's convolutional layers #data is generated", "the resnet model to be used for feature determination #label", "32 import numpy as np from keras.preprocessing.image import ImageDataGenerator from", "print(\"Could not find directory: \"+ data_path) return data_contents = listdir(data_path)", "datasets for each class print(\"Generating Training Set...\") generate_features_from_directory(train_dir,train_size,model=resnet) print(\"Generating Testing", "os.path import exists from keras.preprocessing.image import img_to_array if(isinstance(image,str)): if(not exists(image)):", "ResNet50 print(\"Generating feature maps for \" + label + \"...\")", "X = np.vstack([arr for arr in arrays]) #load the labels", "each directory in if(not isdir(location)): print(\"could not find location: \"", "#Class Attributes: #model - the underlying keras model #labels -", "from keras.preprocessing.image import img_to_array import numpy as np #check if", "train data X_train,y_train = shuffle(X_train,y_train) num_classes = len(labels) #create the", "print(\"Generating Testing Set...\") generate_features_from_directory(val_dir,val_size,model=resnet) #create the combined dataset print(\"Combining datasets...\")", "number of feature maps to generate for each image class", "size is 256x256 to fit the ResNet50 print(\"Generating feature maps", "a numpy binary np.save(location+'/'+label+'.npy', features) def create_data_set(data_path,output_folder,save_to_file=True): #combines all npy", "the activation of each output neuron. #Labels must be the", "containing the validation images #output_dir is the directory to save", "np.vstack([l for l in labelcodes]) if(save_to_file): np.save(output_folder+'/data_set.npy',X) np.save(output_folder+'/label_codes.npy',y) with open(output_folder+\"/labels.txt\",\"w\")", "all arrays into memory. #In the future, might need to", "os.path import isdir #create the model, if not defined if", "output: output.write(\"\".join([label + '\\n' for label in labels])) #train model", "os import listdir import numpy as np #find out how", "maps from the convolutional layers of ResNet50 using all #images", "#val_size is the number of images to generate for each", "#Outputs: #training array and training labels #label array is returned", "in a numpy binary np.save(location+'/'+label+'.npy', features) def create_data_set(data_path,output_folder,save_to_file=True): #combines all", "return self.labels def set_min_confidence(self,conf): self.min_confidence=conf def get_min_confidence(self): return self.min_confidence def", "a filepath if(isinstance(img,str)): if(not os.path.exists(img)): print(\"Error: Invalid File Path\") return", "containing NESTED DIRECTORIES of images. (Very Important) #the number of", "num_classes +=1 label_names.append(f.split('.')[0]) if(num_classes==0): print(\"Could not find any data files", "= create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels = create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle the train data X_train,y_train", "\" + location) return for label in listdir(location): #first check", "to be used for feature determination #label - the name", "load_model(modelpath) if(isinstance(labels,str)): #its a file path from os.path import exists", "directory containig the training images #test_dir is the directory containing", "not find location: \" + location) return for label in", "if(num_classes==0): print(\"Could not find any data files in directory: \"+data_path)", "placed in this directory #The model created is an SVM", "= ResNet50(include_top=False,weights='imagenet',pooling='max',input_shape=(224,224,3)) self.extModel = load_model(modelpath) if(isinstance(labels,str)): #its a file path", "combined dataset print(\"Combining datasets...\") X_train,y_train,labels = create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels = create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True)", "a one hot encoding #label names from os.path import isdir", "get_extModel(self): return self.extModel def set_labels(self,labels): self.labels = labels def get_labels(self):", "from keras.models import Sequential from keras.optimizers import SGD from keras.regularizers", "\"+data_path) return #generate one-hot label vectors labels = np.zeros([num_classes,num_classes]) for", "one-hot label vectors labels = np.zeros([num_classes,num_classes]) for i in range(0,num_classes):", "PIL image img = Image.open(image) shape = resnet.input_shape imgr =", "self.extModel = model def get_extModel(self): return self.extModel def set_labels(self,labels): self.labels", "convolutional layers of ResNet50 using all #images from the directory", "the validation images #output_dir is the directory to save the", "X_val,y_val,labels = create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle the train data X_train,y_train = shuffle(X_train,y_train)", "#create the training and validation datasets for each class print(\"Generating", "the output layer of the neural network. def __init__(self, modelpath,", "0.6): from keras.models import load_model from keras.applications.resnet50 import ResNet50 self.resnet", "Attributes: #model - the underlying keras model #labels - the", "print(\"Generating feature maps for \" + label + \"...\") generator", "[] if(not isdir(data_path)): print(\"Could not find directory: \"+ data_path) return", "the directory containing the validation images #output_dir is the directory", "open(labels,'r') x = f.readlines() y = [] for i in", "features) def create_data_set(data_path,output_folder,save_to_file=True): #combines all npy files into one large", "patience=10, verbose=1, mode='auto') with open(output_dir+\"/labels.txt\",\"w\") as output: output.write(\"\".join([label + '\\n'", "model #train_size is the number of images to generate for", "of feature maps and outputs #a prediction of what an", "self.min_confidence=conf def get_min_confidence(self): return self.min_confidence def generate_features_from_directory(location,target_image_count,model=None): #generates feature maps", "to the image being added #resnet - the resnet model", "size as the output layer of the neural network. def", "[checkpoint,early]) return extModel def add_to_train(train_dir,image,label, resnet): #INPUTS #Train_dir - the", "= y else: self.labels = labels self.num_classes = len(labels) self.min_confidence=min_confidence", "Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks checkpoint = ModelCheckpoint(output_dir +", "from os.path import exists from keras.preprocessing.image import img_to_array if(isinstance(image,str)): if(not", "listdir(location): #first check that its a directory label_path = location+'/'+label", "the same size as the output layer of the neural", "Invalid File Path\") return \"\" else: #if its a filepath,", "- the labels to be associated with the activation of", "find directory: \"+ data_path) return data_contents = listdir(data_path) for f", "the trained model #train_size is the number of images to", "the features in a numpy binary np.save(location+'/'+label+'.npy', features) def create_data_set(data_path,output_folder,save_to_file=True):", "= resnet.input_shape imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features", "maps to generate for each image class #OUTPUT: #a npy", "if model==None: model = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the data generation datagen", "check that its a directory label_path = location+'/'+label if(not isdir(label_path)):", "+ '\\n' for label in label_names])) return X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir):", "data files in directory: \"+data_path) return #generate one-hot label vectors", "self.extModel def set_labels(self,labels): self.labels = labels def get_labels(self): return self.labels", "extModel def add_to_train(train_dir,image,label, resnet): #INPUTS #Train_dir - the directory that", "to PIL image img = Image.open(image) shape = resnet.input_shape imgr", "ResNet50 to create the features features = model.predict_generator(generator,target_image_count/32) #features =", "#image - the path to the image being added #resnet", "2048-dimensional feature vector #produced by ResNet50's convolutional layers #data is", "extension model...\") extModel = Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax', W_regularizer=l2(0.01))) extModel.compile(loss='hinge',optimizer=SGD(lr=0.01,momentum=0.9),metrics=[\"accuracy\"]) #callbacks", "image #shape from model input shape = self.resnet.input_shape imgr =", "= ImageDataGenerator() #for each directory in if(not isdir(location)): print(\"could not", "#labels - the labels to be associated with the activation", "if(prediction[0,predIdx]<self.min_confidence): return \"\" else: return self.labels[predIdx] def set_extModel(self,model): self.extModel =", "= model def get_extModel(self): return self.extModel def set_labels(self,labels): self.labels =", "associated with the activation of each output neuron. #Labels must", "directory that all npy files are contained #image - the", "self.resnet.predict(x) prediction = self.extModel.predict(features) #get max of predictions and return", "for arr in arrays]) #load the labels into memory labelcodes", "#use ResNet50 to create the features features = model.predict_generator(generator,target_image_count/32) #features", "outputs #a prediction of what an image with those features", "datagen = ImageDataGenerator() #for each directory in if(not isdir(location)): print(\"could", "the directory that all npy files are contained #image -", "#shape from model input shape = self.resnet.input_shape imgr = img.resize(shape[1:3])", "each training class #val_size is the number of images to", "class #OUTPUTS #A model that takes as input a 2048-vector", "import Sequential from keras.optimizers import SGD from keras.regularizers import l2", "labels, min_confidence = 0.6): from keras.models import load_model from keras.applications.resnet50", "the new item to the training set data for that", "predict(self,img): import os from PIL import Image from keras.preprocessing.image import", "with those features might be. #The labels file is also", "the number of images to generate for each training class", "those features might be. #The labels file is also placed", "return label(s) predIdx = np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return \"\" else: return", "one large file with their respective labels #INPUTS: #a directory", "from keras.callbacks import EarlyStopping, ModelCheckpoint #import ResNet50 without top layer", "for feature determination #label - the name of the item", "of predictions and return label(s) predIdx = np.argmax(prediction) if(prediction[0,predIdx]<self.min_confidence): return", "the directory #INPUT: #directory containing NESTED DIRECTORIES of images. (Very", "extension model print(\"Creating extension model...\") extModel = Sequential() extModel.add(Dense(num_classes,input_shape=(2048,), activation='softmax',", "range(0,num_classes): labelcodes.append(np.vstack([labels[i]]*sizes[i])) y = np.vstack([l for l in labelcodes]) if(save_to_file):", "the extension model print(\"Creating extension model...\") extModel = Sequential() extModel.add(Dense(num_classes,input_shape=(2048,),", "location) return for label in listdir(location): #first check that its", "imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = resnet.predict(x)", "network. def __init__(self, modelpath, labels, min_confidence = 0.6): from keras.models", "all npy files are contained #image - the path to", "model #labels - the labels to be associated with the", "return X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS: #train_dir is the directory containig", "also placed in this directory #The model created is an", "#features = np.reshape(features,(features.shape[0],features.shape[3])) #save the features in a numpy binary", "= len(labels) self.min_confidence=min_confidence def predict(self,img): import os from PIL import", "keras.preprocessing.image import img_to_array if(isinstance(image,str)): if(not exists(image)): print(\"Error: Invalid File Path\")", "labels file is also placed in this directory #The model", "early = EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode='auto') with open(output_dir+\"/labels.txt\",\"w\") as", "either a high ram machine #or find another way to", "data_contents: if(f.endswith('.npy')): num_classes +=1 label_names.append(f.split('.')[0]) if(num_classes==0): print(\"Could not find any", "= ResNet50(weights='imagenet',include_top=False,pooling='max') #create the training and validation datasets for each", "resnet = ResNet50(weights='imagenet',include_top=False,pooling='max') #create the training and validation datasets for", "Important) #the number of feature maps to generate for each", "import ImageDataGenerator from keras.applications.resnet50 import ResNet50 from os import listdir", "from os.path import isdir #create the model, if not defined", "= [] for i in x: y.append(i.split('\\n')[0]) self.labels = y", "directory containing npy fils of all different classes #Outputs: #training", "= Image.open(image) shape = resnet.input_shape imgr = img.resize(shape[1:3]) x =", "= EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode='auto') with open(output_dir+\"/labels.txt\",\"w\") as output:", "the underlying keras model #labels - the labels to be", "if(not os.path.exists(img)): print(\"Error: Invalid File Path\") return \"\" else: #if", "NESTED DIRECTORIES of images. (Very Important) #the number of feature", "different classes #Outputs: #training array and training labels #label array", "#generate one-hot label vectors labels = np.zeros([num_classes,num_classes]) for i in", "for i in range(0,num_classes): labels[i][i]=1 #load all arrays into memory.", "the combined dataset print(\"Combining datasets...\") X_train,y_train,labels = create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels =", "import os from PIL import Image from keras.preprocessing.image import img_to_array", "y = [] for i in x: y.append(i.split('\\n')[0]) self.labels =", "from os import listdir import numpy as np #find out", "arrays.append(arr) X = np.vstack([arr for arr in arrays]) #load the", "is also placed in this directory #The model created is", "\"\" else: #if its a filepath, convert to PIL image", "directory: \"+ data_path) return data_contents = listdir(data_path) for f in", "trained model #train_size is the number of images to generate", "being added #resnet - the resnet model to be used", "resnet.predict(x) import numpy as np npyname = train_dir+'/'+label+'.npy' if(not exists(npyname)):", "return data_contents = listdir(data_path) for f in data_contents: if(f.endswith('.npy')): num_classes", "#label names from os.path import isdir from os import listdir", "to generate for each training class #val_size is the number", "= 32, class_mode=None) #use ResNet50 to create the features features", "ResNet50 from keras.models import Sequential from keras.optimizers import SGD from", "model.predict_generator(generator,target_image_count/32) #features = np.reshape(features,(features.shape[0],features.shape[3])) #save the features in a numpy", "neural network. def __init__(self, modelpath, labels, min_confidence = 0.6): from", "#produced by ResNet50's convolutional layers #data is generated in batches", "arrays into memory. #In the future, might need to do", "def predict(self,img): import os from PIL import Image from keras.preprocessing.image", "if(f.endswith('.npy')): arr = np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr) X = np.vstack([arr for", "generator = datagen.flow_from_directory( label_path, target_size = (224,224), batch_size = 32,", "\"+ data_path) return data_contents = listdir(data_path) for f in data_contents:", "= [] sizes = [] for f in data_contents: if(f.endswith('.npy')):", "X_train,y_train = shuffle(X_train,y_train) num_classes = len(labels) #create the extension model", "in this directory #The model created is an SVM with", "feature determination #label - the name of the item #Appends", "#a prediction of what an image with those features might", "that its a directory label_path = location+'/'+label if(not isdir(label_path)): continue", "features might be. #The labels file is also placed in", "ModelCheckpoint(output_dir + \"/extModel\"+str(int(time()))+\".h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1) early", "0 label_names = [] if(not isdir(data_path)): print(\"Could not find directory:", "file is also placed in this directory #The model created", "create_data_set(train_dir,output_dir+\"/train\",save_to_file=True) X_val,y_val,labels = create_data_set(val_dir,output_dir+\"/validation\",save_to_file=True) #shuffle the train data X_train,y_train =", "as np #find out how many classes num_classes = 0", "import time from keras.applications.resnet50 import ResNet50 from keras.models import Sequential", "imgr = img.resize(shape[1:3]) x = img_to_array(imgr).reshape((1,shape[1],shape[2],shape[3])) #predict features = self.resnet.predict(x)", "one hot encoding #label names from os.path import isdir from", "its a directory label_path = location+'/'+label if(not isdir(label_path)): continue #create", "image being added #resnet - the resnet model to be", "import numpy as np npyname = train_dir+'/'+label+'.npy' if(not exists(npyname)): np.save(npyname,features)", "files into one large file with their respective labels #INPUTS:", "= np.reshape(features,(features.shape[0],features.shape[3])) #save the features in a numpy binary np.save(location+'/'+label+'.npy',", "'\\n' for label in label_names])) return X,y,label_names def train_classifier_from_images(train_dir,train_size,val_dir,val_size,output_dir): #INPUTS:", "import numpy as np #find out how many classes num_classes", "extModel.fit(X_train,y_train, batch_size=32, epochs=50, validation_data=(X_val,y_val), callbacks = [checkpoint,early]) return extModel def", "label_path = location+'/'+label if(not isdir(label_path)): continue #create the data generator", "npy files are contained #image - the path to the", "encoding #label names from os.path import isdir from os import", "into one large file with their respective labels #INPUTS: #a", "validation images #output_dir is the directory to save the trained", "#generates feature maps from the convolutional layers of ResNet50 using", "__init__(self, modelpath, labels, min_confidence = 0.6): from keras.models import load_model", "#Output size is 256x256 to fit the ResNet50 print(\"Generating feature", "from os.path import isdir from os import listdir import numpy", "respective labels #INPUTS: #a directory containing npy fils of all", "np.vstack([arr for arr in arrays]) #load the labels into memory", "image img = Image.open(img) #resize image #shape from model input", "how many classes num_classes = 0 label_names = [] if(not", "maps and outputs #a prediction of what an image with", "= np.load(data_path+'/'+f) sizes.append(arr.shape[0]) arrays.append(arr) X = np.vstack([arr for arr in", "containig the training images #test_dir is the directory containing the", "generate_features_from_directory(val_dir,val_size,model=resnet) #create the combined dataset print(\"Combining datasets...\") X_train,y_train,labels = create_data_set(train_dir,output_dir+\"/train\",save_to_file=True)", "ResNet50 without top layer print(\"Loading the ResNet50 Network...\") resnet =", "image is a filepath if(isinstance(img,str)): if(not os.path.exists(img)): print(\"Error: Invalid File", "need to do this on either a high ram machine", "convert to PIL image img = Image.open(image) shape = resnet.input_shape", "to PIL image img = Image.open(img) #resize image #shape from", "large file with their respective labels #INPUTS: #a directory containing", "path to the image being added #resnet - the resnet", "FoodClassifier: #Class Attributes: #model - the underlying keras model #labels", "vector #produced by ResNet50's convolutional layers #data is generated in", "memory. #In the future, might need to do this on", "images #output_dir is the directory to save the trained model", "file path from os.path import exists if(exists(labels)): f = open(labels,'r')" ]
[ "-*- # Copyright (c) 2020-2021 FreeHackQuest Team <<EMAIL>> \"\"\"This file", "FreeHackQuest Team <<EMAIL>> \"\"\"This file was automatically generated by fhq-server", "python3 # -*- coding: utf-8 -*- # Copyright (c) 2020-2021", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c)", "\"\"\"This file was automatically generated by fhq-server Version: v0.2.47 Date:", "file was automatically generated by fhq-server Version: v0.2.47 Date: 2022-01-01", "Team <<EMAIL>> \"\"\"This file was automatically generated by fhq-server Version:", "was automatically generated by fhq-server Version: v0.2.47 Date: 2022-01-01 07:15:35", "fhq-server Version: v0.2.47 Date: 2022-01-01 07:15:35 \"\"\" from freehackquest_libclient_py.freehackquest_client import", "<<EMAIL>> \"\"\"This file was automatically generated by fhq-server Version: v0.2.47", "# Copyright (c) 2020-2021 FreeHackQuest Team <<EMAIL>> \"\"\"This file was", "generated by fhq-server Version: v0.2.47 Date: 2022-01-01 07:15:35 \"\"\" from", "utf-8 -*- # Copyright (c) 2020-2021 FreeHackQuest Team <<EMAIL>> \"\"\"This", "-*- coding: utf-8 -*- # Copyright (c) 2020-2021 FreeHackQuest Team", "Version: v0.2.47 Date: 2022-01-01 07:15:35 \"\"\" from freehackquest_libclient_py.freehackquest_client import FreeHackQuestClient", "automatically generated by fhq-server Version: v0.2.47 Date: 2022-01-01 07:15:35 \"\"\"", "Copyright (c) 2020-2021 FreeHackQuest Team <<EMAIL>> \"\"\"This file was automatically", "by fhq-server Version: v0.2.47 Date: 2022-01-01 07:15:35 \"\"\" from freehackquest_libclient_py.freehackquest_client", "(c) 2020-2021 FreeHackQuest Team <<EMAIL>> \"\"\"This file was automatically generated", "coding: utf-8 -*- # Copyright (c) 2020-2021 FreeHackQuest Team <<EMAIL>>", "# -*- coding: utf-8 -*- # Copyright (c) 2020-2021 FreeHackQuest", "2020-2021 FreeHackQuest Team <<EMAIL>> \"\"\"This file was automatically generated by", "<reponame>freehackquest/libfhqcli-py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright" ]
[ "True self.wst.start() logger.debug(\"Started thread\") # Wait for connect before continuing", "data = message['data'] channel = message['channel'] symbol = channel.split('_')[-1] stream", "in ['bids', 'asks']: for cur in data[side]: if not all_data.get(symbol,", "logger.error('%s. Stream is not initialized', self.exchange) def close_socket(self): self.exited =", "'bts:subscribe' cur['data'] = {'channel': \"{}_{}\".format(sub_stream, pair)} self.streams.append(cur) def start_multiple_websocket(self, init_streams=True):", "def __on_message(self, ws, message): if message is None: return try:", "to %s! Exiting.\", self.node, self.exchange) self.close_socket() else: logger.info('{} socket is", "'asks']: for cur in data[side]: if not all_data.get(symbol, None): all_data[symbol]", "Couldn't connect to %s! Exiting.\", self.node, self.exchange) self.close_socket() else: logger.info('{}", "= cur[0] size = cur[1] all_data[symbol].append(\"{},{},{}\\n\".format( data_time, price, size if", "time import json import ssl logger = MyLogger() class BitstampWebsocket(ExchangeWebSocket):", "error)) def __on_close(self, ws): logger.info(\"On close\\n{}\".format(self.exchange)) def __on_open(self, ws): logger.info(\"On", "import MyLogger import websocket import threading from time import sleep", "None: return try: self.last_msg_time = int(time()) message = json.loads(message) channel", "= ['live_trades', 'diff_order_book'] self.streams = [] def init_streams(self): for pair,", "all_data[symbol].append(\"{},{},{}\\n\".format( data_time, price, size if side == \"bids\" else \"-{}\".format(size)))", "self.streams: for stream in self.streams: logger.info('Subscribing to %s', json.dumps(stream)) self.ws.send(json.dumps(stream))", "time import sleep from time import time import json import", "= channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)] all_data = {}", "import websocket import threading from time import sleep from time", "\"{},{},{},{}\\n\".format(data['timestamp'], data['price'], data['amount'], data['type']) self.file_manager.save_data_to_file(self.exchange, stream, symbol, append_data) def save_level2_orderbook(self,", "symbol, append_data) def save_level2_orderbook(self, message): data = message['data'] channel =", "size = cur[1] all_data[symbol].append(\"{},{},{}\\n\".format( data_time, price, size if side ==", "if side == \"bids\" else \"-{}\".format(size))) for symbol, l2_ob_data in", "= websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close) self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs':", "self.node, self.exchange) self.close_socket() else: logger.info('{} socket is started:\\n{}\\n{}'.format(self.exchange, self.node, str(self.streams)))", "int(time()) message = json.loads(message) channel = message['channel'] if channel.startswith('diff_order_book'): self.save_level2_orderbook(message)", "[] price = cur[0] size = cur[1] all_data[symbol].append(\"{},{},{}\\n\".format( data_time, price,", "cur = dict() cur['event'] = 'bts:subscribe' cur['data'] = {'channel': \"{}_{}\".format(sub_stream,", "message): data = message['data'] channel = message['channel'] symbol = channel.split('_')[-1]", "cur['data'] = {'channel': \"{}_{}\".format(sub_stream, pair)} self.streams.append(cur) def start_multiple_websocket(self, init_streams=True): super().start_multiple_websocket(init_streams=init_streams)", "on_open=self.__on_open, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close) self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})) self.wst.daemon", "import threading from time import sleep from time import time", "channel = message['channel'] symbol = channel.split('_')[-1] stream = channel[:-(len(symbol) +", "= message['data'] channel = message['channel'] symbol = channel.split('_')[-1] stream =", "cur[1] all_data[symbol].append(\"{},{},{}\\n\".format( data_time, price, size if side == \"bids\" else", "15 while not self.ws.sock or not self.ws.sock.connected and conn_timeout: sleep(1)", "websocket.enableTrace(True) self.ws = websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close) self.wst =", "channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)] append_data = \"{},{},{},{}\\n\".format(data['timestamp'], data['price'],", "__init__(self, pairs_n_streams): super().__init__('Bitstamp', pairs_n_streams) self.possible_streams = ['live_trades', 'diff_order_book'] self.streams =", "in streams.split(','): if self.has_stream(sub_stream): cur = dict() cur['event'] = 'bts:subscribe'", "message['channel'] symbol = channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)] all_data", "= MyLogger() class BitstampWebsocket(ExchangeWebSocket): def __init__(self, pairs_n_streams): super().__init__('Bitstamp', pairs_n_streams) self.possible_streams", "exchange_sockets.exchange_websocket import ExchangeWebSocket from singletones.custom_logger import MyLogger import websocket import", "price, size if side == \"bids\" else \"-{}\".format(size))) for symbol,", "['live_trades', 'diff_order_book'] self.streams = [] def init_streams(self): for pair, streams", "= json.loads(message) channel = message['channel'] if channel.startswith('diff_order_book'): self.save_level2_orderbook(message) elif channel.startswith('live_trades'):", "not initialized', self.exchange) def close_socket(self): self.exited = True if self.ws:", "data_time, price, size if side == \"bids\" else \"-{}\".format(size))) for", "self.wst.start() logger.debug(\"Started thread\") # Wait for connect before continuing conn_timeout", "message['channel'] if channel.startswith('diff_order_book'): self.save_level2_orderbook(message) elif channel.startswith('live_trades'): self.save_trades(message) except Exception as", "__on_close(self, ws): logger.info(\"On close\\n{}\".format(self.exchange)) def __on_open(self, ws): logger.info(\"On Open\\n{}\".format(self.exchange)) if", "and conn_timeout: sleep(1) conn_timeout -= 1 if not conn_timeout: logger.error(\"%s", "close\\n{}\".format(self.exchange)) def __on_open(self, ws): logger.info(\"On Open\\n{}\".format(self.exchange)) if self.streams: for stream", "from time import time import json import ssl logger =", "not self.ws.sock or not self.ws.sock.connected and conn_timeout: sleep(1) conn_timeout -=", "sleep(1) conn_timeout -= 1 if not conn_timeout: logger.error(\"%s Couldn't connect", "logger.info('Subscribing to %s', json.dumps(stream)) self.ws.send(json.dumps(stream)) sleep(2) else: logger.error('%s. Stream is", "+ 1)] append_data = \"{},{},{},{}\\n\".format(data['timestamp'], data['price'], data['amount'], data['type']) self.file_manager.save_data_to_file(self.exchange, stream,", "else: logger.error('%s. Stream is not initialized', self.exchange) def close_socket(self): self.exited", "conn_timeout = 15 while not self.ws.sock or not self.ws.sock.connected and", "socket is started:\\n{}\\n{}'.format(self.exchange, self.node, str(self.streams))) def save_trades(self, message): data =", "# Wait for connect before continuing conn_timeout = 15 while", "str(self.streams))) def save_trades(self, message): data = message['data'] channel = message['channel']", "websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close) self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE}))", "channel[:-(len(symbol) + 1)] append_data = \"{},{},{},{}\\n\".format(data['timestamp'], data['price'], data['amount'], data['type']) self.file_manager.save_data_to_file(self.exchange,", "= message['channel'] if channel.startswith('diff_order_book'): self.save_level2_orderbook(message) elif channel.startswith('live_trades'): self.save_trades(message) except Exception", "l2_ob_data: self.file_manager.save_data_to_file(self.exchange, stream, symbol, l2_ob) def __on_message(self, ws, message): if", "symbol, l2_ob_data in all_data.items(): for l2_ob in l2_ob_data: self.file_manager.save_data_to_file(self.exchange, stream,", "websocket import threading from time import sleep from time import", "append_data = \"{},{},{},{}\\n\".format(data['timestamp'], data['price'], data['amount'], data['type']) self.file_manager.save_data_to_file(self.exchange, stream, symbol, append_data)", "error): self.on_error = True logger.error(\"On error\\n{}\\n{} {}\".format(self.node, self.exchange, error)) def", "ssl.CERT_NONE})) self.wst.daemon = True self.wst.start() logger.debug(\"Started thread\") # Wait for", "Open\\n{}\".format(self.exchange)) if self.streams: for stream in self.streams: logger.info('Subscribing to %s',", "= dict() cur['event'] = 'bts:subscribe' cur['data'] = {'channel': \"{}_{}\".format(sub_stream, pair)}", "ssl logger = MyLogger() class BitstampWebsocket(ExchangeWebSocket): def __init__(self, pairs_n_streams): super().__init__('Bitstamp',", "ExchangeWebSocket from singletones.custom_logger import MyLogger import websocket import threading from", "json import ssl logger = MyLogger() class BitstampWebsocket(ExchangeWebSocket): def __init__(self,", "sub_stream in streams.split(','): if self.has_stream(sub_stream): cur = dict() cur['event'] =", "message): if message is None: return try: self.last_msg_time = int(time())", "%s! Exiting.\", self.node, self.exchange) self.close_socket() else: logger.info('{} socket is started:\\n{}\\n{}'.format(self.exchange,", "not conn_timeout: logger.error(\"%s Couldn't connect to %s! Exiting.\", self.node, self.exchange)", "stream, symbol, l2_ob) def __on_message(self, ws, message): if message is", "else \"-{}\".format(size))) for symbol, l2_ob_data in all_data.items(): for l2_ob in", "connect before continuing conn_timeout = 15 while not self.ws.sock or", "start_multiple_websocket(self, init_streams=True): super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True) self.ws = websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open, on_message=self.__on_message, on_error=self.__on_error,", "self.on_error = True logger.error(\"On error\\n{}\\n{} {}\".format(self.node, self.exchange, error)) def __on_close(self,", "stream, symbol, append_data) def save_level2_orderbook(self, message): data = message['data'] channel", "logger = MyLogger() class BitstampWebsocket(ExchangeWebSocket): def __init__(self, pairs_n_streams): super().__init__('Bitstamp', pairs_n_streams)", "def init_streams(self): for pair, streams in self.pairs_n_streams.items(): for sub_stream in", "import time import json import ssl logger = MyLogger() class", "message = json.loads(message) channel = message['channel'] if channel.startswith('diff_order_book'): self.save_level2_orderbook(message) elif", "l2_ob_data in all_data.items(): for l2_ob in l2_ob_data: self.file_manager.save_data_to_file(self.exchange, stream, symbol,", "class BitstampWebsocket(ExchangeWebSocket): def __init__(self, pairs_n_streams): super().__init__('Bitstamp', pairs_n_streams) self.possible_streams = ['live_trades',", "conn_timeout: logger.error(\"%s Couldn't connect to %s! Exiting.\", self.node, self.exchange) self.close_socket()", "for l2_ob in l2_ob_data: self.file_manager.save_data_to_file(self.exchange, stream, symbol, l2_ob) def __on_message(self,", "streams in self.pairs_n_streams.items(): for sub_stream in streams.split(','): if self.has_stream(sub_stream): cur", "cur['event'] = 'bts:subscribe' cur['data'] = {'channel': \"{}_{}\".format(sub_stream, pair)} self.streams.append(cur) def", "stream = channel[:-(len(symbol) + 1)] all_data = {} data_time =", "cur[0] size = cur[1] all_data[symbol].append(\"{},{},{}\\n\".format( data_time, price, size if side", "before continuing conn_timeout = 15 while not self.ws.sock or not", "Exiting.\", self.node, self.exchange) self.close_socket() else: logger.info('{} socket is started:\\n{}\\n{}'.format(self.exchange, self.node,", "logger.info(\"On Open\\n{}\".format(self.exchange)) if self.streams: for stream in self.streams: logger.info('Subscribing to", "size if side == \"bids\" else \"-{}\".format(size))) for symbol, l2_ob_data", "on_close=self.__on_close) self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})) self.wst.daemon = True self.wst.start()", "threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})) self.wst.daemon = True self.wst.start() logger.debug(\"Started thread\") #", "self.file_manager.save_data_to_file(self.exchange, stream, symbol, append_data) def save_level2_orderbook(self, message): data = message['data']", "try: self.last_msg_time = int(time()) message = json.loads(message) channel = message['channel']", "if message is None: return try: self.last_msg_time = int(time()) message", "'diff_order_book'] self.streams = [] def init_streams(self): for pair, streams in", "save_trades(self, message): data = message['data'] channel = message['channel'] symbol =", "all_data = {} data_time = data['timestamp'] for side in ['bids',", "super().__init__('Bitstamp', pairs_n_streams) self.possible_streams = ['live_trades', 'diff_order_book'] self.streams = [] def", "else: logger.info('{} socket is started:\\n{}\\n{}'.format(self.exchange, self.node, str(self.streams))) def save_trades(self, message):", "= data['timestamp'] for side in ['bids', 'asks']: for cur in", "data['price'], data['amount'], data['type']) self.file_manager.save_data_to_file(self.exchange, stream, symbol, append_data) def save_level2_orderbook(self, message):", "ws, error): self.on_error = True logger.error(\"On error\\n{}\\n{} {}\".format(self.node, self.exchange, error))", "in self.pairs_n_streams.items(): for sub_stream in streams.split(','): if self.has_stream(sub_stream): cur =", "self.ws.sock.connected and conn_timeout: sleep(1) conn_timeout -= 1 if not conn_timeout:", "+ 1)] all_data = {} data_time = data['timestamp'] for side", "if self.has_stream(sub_stream): cur = dict() cur['event'] = 'bts:subscribe' cur['data'] =", "\"bids\" else \"-{}\".format(size))) for symbol, l2_ob_data in all_data.items(): for l2_ob", "as e: logger.debug(str(e)) def __on_error(self, ws, error): self.on_error = True", "if self.streams: for stream in self.streams: logger.info('Subscribing to %s', json.dumps(stream))", "self.streams: logger.info('Subscribing to %s', json.dumps(stream)) self.ws.send(json.dumps(stream)) sleep(2) else: logger.error('%s. Stream", "%s', json.dumps(stream)) self.ws.send(json.dumps(stream)) sleep(2) else: logger.error('%s. Stream is not initialized',", "message['channel'] symbol = channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)] append_data", "super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True) self.ws = websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close) self.wst", "= channel[:-(len(symbol) + 1)] all_data = {} data_time = data['timestamp']", "def start_multiple_websocket(self, init_streams=True): super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True) self.ws = websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open, on_message=self.__on_message,", "MyLogger import websocket import threading from time import sleep from", "symbol, l2_ob) def __on_message(self, ws, message): if message is None:", "is not initialized', self.exchange) def close_socket(self): self.exited = True if", "data[side]: if not all_data.get(symbol, None): all_data[symbol] = [] price =", "message is None: return try: self.last_msg_time = int(time()) message =", "Stream is not initialized', self.exchange) def close_socket(self): self.exited = True", "['bids', 'asks']: for cur in data[side]: if not all_data.get(symbol, None):", "symbol = channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)] append_data =", "pairs_n_streams) self.possible_streams = ['live_trades', 'diff_order_book'] self.streams = [] def init_streams(self):", "= channel[:-(len(symbol) + 1)] append_data = \"{},{},{},{}\\n\".format(data['timestamp'], data['price'], data['amount'], data['type'])", "in all_data.items(): for l2_ob in l2_ob_data: self.file_manager.save_data_to_file(self.exchange, stream, symbol, l2_ob)", "\"-{}\".format(size))) for symbol, l2_ob_data in all_data.items(): for l2_ob in l2_ob_data:", "BitstampWebsocket(ExchangeWebSocket): def __init__(self, pairs_n_streams): super().__init__('Bitstamp', pairs_n_streams) self.possible_streams = ['live_trades', 'diff_order_book']", "= [] def init_streams(self): for pair, streams in self.pairs_n_streams.items(): for", "self.pairs_n_streams.items(): for sub_stream in streams.split(','): if self.has_stream(sub_stream): cur = dict()", "json.dumps(stream)) self.ws.send(json.dumps(stream)) sleep(2) else: logger.error('%s. Stream is not initialized', self.exchange)", "= {} data_time = data['timestamp'] for side in ['bids', 'asks']:", "channel.startswith('live_trades'): self.save_trades(message) except Exception as e: logger.debug(str(e)) def __on_error(self, ws,", "logger.info(\"On close\\n{}\".format(self.exchange)) def __on_open(self, ws): logger.info(\"On Open\\n{}\".format(self.exchange)) if self.streams: for", "all_data[symbol] = [] price = cur[0] size = cur[1] all_data[symbol].append(\"{},{},{}\\n\".format(", "MyLogger() class BitstampWebsocket(ExchangeWebSocket): def __init__(self, pairs_n_streams): super().__init__('Bitstamp', pairs_n_streams) self.possible_streams =", "= 15 while not self.ws.sock or not self.ws.sock.connected and conn_timeout:", "{} data_time = data['timestamp'] for side in ['bids', 'asks']: for", "ws, message): if message is None: return try: self.last_msg_time =", "is None: return try: self.last_msg_time = int(time()) message = json.loads(message)", "ws): logger.info(\"On close\\n{}\".format(self.exchange)) def __on_open(self, ws): logger.info(\"On Open\\n{}\".format(self.exchange)) if self.streams:", "for sub_stream in streams.split(','): if self.has_stream(sub_stream): cur = dict() cur['event']", "pair, streams in self.pairs_n_streams.items(): for sub_stream in streams.split(','): if self.has_stream(sub_stream):", "threading from time import sleep from time import time import", "thread\") # Wait for connect before continuing conn_timeout = 15", "pairs_n_streams): super().__init__('Bitstamp', pairs_n_streams) self.possible_streams = ['live_trades', 'diff_order_book'] self.streams = []", "except Exception as e: logger.debug(str(e)) def __on_error(self, ws, error): self.on_error", "import sleep from time import time import json import ssl", "if channel.startswith('diff_order_book'): self.save_level2_orderbook(message) elif channel.startswith('live_trades'): self.save_trades(message) except Exception as e:", "self.exchange, error)) def __on_close(self, ws): logger.info(\"On close\\n{}\".format(self.exchange)) def __on_open(self, ws):", "{}\".format(self.node, self.exchange, error)) def __on_close(self, ws): logger.info(\"On close\\n{}\".format(self.exchange)) def __on_open(self,", "ws): logger.info(\"On Open\\n{}\".format(self.exchange)) if self.streams: for stream in self.streams: logger.info('Subscribing", "side in ['bids', 'asks']: for cur in data[side]: if not", "channel[:-(len(symbol) + 1)] all_data = {} data_time = data['timestamp'] for", "price = cur[0] size = cur[1] all_data[symbol].append(\"{},{},{}\\n\".format( data_time, price, size", "import json import ssl logger = MyLogger() class BitstampWebsocket(ExchangeWebSocket): def", "self.possible_streams = ['live_trades', 'diff_order_book'] self.streams = [] def init_streams(self): for", "self.wst.daemon = True self.wst.start() logger.debug(\"Started thread\") # Wait for connect", "is started:\\n{}\\n{}'.format(self.exchange, self.node, str(self.streams))) def save_trades(self, message): data = message['data']", "save_level2_orderbook(self, message): data = message['data'] channel = message['channel'] symbol =", "channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)] all_data = {} data_time", "all_data.get(symbol, None): all_data[symbol] = [] price = cur[0] size =", "side == \"bids\" else \"-{}\".format(size))) for symbol, l2_ob_data in all_data.items():", "elif channel.startswith('live_trades'): self.save_trades(message) except Exception as e: logger.debug(str(e)) def __on_error(self,", "sleep(2) else: logger.error('%s. Stream is not initialized', self.exchange) def close_socket(self):", "not self.ws.sock.connected and conn_timeout: sleep(1) conn_timeout -= 1 if not", "l2_ob) def __on_message(self, ws, message): if message is None: return", "self.ws.send(json.dumps(stream)) sleep(2) else: logger.error('%s. Stream is not initialized', self.exchange) def", "self.save_level2_orderbook(message) elif channel.startswith('live_trades'): self.save_trades(message) except Exception as e: logger.debug(str(e)) def", "streams.split(','): if self.has_stream(sub_stream): cur = dict() cur['event'] = 'bts:subscribe' cur['data']", "self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})) self.wst.daemon = True self.wst.start() logger.debug(\"Started thread\") # Wait", "not all_data.get(symbol, None): all_data[symbol] = [] price = cur[0] size", "None): all_data[symbol] = [] price = cur[0] size = cur[1]", "= cur[1] all_data[symbol].append(\"{},{},{}\\n\".format( data_time, price, size if side == \"bids\"", "sleep from time import time import json import ssl logger", "= channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)] append_data = \"{},{},{},{}\\n\".format(data['timestamp'],", "__on_message(self, ws, message): if message is None: return try: self.last_msg_time", "return try: self.last_msg_time = int(time()) message = json.loads(message) channel =", "self.has_stream(sub_stream): cur = dict() cur['event'] = 'bts:subscribe' cur['data'] = {'channel':", "logger.info('{} socket is started:\\n{}\\n{}'.format(self.exchange, self.node, str(self.streams))) def save_trades(self, message): data", "in data[side]: if not all_data.get(symbol, None): all_data[symbol] = [] price", "started:\\n{}\\n{}'.format(self.exchange, self.node, str(self.streams))) def save_trades(self, message): data = message['data'] channel", "e: logger.debug(str(e)) def __on_error(self, ws, error): self.on_error = True logger.error(\"On", "if not all_data.get(symbol, None): all_data[symbol] = [] price = cur[0]", "init_streams=True): super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True) self.ws = websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close)", "for symbol, l2_ob_data in all_data.items(): for l2_ob in l2_ob_data: self.file_manager.save_data_to_file(self.exchange,", "message['data'] channel = message['channel'] symbol = channel.split('_')[-1] stream = channel[:-(len(symbol)", "append_data) def save_level2_orderbook(self, message): data = message['data'] channel = message['channel']", "while not self.ws.sock or not self.ws.sock.connected and conn_timeout: sleep(1) conn_timeout", "= \"{},{},{},{}\\n\".format(data['timestamp'], data['price'], data['amount'], data['type']) self.file_manager.save_data_to_file(self.exchange, stream, symbol, append_data) def", "channel.startswith('diff_order_book'): self.save_level2_orderbook(message) elif channel.startswith('live_trades'): self.save_trades(message) except Exception as e: logger.debug(str(e))", "in self.streams: logger.info('Subscribing to %s', json.dumps(stream)) self.ws.send(json.dumps(stream)) sleep(2) else: logger.error('%s.", "self.streams = [] def init_streams(self): for pair, streams in self.pairs_n_streams.items():", "__on_error(self, ws, error): self.on_error = True logger.error(\"On error\\n{}\\n{} {}\".format(self.node, self.exchange,", "= {'channel': \"{}_{}\".format(sub_stream, pair)} self.streams.append(cur) def start_multiple_websocket(self, init_streams=True): super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True)", "continuing conn_timeout = 15 while not self.ws.sock or not self.ws.sock.connected", "for connect before continuing conn_timeout = 15 while not self.ws.sock", "data['type']) self.file_manager.save_data_to_file(self.exchange, stream, symbol, append_data) def save_level2_orderbook(self, message): data =", "= [] price = cur[0] size = cur[1] all_data[symbol].append(\"{},{},{}\\n\".format( data_time,", "def __init__(self, pairs_n_streams): super().__init__('Bitstamp', pairs_n_streams) self.possible_streams = ['live_trades', 'diff_order_book'] self.streams", "1)] append_data = \"{},{},{},{}\\n\".format(data['timestamp'], data['price'], data['amount'], data['type']) self.file_manager.save_data_to_file(self.exchange, stream, symbol,", "self.ws.sock or not self.ws.sock.connected and conn_timeout: sleep(1) conn_timeout -= 1", "self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})) self.wst.daemon = True self.wst.start() logger.debug(\"Started", "for side in ['bids', 'asks']: for cur in data[side]: if", "def __on_error(self, ws, error): self.on_error = True logger.error(\"On error\\n{}\\n{} {}\".format(self.node,", "def __on_open(self, ws): logger.info(\"On Open\\n{}\".format(self.exchange)) if self.streams: for stream in", "= True self.wst.start() logger.debug(\"Started thread\") # Wait for connect before", "def save_level2_orderbook(self, message): data = message['data'] channel = message['channel'] symbol", "1)] all_data = {} data_time = data['timestamp'] for side in", "error\\n{}\\n{} {}\".format(self.node, self.exchange, error)) def __on_close(self, ws): logger.info(\"On close\\n{}\".format(self.exchange)) def", "on_error=self.__on_error, on_close=self.__on_close) self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})) self.wst.daemon = True", "for stream in self.streams: logger.info('Subscribing to %s', json.dumps(stream)) self.ws.send(json.dumps(stream)) sleep(2)", "conn_timeout: sleep(1) conn_timeout -= 1 if not conn_timeout: logger.error(\"%s Couldn't", "pair)} self.streams.append(cur) def start_multiple_websocket(self, init_streams=True): super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True) self.ws = websocket.WebSocketApp(\"wss://ws.bitstamp.net\",", "import ssl logger = MyLogger() class BitstampWebsocket(ExchangeWebSocket): def __init__(self, pairs_n_streams):", "{'channel': \"{}_{}\".format(sub_stream, pair)} self.streams.append(cur) def start_multiple_websocket(self, init_streams=True): super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True) self.ws", "def save_trades(self, message): data = message['data'] channel = message['channel'] symbol", "data_time = data['timestamp'] for side in ['bids', 'asks']: for cur", "in l2_ob_data: self.file_manager.save_data_to_file(self.exchange, stream, symbol, l2_ob) def __on_message(self, ws, message):", "from exchange_sockets.exchange_websocket import ExchangeWebSocket from singletones.custom_logger import MyLogger import websocket", "logger.error(\"%s Couldn't connect to %s! Exiting.\", self.node, self.exchange) self.close_socket() else:", "initialized', self.exchange) def close_socket(self): self.exited = True if self.ws: self.ws.close()", "conn_timeout -= 1 if not conn_timeout: logger.error(\"%s Couldn't connect to", "if not conn_timeout: logger.error(\"%s Couldn't connect to %s! Exiting.\", self.node,", "= True logger.error(\"On error\\n{}\\n{} {}\".format(self.node, self.exchange, error)) def __on_close(self, ws):", "self.close_socket() else: logger.info('{} socket is started:\\n{}\\n{}'.format(self.exchange, self.node, str(self.streams))) def save_trades(self,", "data['timestamp'] for side in ['bids', 'asks']: for cur in data[side]:", "for pair, streams in self.pairs_n_streams.items(): for sub_stream in streams.split(','): if", "on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close) self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})) self.wst.daemon =", "l2_ob in l2_ob_data: self.file_manager.save_data_to_file(self.exchange, stream, symbol, l2_ob) def __on_message(self, ws,", "= 'bts:subscribe' cur['data'] = {'channel': \"{}_{}\".format(sub_stream, pair)} self.streams.append(cur) def start_multiple_websocket(self,", "json.loads(message) channel = message['channel'] if channel.startswith('diff_order_book'): self.save_level2_orderbook(message) elif channel.startswith('live_trades'): self.save_trades(message)", "1 if not conn_timeout: logger.error(\"%s Couldn't connect to %s! Exiting.\",", "Exception as e: logger.debug(str(e)) def __on_error(self, ws, error): self.on_error =", "== \"bids\" else \"-{}\".format(size))) for symbol, l2_ob_data in all_data.items(): for", "or not self.ws.sock.connected and conn_timeout: sleep(1) conn_timeout -= 1 if", "stream in self.streams: logger.info('Subscribing to %s', json.dumps(stream)) self.ws.send(json.dumps(stream)) sleep(2) else:", "= int(time()) message = json.loads(message) channel = message['channel'] if channel.startswith('diff_order_book'):", "for cur in data[side]: if not all_data.get(symbol, None): all_data[symbol] =", "to %s', json.dumps(stream)) self.ws.send(json.dumps(stream)) sleep(2) else: logger.error('%s. Stream is not", "self.file_manager.save_data_to_file(self.exchange, stream, symbol, l2_ob) def __on_message(self, ws, message): if message", "import ExchangeWebSocket from singletones.custom_logger import MyLogger import websocket import threading", "[] def init_streams(self): for pair, streams in self.pairs_n_streams.items(): for sub_stream", "logger.error(\"On error\\n{}\\n{} {}\".format(self.node, self.exchange, error)) def __on_close(self, ws): logger.info(\"On close\\n{}\".format(self.exchange))", "self.ws = websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open, on_message=self.__on_message, on_error=self.__on_error, on_close=self.__on_close) self.wst = threading.Thread(target=lambda:", "self.exchange) self.close_socket() else: logger.info('{} socket is started:\\n{}\\n{}'.format(self.exchange, self.node, str(self.streams))) def", "time import time import json import ssl logger = MyLogger()", "self.save_trades(message) except Exception as e: logger.debug(str(e)) def __on_error(self, ws, error):", "= threading.Thread(target=lambda: self.ws.run_forever(sslopt={'cert_reqs': ssl.CERT_NONE})) self.wst.daemon = True self.wst.start() logger.debug(\"Started thread\")", "singletones.custom_logger import MyLogger import websocket import threading from time import", "= message['channel'] symbol = channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)]", "channel = message['channel'] if channel.startswith('diff_order_book'): self.save_level2_orderbook(message) elif channel.startswith('live_trades'): self.save_trades(message) except", "data['amount'], data['type']) self.file_manager.save_data_to_file(self.exchange, stream, symbol, append_data) def save_level2_orderbook(self, message): data", "-= 1 if not conn_timeout: logger.error(\"%s Couldn't connect to %s!", "stream = channel[:-(len(symbol) + 1)] append_data = \"{},{},{},{}\\n\".format(data['timestamp'], data['price'], data['amount'],", "self.streams.append(cur) def start_multiple_websocket(self, init_streams=True): super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True) self.ws = websocket.WebSocketApp(\"wss://ws.bitstamp.net\", on_open=self.__on_open,", "from singletones.custom_logger import MyLogger import websocket import threading from time", "dict() cur['event'] = 'bts:subscribe' cur['data'] = {'channel': \"{}_{}\".format(sub_stream, pair)} self.streams.append(cur)", "all_data.items(): for l2_ob in l2_ob_data: self.file_manager.save_data_to_file(self.exchange, stream, symbol, l2_ob) def", "def __on_close(self, ws): logger.info(\"On close\\n{}\".format(self.exchange)) def __on_open(self, ws): logger.info(\"On Open\\n{}\".format(self.exchange))", "__on_open(self, ws): logger.info(\"On Open\\n{}\".format(self.exchange)) if self.streams: for stream in self.streams:", "\"{}_{}\".format(sub_stream, pair)} self.streams.append(cur) def start_multiple_websocket(self, init_streams=True): super().start_multiple_websocket(init_streams=init_streams) websocket.enableTrace(True) self.ws =", "self.node, str(self.streams))) def save_trades(self, message): data = message['data'] channel =", "init_streams(self): for pair, streams in self.pairs_n_streams.items(): for sub_stream in streams.split(','):", "True logger.error(\"On error\\n{}\\n{} {}\".format(self.node, self.exchange, error)) def __on_close(self, ws): logger.info(\"On", "connect to %s! Exiting.\", self.node, self.exchange) self.close_socket() else: logger.info('{} socket", "logger.debug(str(e)) def __on_error(self, ws, error): self.on_error = True logger.error(\"On error\\n{}\\n{}", "from time import sleep from time import time import json", "Wait for connect before continuing conn_timeout = 15 while not", "logger.debug(\"Started thread\") # Wait for connect before continuing conn_timeout =", "self.last_msg_time = int(time()) message = json.loads(message) channel = message['channel'] if", "cur in data[side]: if not all_data.get(symbol, None): all_data[symbol] = []", "symbol = channel.split('_')[-1] stream = channel[:-(len(symbol) + 1)] all_data =" ]
[ "batch_cutoff will be returned (This is to allow sampling with", "def __len__(self): return 1 def get_data_loader(task, batch_size=1, split='train'): # NOTE:", "instances PER CLASS if task.dataset == 'mnist': normalize = transforms.Normalize(mean=[0.13066,", "the number of batches up to the batch_cutoff will be", "task.num_inst, batch_cutoff = (None if split != 'train' else batch_size))", "in range(self.num_cl)] batches = [[batches[j][i] for j in range(self.num_cl)] for", "over batches of the entire dataset will be returned Otherwise,", "num_cl, num_inst, batch_cutoff=None): self.num_cl = num_cl self.num_inst = num_inst self.batch_cutoff", "torch.utils.data.sampler import Sampler import torchvision.transforms as transforms from dataset import", "will be grouped by class ''' # First construct batches", "random import torch from torch.utils.data import DataLoader from torch.utils.data.sampler import", "sublist] return iter(batches) def __len__(self): return 1 def get_data_loader(task, batch_size=1,", "batch_cutoff=None): self.num_cl = num_cl self.num_inst = num_inst self.batch_cutoff = batch_cutoff", "range(self.num_inst)] # Shuffle within each batch so that classes don't", "= (None if split != 'train' else batch_size)) loader =", "for loading class-balanced few-shot tasks from datasets ''' class ClassBalancedSampler(Sampler):", "# NOTE: batch size here is # instances PER CLASS", "''' Samples class-balanced batches from 'num_cl' pools each of size", "the entire dataset will be returned Otherwise, indices for the", "by class ''' # First construct batches of 1 instance", "single list of indices, assuming that items will be grouped", "for j in range(self.num_cl)] batches = [[batches[j][i] for j in", "will be returned (This is to allow sampling with replacement", "list of indices, assuming that items will be grouped by", "be returned Otherwise, indices for the number of batches up", "don't always appear in same order for sublist in batches:", "sampler = ClassBalancedSampler(task.num_cl, task.num_inst, batch_cutoff = (None if split !=", "class ''' # First construct batches of 1 instance per", "batches = [[i+j*self.num_inst for i in torch.randperm(self.num_inst)] for j in", "not None: random.shuffle(batches) batches = batches[:self.batch_cutoff] batches = [item for", "def get_data_loader(task, batch_size=1, split='train'): # NOTE: batch size here is", "get_data_loader(task, batch_size=1, split='train'): # NOTE: batch size here is #", "transforms from dataset import Omniglot, MNIST ''' Helpers for loading", "std=[0.08426, 0.08426, 0.08426]) dset = Omniglot(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) sampler", "= ClassBalancedSampler(task.num_cl, task.num_inst, batch_cutoff = (None if split != 'train'", "import random import torch from torch.utils.data import DataLoader from torch.utils.data.sampler", "to the batch_cutoff will be returned (This is to allow", "transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) sampler = ClassBalancedSampler(task.num_cl, task.num_inst, batch_cutoff = (None", "import Sampler import torchvision.transforms as transforms from dataset import Omniglot,", "= num_cl self.num_inst = num_inst self.batch_cutoff = batch_cutoff def __iter__(self):", "size here is # instances PER CLASS if task.dataset ==", "= num_inst self.batch_cutoff = batch_cutoff def __iter__(self): '''return a single", "[[i+j*self.num_inst for i in torch.randperm(self.num_inst)] for j in range(self.num_cl)] batches", "Otherwise, indices for the number of batches up to the", "[item for sublist in batches for item in sublist] return", "is None, indices for iterating over batches of the entire", "from torch.utils.data import DataLoader from torch.utils.data.sampler import Sampler import torchvision.transforms", "j in range(self.num_cl)] for i in range(self.num_inst)] # Shuffle within", "__len__(self): return 1 def get_data_loader(task, batch_size=1, split='train'): # NOTE: batch", "std=[0.30131, 0.30131, 0.30131]) dset = MNIST(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) else:", "numpy as np import random import torch from torch.utils.data import", "for iterating over batches of the entire dataset will be", "= MNIST(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) else: normalize = transforms.Normalize(mean=[0.92206, 0.92206,", "from dataset import Omniglot, MNIST ''' Helpers for loading class-balanced", "always appear in same order for sublist in batches: random.shuffle(sublist)", "1 instance per class batches = [[i+j*self.num_inst for i in", "if self.batch_cutoff is not None: random.shuffle(batches) batches = batches[:self.batch_cutoff] batches", "for i in torch.randperm(self.num_inst)] for j in range(self.num_cl)] batches =", "batches = batches[:self.batch_cutoff] batches = [item for sublist in batches", "1 def get_data_loader(task, batch_size=1, split='train'): # NOTE: batch size here", "0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426]) dset = Omniglot(task, transform=transforms.Compose([transforms.ToTensor(), normalize]),", "j in range(self.num_cl)] batches = [[batches[j][i] for j in range(self.num_cl)]", "import Omniglot, MNIST ''' Helpers for loading class-balanced few-shot tasks", "as transforms from dataset import Omniglot, MNIST ''' Helpers for", "size 'num_inst' If 'batch_cutoff' is None, indices for iterating over", "loading class-balanced few-shot tasks from datasets ''' class ClassBalancedSampler(Sampler): '''", "dataset will be returned Otherwise, indices for the number of", "Omniglot, MNIST ''' Helpers for loading class-balanced few-shot tasks from", "up to the batch_cutoff will be returned (This is to", "= transforms.Normalize(mean=[0.13066, 0.13066, 0.13066], std=[0.30131, 0.30131, 0.30131]) dset = MNIST(task,", "(None if split != 'train' else batch_size)) loader = DataLoader(dset,", "per class batches = [[i+j*self.num_inst for i in torch.randperm(self.num_inst)] for", "training iterations) ''' def __init__(self, num_cl, num_inst, batch_cutoff=None): self.num_cl =", "def __iter__(self): '''return a single list of indices, assuming that", "''' Helpers for loading class-balanced few-shot tasks from datasets '''", "datasets ''' class ClassBalancedSampler(Sampler): ''' Samples class-balanced batches from 'num_cl'", "be returned (This is to allow sampling with replacement across", "that items will be grouped by class ''' # First", "split=split) sampler = ClassBalancedSampler(task.num_cl, task.num_inst, batch_cutoff = (None if split", "batch_size)) loader = DataLoader(dset, batch_size=batch_size*task.num_cl, sampler=sampler, num_workers=1, pin_memory=True) return loader", "class batches = [[i+j*self.num_inst for i in torch.randperm(self.num_inst)] for j", "batch_cutoff def __iter__(self): '''return a single list of indices, assuming", "classes don't always appear in same order for sublist in", "num_cl self.num_inst = num_inst self.batch_cutoff = batch_cutoff def __iter__(self): '''return", "0.30131]) dset = MNIST(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) else: normalize =", "is # instances PER CLASS if task.dataset == 'mnist': normalize", "''' def __init__(self, num_cl, num_inst, batch_cutoff=None): self.num_cl = num_cl self.num_inst", "'''return a single list of indices, assuming that items will", "return iter(batches) def __len__(self): return 1 def get_data_loader(task, batch_size=1, split='train'):", "import numpy as np import random import torch from torch.utils.data", "for item in sublist] return iter(batches) def __len__(self): return 1", "batch size here is # instances PER CLASS if task.dataset", "batch so that classes don't always appear in same order", "self.num_inst = num_inst self.batch_cutoff = batch_cutoff def __iter__(self): '''return a", "self.batch_cutoff = batch_cutoff def __iter__(self): '''return a single list of", "MNIST(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) else: normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206],", "NOTE: batch size here is # instances PER CLASS if", "batches from 'num_cl' pools each of size 'num_inst' If 'batch_cutoff'", "= batch_cutoff def __iter__(self): '''return a single list of indices,", "allow sampling with replacement across training iterations) ''' def __init__(self,", "num_inst, batch_cutoff=None): self.num_cl = num_cl self.num_inst = num_inst self.batch_cutoff =", "for sublist in batches: random.shuffle(sublist) if self.batch_cutoff is not None:", "batches: random.shuffle(sublist) if self.batch_cutoff is not None: random.shuffle(batches) batches =", "that classes don't always appear in same order for sublist", "batches of the entire dataset will be returned Otherwise, indices", "class-balanced few-shot tasks from datasets ''' class ClassBalancedSampler(Sampler): ''' Samples", "be grouped by class ''' # First construct batches of", "= Omniglot(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) sampler = ClassBalancedSampler(task.num_cl, task.num_inst, batch_cutoff", "import torch from torch.utils.data import DataLoader from torch.utils.data.sampler import Sampler", "Helpers for loading class-balanced few-shot tasks from datasets ''' class", "DataLoader from torch.utils.data.sampler import Sampler import torchvision.transforms as transforms from", "torchvision.transforms as transforms from dataset import Omniglot, MNIST ''' Helpers", "'batch_cutoff' is None, indices for iterating over batches of the", "First construct batches of 1 instance per class batches =", "batches[:self.batch_cutoff] batches = [item for sublist in batches for item", "ClassBalancedSampler(task.num_cl, task.num_inst, batch_cutoff = (None if split != 'train' else", "# instances PER CLASS if task.dataset == 'mnist': normalize =", "batches up to the batch_cutoff will be returned (This is", "split='train'): # NOTE: batch size here is # instances PER", "batches of 1 instance per class batches = [[i+j*self.num_inst for", "dset = MNIST(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) else: normalize = transforms.Normalize(mean=[0.92206,", "for sublist in batches for item in sublist] return iter(batches)", "return 1 def get_data_loader(task, batch_size=1, split='train'): # NOTE: batch size", "batch_cutoff = (None if split != 'train' else batch_size)) loader", "in batches for item in sublist] return iter(batches) def __len__(self):", "# Shuffle within each batch so that classes don't always", "= [item for sublist in batches for item in sublist]", "sampling with replacement across training iterations) ''' def __init__(self, num_cl,", "returned (This is to allow sampling with replacement across training", "as np import random import torch from torch.utils.data import DataLoader", "range(self.num_cl)] for i in range(self.num_inst)] # Shuffle within each batch", "assuming that items will be grouped by class ''' #", "from datasets ''' class ClassBalancedSampler(Sampler): ''' Samples class-balanced batches from", "batches = [[batches[j][i] for j in range(self.num_cl)] for i in", "iterations) ''' def __init__(self, num_cl, num_inst, batch_cutoff=None): self.num_cl = num_cl", "range(self.num_cl)] batches = [[batches[j][i] for j in range(self.num_cl)] for i", "same order for sublist in batches: random.shuffle(sublist) if self.batch_cutoff is", "torch.utils.data import DataLoader from torch.utils.data.sampler import Sampler import torchvision.transforms as", "0.30131, 0.30131]) dset = MNIST(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) else: normalize", "import DataLoader from torch.utils.data.sampler import Sampler import torchvision.transforms as transforms", "'num_cl' pools each of size 'num_inst' If 'batch_cutoff' is None,", "i in torch.randperm(self.num_inst)] for j in range(self.num_cl)] batches = [[batches[j][i]", "transforms.Normalize(mean=[0.13066, 0.13066, 0.13066], std=[0.30131, 0.30131, 0.30131]) dset = MNIST(task, transform=transforms.Compose([transforms.ToTensor(),", "'train' else batch_size)) loader = DataLoader(dset, batch_size=batch_size*task.num_cl, sampler=sampler, num_workers=1, pin_memory=True)", "appear in same order for sublist in batches: random.shuffle(sublist) if", "if task.dataset == 'mnist': normalize = transforms.Normalize(mean=[0.13066, 0.13066, 0.13066], std=[0.30131,", "else: normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426]) dset", "(This is to allow sampling with replacement across training iterations)", "num_inst self.batch_cutoff = batch_cutoff def __iter__(self): '''return a single list", "item in sublist] return iter(batches) def __len__(self): return 1 def", "Omniglot(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) sampler = ClassBalancedSampler(task.num_cl, task.num_inst, batch_cutoff =", "normalize]), split=split) sampler = ClassBalancedSampler(task.num_cl, task.num_inst, batch_cutoff = (None if", "for j in range(self.num_cl)] for i in range(self.num_inst)] # Shuffle", "sublist in batches for item in sublist] return iter(batches) def", "indices, assuming that items will be grouped by class '''", "'num_inst' If 'batch_cutoff' is None, indices for iterating over batches", "= batches[:self.batch_cutoff] batches = [item for sublist in batches for", "in sublist] return iter(batches) def __len__(self): return 1 def get_data_loader(task,", "= transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426]) dset = Omniglot(task,", "from 'num_cl' pools each of size 'num_inst' If 'batch_cutoff' is", "replacement across training iterations) ''' def __init__(self, num_cl, num_inst, batch_cutoff=None):", "in same order for sublist in batches: random.shuffle(sublist) if self.batch_cutoff", "of size 'num_inst' If 'batch_cutoff' is None, indices for iterating", "self.num_cl = num_cl self.num_inst = num_inst self.batch_cutoff = batch_cutoff def", "np import random import torch from torch.utils.data import DataLoader from", "grouped by class ''' # First construct batches of 1", "0.08426]) dset = Omniglot(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) sampler = ClassBalancedSampler(task.num_cl,", "__init__(self, num_cl, num_inst, batch_cutoff=None): self.num_cl = num_cl self.num_inst = num_inst", "in range(self.num_cl)] for i in range(self.num_inst)] # Shuffle within each", "from torch.utils.data.sampler import Sampler import torchvision.transforms as transforms from dataset", "import torchvision.transforms as transforms from dataset import Omniglot, MNIST '''", "items will be grouped by class ''' # First construct", "across training iterations) ''' def __init__(self, num_cl, num_inst, batch_cutoff=None): self.num_cl", "random.shuffle(batches) batches = batches[:self.batch_cutoff] batches = [item for sublist in", "Samples class-balanced batches from 'num_cl' pools each of size 'num_inst'", "of indices, assuming that items will be grouped by class", "= [[i+j*self.num_inst for i in torch.randperm(self.num_inst)] for j in range(self.num_cl)]", "def __init__(self, num_cl, num_inst, batch_cutoff=None): self.num_cl = num_cl self.num_inst =", "sublist in batches: random.shuffle(sublist) if self.batch_cutoff is not None: random.shuffle(batches)", "with replacement across training iterations) ''' def __init__(self, num_cl, num_inst,", "instance per class batches = [[i+j*self.num_inst for i in torch.randperm(self.num_inst)]", "of 1 instance per class batches = [[i+j*self.num_inst for i", "torch.randperm(self.num_inst)] for j in range(self.num_cl)] batches = [[batches[j][i] for j", "order for sublist in batches: random.shuffle(sublist) if self.batch_cutoff is not", "normalize]), split=split) else: normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426,", "if split != 'train' else batch_size)) loader = DataLoader(dset, batch_size=batch_size*task.num_cl,", "pools each of size 'num_inst' If 'batch_cutoff' is None, indices", "to allow sampling with replacement across training iterations) ''' def", "class ClassBalancedSampler(Sampler): ''' Samples class-balanced batches from 'num_cl' pools each", "Shuffle within each batch so that classes don't always appear", "Sampler import torchvision.transforms as transforms from dataset import Omniglot, MNIST", "ClassBalancedSampler(Sampler): ''' Samples class-balanced batches from 'num_cl' pools each of", "__iter__(self): '''return a single list of indices, assuming that items", "batch_size=1, split='train'): # NOTE: batch size here is # instances", "entire dataset will be returned Otherwise, indices for the number", "iter(batches) def __len__(self): return 1 def get_data_loader(task, batch_size=1, split='train'): #", "0.08426, 0.08426]) dset = Omniglot(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) sampler =", "CLASS if task.dataset == 'mnist': normalize = transforms.Normalize(mean=[0.13066, 0.13066, 0.13066],", "split=split) else: normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426])", "indices for the number of batches up to the batch_cutoff", "in torch.randperm(self.num_inst)] for j in range(self.num_cl)] batches = [[batches[j][i] for", "else batch_size)) loader = DataLoader(dset, batch_size=batch_size*task.num_cl, sampler=sampler, num_workers=1, pin_memory=True) return", "task.dataset == 'mnist': normalize = transforms.Normalize(mean=[0.13066, 0.13066, 0.13066], std=[0.30131, 0.30131,", "few-shot tasks from datasets ''' class ClassBalancedSampler(Sampler): ''' Samples class-balanced", "''' class ClassBalancedSampler(Sampler): ''' Samples class-balanced batches from 'num_cl' pools", "torch from torch.utils.data import DataLoader from torch.utils.data.sampler import Sampler import", "number of batches up to the batch_cutoff will be returned", "split != 'train' else batch_size)) loader = DataLoader(dset, batch_size=batch_size*task.num_cl, sampler=sampler,", "None, indices for iterating over batches of the entire dataset", "<gh_stars>100-1000 import numpy as np import random import torch from", "will be returned Otherwise, indices for the number of batches", "returned Otherwise, indices for the number of batches up to", "None: random.shuffle(batches) batches = batches[:self.batch_cutoff] batches = [item for sublist", "a single list of indices, assuming that items will be", "of batches up to the batch_cutoff will be returned (This", "= [[batches[j][i] for j in range(self.num_cl)] for i in range(self.num_inst)]", "is to allow sampling with replacement across training iterations) '''", "of the entire dataset will be returned Otherwise, indices for", "''' # First construct batches of 1 instance per class", "in range(self.num_inst)] # Shuffle within each batch so that classes", "'mnist': normalize = transforms.Normalize(mean=[0.13066, 0.13066, 0.13066], std=[0.30131, 0.30131, 0.30131]) dset", "dset = Omniglot(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) sampler = ClassBalancedSampler(task.num_cl, task.num_inst,", "the batch_cutoff will be returned (This is to allow sampling", "dataset import Omniglot, MNIST ''' Helpers for loading class-balanced few-shot", "MNIST ''' Helpers for loading class-balanced few-shot tasks from datasets", "tasks from datasets ''' class ClassBalancedSampler(Sampler): ''' Samples class-balanced batches", "each batch so that classes don't always appear in same", "0.13066, 0.13066], std=[0.30131, 0.30131, 0.30131]) dset = MNIST(task, transform=transforms.Compose([transforms.ToTensor(), normalize]),", "each of size 'num_inst' If 'batch_cutoff' is None, indices for", "transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split) else: normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426,", "iterating over batches of the entire dataset will be returned", "!= 'train' else batch_size)) loader = DataLoader(dset, batch_size=batch_size*task.num_cl, sampler=sampler, num_workers=1,", "class-balanced batches from 'num_cl' pools each of size 'num_inst' If", "normalize = transforms.Normalize(mean=[0.13066, 0.13066, 0.13066], std=[0.30131, 0.30131, 0.30131]) dset =", "[[batches[j][i] for j in range(self.num_cl)] for i in range(self.num_inst)] #", "PER CLASS if task.dataset == 'mnist': normalize = transforms.Normalize(mean=[0.13066, 0.13066,", "indices for iterating over batches of the entire dataset will", "so that classes don't always appear in same order for", "# First construct batches of 1 instance per class batches", "0.13066], std=[0.30131, 0.30131, 0.30131]) dset = MNIST(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split)", "batches for item in sublist] return iter(batches) def __len__(self): return", "0.92206], std=[0.08426, 0.08426, 0.08426]) dset = Omniglot(task, transform=transforms.Compose([transforms.ToTensor(), normalize]), split=split)", "construct batches of 1 instance per class batches = [[i+j*self.num_inst", "batches = [item for sublist in batches for item in", "for i in range(self.num_inst)] # Shuffle within each batch so", "== 'mnist': normalize = transforms.Normalize(mean=[0.13066, 0.13066, 0.13066], std=[0.30131, 0.30131, 0.30131])", "normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426]) dset =", "in batches: random.shuffle(sublist) if self.batch_cutoff is not None: random.shuffle(batches) batches", "i in range(self.num_inst)] # Shuffle within each batch so that", "random.shuffle(sublist) if self.batch_cutoff is not None: random.shuffle(batches) batches = batches[:self.batch_cutoff]", "within each batch so that classes don't always appear in", "is not None: random.shuffle(batches) batches = batches[:self.batch_cutoff] batches = [item", "self.batch_cutoff is not None: random.shuffle(batches) batches = batches[:self.batch_cutoff] batches =", "here is # instances PER CLASS if task.dataset == 'mnist':", "for the number of batches up to the batch_cutoff will", "If 'batch_cutoff' is None, indices for iterating over batches of", "transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426]) dset = Omniglot(task, transform=transforms.Compose([transforms.ToTensor()," ]
[ "accepts arguments 'download' and 'withEns'\") except AttributeError or IndexError: raise", "splitArg[0] in (\"download\", \"withEns\"): inputDict[splitArg[0]] = splitArg[1] else: raise ValueError(\"Wrong", "inputDict['download'] == 'True' withEns = inputDict['withEns'] == 'True' print(\"Running DBbuilder", "= len(species) spnum = 1 for sp in species: print(\"===========Current", "dbBuild = dbBuilder(sp, download=download, withEns=withEns) dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False) print(\"Filling {} completed!\".format(dbBuild.dbName))", "== 'True' print(\"Running DBbuilder with Download {} and withENS {}\".format(download,", "{} and withENS {}\".format(download, withEns)) print(type(download)) print(type(withEns)) director = Director()", "print(\"Filling {} completed!\".format(dbBuild.dbName)) if spnum == 1: dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True) if", "import os sys.path.append(os.getcwd()) from Director import Director from OrthologsBuilder import", "Director import Director from OrthologsBuilder import * from SpeciesDB import", "DBbuilder with Download {} and withENS {}\".format(download, withEns)) print(type(download)) print(type(withEns))", "'True' print(\"Running DBbuilder with Download {} and withENS {}\".format(download, withEns))", "spnum = 1 for sp in species: print(\"===========Current Species: {}===========\".format(sp))", "input arguments are argumentName=argumentValue\") species = ['M_musculus', 'H_sapiens', 'R_norvegicus', 'D_rerio',", "download = inputDict['download'] == 'True' withEns = inputDict['withEns'] == 'True'", "sys import os sys.path.append(os.getcwd()) from Director import Director from OrthologsBuilder", "or IndexError: raise ValueError(\"Make sure that input arguments are argumentName=argumentValue\")", "and withENS {}\".format(download, withEns)) print(type(download)) print(type(withEns)) director = Director() orthologs", "len(species) spnum = 1 for sp in species: print(\"===========Current Species:", "OrthologsBuilder import * from SpeciesDB import * if __name__ ==", "spnum == spl: dbBuild.create_index() dbBuild.AddOrthology(orthologs.OrthoTable) spnum += 1 print(\"Filling {}", "print(\"===========Current Species: {}===========\".format(sp)) dbBuild = dbBuilder(sp, download=download, withEns=withEns) dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False)", "sure that input arguments are argumentName=argumentValue\") species = ['M_musculus', 'H_sapiens',", "== 'True' withEns = inputDict['withEns'] == 'True' print(\"Running DBbuilder with", "inputDict['withEns'] == 'True' print(\"Running DBbuilder with Download {} and withENS", "dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False) print(\"Filling {} completed!\".format(dbBuild.dbName)) if spnum == 1: dbBuild.create_tables_db(merged=True)", "try: splitArg = inarg.strip(\"-\").split(\"=\") if splitArg[0] in (\"download\", \"withEns\"): inputDict[splitArg[0]]", "in (\"download\", \"withEns\"): inputDict[splitArg[0]] = splitArg[1] else: raise ValueError(\"Wrong input", "withEns = inputDict['withEns'] == 'True' print(\"Running DBbuilder with Download {}", "print(type(download)) print(type(withEns)) director = Director() orthologs = OrthologsBuilder(species=species, download=download) director.setBuilder(orthologs)", "print(\"Running DBbuilder with Download {} and withENS {}\".format(download, withEns)) print(type(download))", "* if __name__ == \"__main__\": inputDict = {} for inarg", "= {} for inarg in sys.argv[1:]: try: splitArg = inarg.strip(\"-\").split(\"=\")", "input arguments. only accepts arguments 'download' and 'withEns'\") except AttributeError", "that input arguments are argumentName=argumentValue\") species = ['M_musculus', 'H_sapiens', 'R_norvegicus',", "= inarg.strip(\"-\").split(\"=\") if splitArg[0] in (\"download\", \"withEns\"): inputDict[splitArg[0]] = splitArg[1]", "spl = len(species) spnum = 1 for sp in species:", "sp in species: print(\"===========Current Species: {}===========\".format(sp)) dbBuild = dbBuilder(sp, download=download,", "import Director from OrthologsBuilder import * from SpeciesDB import *", "ValueError(\"Wrong input arguments. only accepts arguments 'download' and 'withEns'\") except", "withENS {}\".format(download, withEns)) print(type(download)) print(type(withEns)) director = Director() orthologs =", "__name__ == \"__main__\": inputDict = {} for inarg in sys.argv[1:]:", "'H_sapiens', 'R_norvegicus', 'D_rerio', 'X_tropicalis'] download = inputDict['download'] == 'True' withEns", "dbBuild.fill_in_db(merged=False) print(\"Filling {} completed!\".format(dbBuild.dbName)) if spnum == 1: dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True)", "\"__main__\": inputDict = {} for inarg in sys.argv[1:]: try: splitArg", "== 1: dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True) if spnum == spl: dbBuild.create_index() dbBuild.AddOrthology(orthologs.OrthoTable)", "Director from OrthologsBuilder import * from SpeciesDB import * if", "spnum == 1: dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True) if spnum == spl: dbBuild.create_index()", "completed!\".format(dbBuild.dbName)) if spnum == 1: dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True) if spnum ==", "Download {} and withENS {}\".format(download, withEns)) print(type(download)) print(type(withEns)) director =", "inputDict = {} for inarg in sys.argv[1:]: try: splitArg =", "\"withEns\"): inputDict[splitArg[0]] = splitArg[1] else: raise ValueError(\"Wrong input arguments. only", "species: print(\"===========Current Species: {}===========\".format(sp)) dbBuild = dbBuilder(sp, download=download, withEns=withEns) dbBuild.create_tables_db(merged=False)", "* from SpeciesDB import * if __name__ == \"__main__\": inputDict", "{}===========\".format(sp)) dbBuild = dbBuilder(sp, download=download, withEns=withEns) dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False) print(\"Filling {}", "download=download) director.setBuilder(orthologs) director.collectFromSource(download=download) spl = len(species) spnum = 1 for", "import * from SpeciesDB import * if __name__ == \"__main__\":", "director.setBuilder(orthologs) director.collectFromSource(download=download) spl = len(species) spnum = 1 for sp", "import sys import os sys.path.append(os.getcwd()) from Director import Director from", "for sp in species: print(\"===========Current Species: {}===========\".format(sp)) dbBuild = dbBuilder(sp,", "for inarg in sys.argv[1:]: try: splitArg = inarg.strip(\"-\").split(\"=\") if splitArg[0]", "splitArg[1] else: raise ValueError(\"Wrong input arguments. only accepts arguments 'download'", "if __name__ == \"__main__\": inputDict = {} for inarg in", "dbBuild.fill_in_db(merged=True) if spnum == spl: dbBuild.create_index() dbBuild.AddOrthology(orthologs.OrthoTable) spnum += 1", "director.collectFromSource(download=download) spl = len(species) spnum = 1 for sp in", "only accepts arguments 'download' and 'withEns'\") except AttributeError or IndexError:", "director = Director() orthologs = OrthologsBuilder(species=species, download=download) director.setBuilder(orthologs) director.collectFromSource(download=download) spl", "inarg.strip(\"-\").split(\"=\") if splitArg[0] in (\"download\", \"withEns\"): inputDict[splitArg[0]] = splitArg[1] else:", "AttributeError or IndexError: raise ValueError(\"Make sure that input arguments are", "<filename>DoChaP-db/UnusedScripts/main.py<gh_stars>1-10 #!/usr/bin/python import sys import os sys.path.append(os.getcwd()) from Director import", "'withEns'\") except AttributeError or IndexError: raise ValueError(\"Make sure that input", "= 1 for sp in species: print(\"===========Current Species: {}===========\".format(sp)) dbBuild", "'True' withEns = inputDict['withEns'] == 'True' print(\"Running DBbuilder with Download", "= OrthologsBuilder(species=species, download=download) director.setBuilder(orthologs) director.collectFromSource(download=download) spl = len(species) spnum =", "from SpeciesDB import * if __name__ == \"__main__\": inputDict =", "os sys.path.append(os.getcwd()) from Director import Director from OrthologsBuilder import *", "= inputDict['withEns'] == 'True' print(\"Running DBbuilder with Download {} and", "'X_tropicalis'] download = inputDict['download'] == 'True' withEns = inputDict['withEns'] ==", "Species: {}===========\".format(sp)) dbBuild = dbBuilder(sp, download=download, withEns=withEns) dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False) print(\"Filling", "inputDict[splitArg[0]] = splitArg[1] else: raise ValueError(\"Wrong input arguments. only accepts", "in sys.argv[1:]: try: splitArg = inarg.strip(\"-\").split(\"=\") if splitArg[0] in (\"download\",", "{}\".format(download, withEns)) print(type(download)) print(type(withEns)) director = Director() orthologs = OrthologsBuilder(species=species,", "download=download, withEns=withEns) dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False) print(\"Filling {} completed!\".format(dbBuild.dbName)) if spnum ==", "if spnum == spl: dbBuild.create_index() dbBuild.AddOrthology(orthologs.OrthoTable) spnum += 1 print(\"Filling", "IndexError: raise ValueError(\"Make sure that input arguments are argumentName=argumentValue\") species", "= splitArg[1] else: raise ValueError(\"Wrong input arguments. only accepts arguments", "orthologs = OrthologsBuilder(species=species, download=download) director.setBuilder(orthologs) director.collectFromSource(download=download) spl = len(species) spnum", "arguments are argumentName=argumentValue\") species = ['M_musculus', 'H_sapiens', 'R_norvegicus', 'D_rerio', 'X_tropicalis']", "ValueError(\"Make sure that input arguments are argumentName=argumentValue\") species = ['M_musculus',", "splitArg = inarg.strip(\"-\").split(\"=\") if splitArg[0] in (\"download\", \"withEns\"): inputDict[splitArg[0]] =", "arguments. only accepts arguments 'download' and 'withEns'\") except AttributeError or", "['M_musculus', 'H_sapiens', 'R_norvegicus', 'D_rerio', 'X_tropicalis'] download = inputDict['download'] == 'True'", "= Director() orthologs = OrthologsBuilder(species=species, download=download) director.setBuilder(orthologs) director.collectFromSource(download=download) spl =", "from OrthologsBuilder import * from SpeciesDB import * if __name__", "= ['M_musculus', 'H_sapiens', 'R_norvegicus', 'D_rerio', 'X_tropicalis'] download = inputDict['download'] ==", "Director() orthologs = OrthologsBuilder(species=species, download=download) director.setBuilder(orthologs) director.collectFromSource(download=download) spl = len(species)", "if spnum == 1: dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True) if spnum == spl:", "== spl: dbBuild.create_index() dbBuild.AddOrthology(orthologs.OrthoTable) spnum += 1 print(\"Filling {} completed!\".format(dbBuild.dbName))", "withEns=withEns) dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False) print(\"Filling {} completed!\".format(dbBuild.dbName)) if spnum == 1:", "#!/usr/bin/python import sys import os sys.path.append(os.getcwd()) from Director import Director", "withEns)) print(type(download)) print(type(withEns)) director = Director() orthologs = OrthologsBuilder(species=species, download=download)", "import * if __name__ == \"__main__\": inputDict = {} for", "from Director import Director from OrthologsBuilder import * from SpeciesDB", "inarg in sys.argv[1:]: try: splitArg = inarg.strip(\"-\").split(\"=\") if splitArg[0] in", "and 'withEns'\") except AttributeError or IndexError: raise ValueError(\"Make sure that", "except AttributeError or IndexError: raise ValueError(\"Make sure that input arguments", "print(type(withEns)) director = Director() orthologs = OrthologsBuilder(species=species, download=download) director.setBuilder(orthologs) director.collectFromSource(download=download)", "'D_rerio', 'X_tropicalis'] download = inputDict['download'] == 'True' withEns = inputDict['withEns']", "else: raise ValueError(\"Wrong input arguments. only accepts arguments 'download' and", "are argumentName=argumentValue\") species = ['M_musculus', 'H_sapiens', 'R_norvegicus', 'D_rerio', 'X_tropicalis'] download", "species = ['M_musculus', 'H_sapiens', 'R_norvegicus', 'D_rerio', 'X_tropicalis'] download = inputDict['download']", "arguments 'download' and 'withEns'\") except AttributeError or IndexError: raise ValueError(\"Make", "sys.path.append(os.getcwd()) from Director import Director from OrthologsBuilder import * from", "1: dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True) if spnum == spl: dbBuild.create_index() dbBuild.AddOrthology(orthologs.OrthoTable) spnum", "{} completed!\".format(dbBuild.dbName)) if spnum == 1: dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True) if spnum", "argumentName=argumentValue\") species = ['M_musculus', 'H_sapiens', 'R_norvegicus', 'D_rerio', 'X_tropicalis'] download =", "(\"download\", \"withEns\"): inputDict[splitArg[0]] = splitArg[1] else: raise ValueError(\"Wrong input arguments.", "'R_norvegicus', 'D_rerio', 'X_tropicalis'] download = inputDict['download'] == 'True' withEns =", "with Download {} and withENS {}\".format(download, withEns)) print(type(download)) print(type(withEns)) director", "= inputDict['download'] == 'True' withEns = inputDict['withEns'] == 'True' print(\"Running", "raise ValueError(\"Make sure that input arguments are argumentName=argumentValue\") species =", "OrthologsBuilder(species=species, download=download) director.setBuilder(orthologs) director.collectFromSource(download=download) spl = len(species) spnum = 1", "dbBuild.create_tables_db(merged=True) dbBuild.fill_in_db(merged=True) if spnum == spl: dbBuild.create_index() dbBuild.AddOrthology(orthologs.OrthoTable) spnum +=", "= dbBuilder(sp, download=download, withEns=withEns) dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False) print(\"Filling {} completed!\".format(dbBuild.dbName)) if", "dbBuilder(sp, download=download, withEns=withEns) dbBuild.create_tables_db(merged=False) dbBuild.fill_in_db(merged=False) print(\"Filling {} completed!\".format(dbBuild.dbName)) if spnum", "in species: print(\"===========Current Species: {}===========\".format(sp)) dbBuild = dbBuilder(sp, download=download, withEns=withEns)", "1 for sp in species: print(\"===========Current Species: {}===========\".format(sp)) dbBuild =", "if splitArg[0] in (\"download\", \"withEns\"): inputDict[splitArg[0]] = splitArg[1] else: raise", "'download' and 'withEns'\") except AttributeError or IndexError: raise ValueError(\"Make sure", "{} for inarg in sys.argv[1:]: try: splitArg = inarg.strip(\"-\").split(\"=\") if", "raise ValueError(\"Wrong input arguments. only accepts arguments 'download' and 'withEns'\")", "== \"__main__\": inputDict = {} for inarg in sys.argv[1:]: try:", "SpeciesDB import * if __name__ == \"__main__\": inputDict = {}", "sys.argv[1:]: try: splitArg = inarg.strip(\"-\").split(\"=\") if splitArg[0] in (\"download\", \"withEns\"):" ]
[ "https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite good_table_names = [ 'foo', '123abc', '123abc.txt', '123abc-ABC.txt', 'foo\"\"bar', '😀',", "# See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite bad_table_names = [ '\"', '\"foo\"', 'sqlite_',", "[ 'foo', '123abc', '123abc.txt', '123abc-ABC.txt', 'foo\"\"bar', '😀', '_sqlite', ] #", "'123abc-ABC.txt', 'foo\"\"bar', '😀', '_sqlite', ] # See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite bad_table_names", "See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite bad_table_names = [ '\"', '\"foo\"', 'sqlite_', 'sqlite_reserved',", "'123abc.txt', '123abc-ABC.txt', 'foo\"\"bar', '😀', '_sqlite', ] # See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite", "good_table_names = [ 'foo', '123abc', '123abc.txt', '123abc-ABC.txt', 'foo\"\"bar', '😀', '_sqlite',", "# See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite good_table_names = [ 'foo', '123abc', '123abc.txt',", "= [ 'foo', '123abc', '123abc.txt', '123abc-ABC.txt', 'foo\"\"bar', '😀', '_sqlite', ]", "] # See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite bad_table_names = [ '\"', '\"foo\"',", "'_sqlite', ] # See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite bad_table_names = [ '\"',", "'foo\"\"bar', '😀', '_sqlite', ] # See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite bad_table_names =", "'123abc', '123abc.txt', '123abc-ABC.txt', 'foo\"\"bar', '😀', '_sqlite', ] # See also:", "'😀', '_sqlite', ] # See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite bad_table_names = [", "also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite bad_table_names = [ '\"', '\"foo\"', 'sqlite_', 'sqlite_reserved', ]", "'foo', '123abc', '123abc.txt', '123abc-ABC.txt', 'foo\"\"bar', '😀', '_sqlite', ] # See", "See also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite good_table_names = [ 'foo', '123abc', '123abc.txt', '123abc-ABC.txt',", "also: https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite good_table_names = [ 'foo', '123abc', '123abc.txt', '123abc-ABC.txt', 'foo\"\"bar'," ]
[ "locale/language-data.json def get_languages_from_locale_subdirectories(dir): current_languages = [] language_data_json = open(os.path.join(dir, \"language-data.json\"))", "faker.config import AVAILABLE_LOCALES as FAKER_AVAILABLE_LOCALES # We're going to replace", "CONFIG # ------------------------------------------------------------------------------ REST_FRAMEWORK = { \"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\" } #", "django.utils.translation import gettext_lazy as _ # Import available locales from", "the environment variables indicated in the README. For more information", "db-stored # translations as low as possible while allowing translatewiki", "get better control of the # mail_admins behavior. LOGGING_CONFIG =", "for a project and will not work as one. You", "reasons. DEBUG = bool(os.environ.get(\"DEBUG\", \"False\").lower() == \"true\") # DATABASE CONFIGURATION", "this. DATABASES = { \"default\": { \"ENGINE\": \"django.db.backends.mysql\", \"NAME\": os.environ.get(\"DJANGO_DB_NAME\",", "start with 'from .base import *'; and proceed to add", "used), but before # Common. \"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", #", "== \"true\") # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/ref/settings/#databases #", "}, }, \"loggers\": { \"django\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\":", "the file-based translation contributions dictate the languages # available to", "not intended to be used as the live settings file", ") LOCALE_PATHS = [ # makemessages looks for locale/ in", "will override this. DATABASES = { \"default\": { \"ENGINE\": \"django.db.backends.mysql\",", "language set. def get_django_faker_languages_intersection(languages): languages_intersection = [] for locale in", "files should live in the settings directory; start with 'from", "indicated in the README. For more information on this file,", "get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES = get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE = \"UTC\" USE_I18N = True", "makes it untestable. Instead we decorate the Application.save(). # DJMAIL", "prefer mysql, so use that. # If you're deploying to", "\"HOST\": os.environ.get(\"DJANGO_DB_HOST\", None), \"PORT\": \"3306\", # This is critical for", "\"localhost 127.0.0.1 [::1]\").split(\" \") # Let Django know about external", "We're going to replace Django's default logging config. import logging.config", "# We cache templates by default. \"loaders\": [ ( \"django.template.loaders.cached.Loader\",", "intended to be used as the live settings file for", "works while others are broken. if ( locale == djlang_code", "for locale_dir in os.listdir(dir): if os.path.isdir(os.path.join(dir, locale_dir)): for lang_code, lang_data", "# required by django.contrib.comments ] THIRD_PARTY_APPS = [ \"annoying\", \"crispy_forms\",", "\"reversion\", \"dal\", \"dal_select2\", \"django_comments\", \"django_cron\", \"django_filters\", \"modeltranslation\", # DO NOT", "DEBUG = bool(os.environ.get(\"DEBUG\", \"False\").lower() == \"true\") # DATABASE CONFIGURATION #", "DEBUG SHOULD BE FALSE ON PRODUCTION for security reasons. DEBUG", "EZPROXY CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL = os.environ.get(\"TWLIGHT_EZPROXY_URL\", None) TWLIGHT_EZPROXY_SECRET =", "package. \"request\", \"django_countries\", \"rest_framework\", \"rest_framework.authtoken\", \"django_extensions\", ] TWLIGHT_APPS = [", "file-based translation contributions dictate the languages # available to the", "} # MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\",", "translation contributions dictate the languages # available to the system.", "for TranslateWiki integration: # https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki # Get the language codes", "\"filters\": [\"require_debug_false\"], \"class\": \"logging.StreamHandler\", }, \"debug_console\": { \"level\": \"INFO\", \"filters\":", "[\"request.middleware.RequestMiddleware\"] # The following are set for privacy purposes. Note", "# DJANGO_REQUEST CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE += [\"request.middleware.RequestMiddleware\"] # The", "= os.path.join(os.path.dirname(BASE_DIR), \"media\") MEDIA_URL = \"/media/\" # ------------------------------------------------------------------------------ # ----------------->", "creates revisions when # save() is called in the context", "current_languages = [] language_data_json = open(os.path.join(dir, \"language-data.json\")) languages = json.loads(language_data_json.read())[\"languages\"]", "= 1 # Overwrite messages.ERROR to use danger instead, to", "override this. DATABASES = { \"default\": { \"ENGINE\": \"django.db.backends.mysql\", \"NAME\":", "\"handlers\": [\"django.server\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), \"propagate\": False, }, \"TWLight\": {", "system. This keeps our column and index count for db-stored", "the # languages in Wikimedia CLDR. Use langauge autonyms from", "# We periodically pull: # https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json # into locale/language-data.json def", "following are set for privacy purposes. Note that, if some", "\"[%(server_time)s] %(message)s\", } }, \"handlers\": { \"nodebug_console\": { \"level\": \"WARNING\",", "for lang_code, lang_data in languages.items(): autonym = lang_data[-1] if locale_dir", "\"/static/\" STATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\")] STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\" # MEDIA", "= [ \"django.contrib.admin\", \"django.contrib.admindocs\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"whitenoise.runserver_nostatic\", #", "key used in production secret! SECRET_KEY = os.environ.get(\"SECRET_KEY\") # In", "# be used without reconfiguring the site. LANGUAGES = get_languages_from_locale_subdirectories(LOCALE_PATHS[0])", "\"3306\", # This is critical for handling Unicode data due", "TranslateWiki integration: # https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki # Get the language codes from", "------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/ref/settings/#databases # WMF sysadmins strongly prefer mysql, so", "from internal # Needed to be added for /admin USE_X_FORWARDED_HOST", "we decorate the Application.save(). # DJMAIL CONFIGURATION # ------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND", "# ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = \"en\" # Sets site", "LocaleMiddleware must go after Session (and Cache, if used), but", "low as possible while allowing translatewiki contributions to # be", "Heroku, heroku.py will override this. DATABASES = { \"default\": {", "}, \"TWLight\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), },", "possible while allowing translatewiki contributions to # be used without", "------------------------------------------------------------------------------ TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [os.path.join(BASE_DIR, \"templates\")],", "\"django.server\": { \"handlers\": [\"django.server\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), \"propagate\": False, },", "} ] # STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/howto/static-files/", "the # mail_admins behavior. LOGGING_CONFIG = None logging.config.dictConfig( { \"version\":", "USE_I18N = True USE_L10N = True USE_TZ = True #", "\"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\", ] TWLIGHT_OAUTH_PROVIDER_URL = os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None) TWLIGHT_OAUTH_CONSUMER_KEY = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\",", "# makemessages looks for locale/ in the top level, not", "project level. os.path.join(os.path.dirname(BASE_DIR), \"locale\") ] # We're letting the file-based", "( \"django.template.loaders.cached.Loader\", [ \"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\", ], ) ], }, }", "before # MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\", ] # DEBUG # ------------------------------------------------------------------------------ #", "# The default storage backend relies on sessions. # That’s", "= bool(os.environ.get(\"DEBUG\", \"False\").lower() == \"true\") # DATABASE CONFIGURATION # ------------------------------------------------------------------------------", "to set ALLOWED_HOSTS before your app will run. If you", "DJANGO_APPS + TWLIGHT_APPS # CRON CONFIGURATION # ------------------------------------------------------------------------------ CRON_CLASSES =", "settings, you are now done. If not, you will also", "We're letting the file-based translation contributions dictate the languages #", "it later. \"context_processors\": ( \"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\", \"django.template.context_processors.i18n\", \"django.template.context_processors.media\", \"django.template.context_processors.request\", \"django.template.context_processors.static\",", "INSTALLED_APPS += [\"djmail\"] # DJANGO_REQUEST CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE +=", "CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL = os.environ.get(\"TWLIGHT_EZPROXY_URL\", None) TWLIGHT_EZPROXY_SECRET = os.environ.get(\"TWLIGHT_EZPROXY_SECRET\",", "security reasons. For local testing '*' is OK. ALLOWED_HOSTS =", "# COMMENTS CONFIGURATION # ------------------------------------------------------------------------------ COMMENTS_APP = \"TWLight.comments\" # REVERSION", "Python URL library! This is # django-request, the user analytics", "\"class\": \"logging.StreamHandler\", }, \"django.server\": { \"level\": \"INFO\", \"class\": \"logging.StreamHandler\", \"formatter\":", "setting this an an environment variable, it is easy to", "json from django.contrib import messages from django.urls import reverse_lazy from", "\"ENGINE\": \"django.db.backends.mysql\", \"NAME\": os.environ.get(\"DJANGO_DB_NAME\", None), \"USER\": os.environ.get(\"DJANGO_DB_USER\", None), \"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\",", "= [ \"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\", ] #", "Wikimedia. # We periodically pull: # https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json # into locale/language-data.json", "full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\"", "dal (autocomplete_light) and modeltranslation must go before django.contrib.admin. INSTALLED_APPS =", "= os.environ.get(\"REQUEST_BASE_URL\", None) ROOT_URLCONF = \"TWLight.urls\" WSGI_APPLICATION = \"TWLight.wsgi.application\" SITE_ID", "[ \"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\", ], ) ], }, } ] #", "MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"media\") MEDIA_URL = \"/media/\" # ------------------------------------------------------------------------------ #", "DEBUG # ------------------------------------------------------------------------------ # By setting this an an environment", "logging config. import logging.config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME = os.path.dirname(", "LANGUAGE_CODE = \"en\" # Sets site default language. # https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings", "heroku.py, or another file that you write. These files should", "scrubs the last octet of the IP address, which could", "\"django_filters\", \"modeltranslation\", # DO NOT CONFUSE THIS with requests, the", "as low as possible while allowing translatewiki contributions to #", "= os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))) ) TWLIGHT_ENV = os.environ.get(\"TWLIGHT_ENV\") # An", "= {messages.ERROR: \"danger\"} # INTERNATIONALIZATION CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/i18n/", "\"django.template.context_processors.media\", \"django.template.context_processors.request\", \"django.template.context_processors.static\", \"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\", ), # We cache templates", "to stupid properties # of MySQL; see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django . \"OPTIONS\":", "}, \"debug_console\": { \"level\": \"INFO\", \"filters\": [\"require_debug_true\"], \"class\": \"logging.StreamHandler\", },", "\"django.core.mail.backends.console.EmailBackend\" ) EMAIL_BACKEND = \"djmail.backends.async.EmailBackend\" EMAIL_HOST = os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\") EMAIL_PORT", "os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), \"propagate\": False, }, \"TWLight\": { \"handlers\": [\"nodebug_console\", \"debug_console\"],", "# ------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT = os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None) # COMMENTS CONFIGURATION #", "# API CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT = os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None) #", "pull: # https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json # into locale/language-data.json def get_languages_from_locale_subdirectories(dir): current_languages =", "------------------------------------------------------------------------------ COMMENTS_APP = \"TWLight.comments\" # REVERSION CONFIGURATION # ------------------------------------------------------------------------------ #", "you're deploying to Heroku, heroku.py will override this. DATABASES =", "LOGGING CONFIGURATION # ------------------------------------------------------------------------------ # We're replacing the default logging", "# The following are set for privacy purposes. Note that,", "os.path.join(BASE_DIR, \"collectedstatic\") STATIC_URL = \"/static/\" STATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\")] STATICFILES_STORAGE", "# DEBUG SHOULD BE FALSE ON PRODUCTION for security reasons.", "# Get the language codes from the locale directories, and", "their context. In particular, you will need to set ALLOWED_HOSTS", "STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\" # MEDIA FILE CONFIGURATION # ------------------------------------------------------------------------------ #", "common English locales from random test selection; English often works", "if ( locale == djlang_code and locale != \"en\" and", "\"whitenoise.storage.CompressedManifestStaticFilesStorage\" # MEDIA FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT", "user analytics package. \"request\", \"django_countries\", \"rest_framework\", \"rest_framework.authtoken\", \"django_extensions\", ] TWLIGHT_APPS", "------------------------------------------------------------------------------ CRON_CLASSES = [ \"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\",", "get semi-granular user tracking (such # as tracking only authenticated", "An atypical way of setting django languages for TranslateWiki integration:", "\"django.template.context_processors.i18n\", \"django.template.context_processors.media\", \"django.template.context_processors.request\", \"django.template.context_processors.static\", \"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\", ), # We cache", "add or override settings as appropriate to their context. In", "tracking only authenticated vs anonymous users). REQUEST_LOG_IP = False REQUEST_LOG_USER", "# else, for security reasons. For local testing '*' is", "do a quick test. # DEBUG SHOULD BE FALSE ON", "= { \"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\" } # MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------", "# ------------------------------------------------------------------------------ # APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS = [", "[ \"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\", ] # REST", "= \"TWLight.wsgi.application\" SITE_ID = 1 # Overwrite messages.ERROR to use", "variables indicated in the README. For more information on this", "instead use production.py, local.py, heroku.py, or another file that you", "def get_languages_from_locale_subdirectories(dir): current_languages = [] language_data_json = open(os.path.join(dir, \"language-data.json\")) languages", "nothing # else, for security reasons. For local testing '*'", "ALLOWED_HOSTS before your app will run. If you want to", "# By setting this an an environment variable, it is", "LOGIN_REDIRECT_URL = reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS = [ \"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\", ] TWLIGHT_OAUTH_PROVIDER_URL", "1, \"disable_existing_loggers\": False, \"filters\": { \"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\": {\"()\":", "# ------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL = os.environ.get(\"TWLIGHT_EZPROXY_URL\", None) TWLIGHT_EZPROXY_SECRET = os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None)", "os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))) ) TWLIGHT_ENV = os.environ.get(\"TWLIGHT_ENV\") # An atypical", "Import available locales from Faker, so we can determine what", "= \"\" EMAIL_USE_TLS = False INSTALLED_APPS += [\"djmail\"] # DJANGO_REQUEST", "= os.environ.get(\"SECRET_KEY\") # In production, this list should contain the", "analytics package. \"request\", \"django_countries\", \"rest_framework\", \"rest_framework.authtoken\", \"django_extensions\", ] TWLIGHT_APPS =", "# DO NOT CONFUSE THIS with requests, the Python URL", "all database # saves. This makes it untestable. Instead we", "to play nice with bootstrap MESSAGE_TAGS = {messages.ERROR: \"danger\"} #", "= os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None) # OAUTH CONFIGURATION # ------------------------------------------------------------------------------ LOGIN_URL =", "\"rest_framework.authtoken\", \"django_extensions\", ] TWLIGHT_APPS = [ \"TWLight.i18n\", \"TWLight.users\", \"TWLight.resources\", \"TWLight.applications\",", "languages for TranslateWiki integration: # https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki # Get the language", "you are now done. If not, you will also need", "from django.utils.translation import gettext_lazy as _ # Import available locales", "\"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", # LocaleMiddleware must go after Session", "file for a project and will not work as one.", "os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None) TWLIGHT_OAUTH_CONSUMER_SECRET = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None) # API CONFIGURATION #", "context of some http requests, but not on all database", "This is not intended to be used as the live", "\"localhost\") EMAIL_PORT = 25 EMAIL_HOST_USER = \"\" EMAIL_HOST_PASSWORD = \"\"", "enumerate(languages): # Exclude common English locales from random test selection;", "if os.path.isdir(os.path.join(dir, locale_dir)): for lang_code, lang_data in languages.items(): autonym =", "\"annoying\", \"crispy_forms\", \"reversion\", \"dal\", \"dal_select2\", \"django_comments\", \"django_cron\", \"django_filters\", \"modeltranslation\", #", "Not a django app; replaces staticfiles \"django.contrib.staticfiles\", \"django.contrib.sites\", # required", "data due to stupid properties # of MySQL; see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django", "None) ROOT_URLCONF = \"TWLight.urls\" WSGI_APPLICATION = \"TWLight.wsgi.application\" SITE_ID = 1", "messages from django.urls import reverse_lazy from django.utils.translation import gettext_lazy as", "file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and", "= get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE = \"UTC\" USE_I18N = True USE_L10N =", "= open(os.path.join(dir, \"language-data.json\")) languages = json.loads(language_data_json.read())[\"languages\"] for locale_dir in os.listdir(dir):", "atypical way of setting django languages for TranslateWiki integration: #", "or another file that you write. These files should live", "\"TWLight.crons.ClearSessions\", ] # REST FRAMEWORK CONFIG # ------------------------------------------------------------------------------ REST_FRAMEWORK =", "languages.items(): autonym = lang_data[-1] if locale_dir == lang_code: current_languages +=", "is easy to switch debug on in # servers to", "contributions dictate the languages # available to the system. This", "the user analytics package. \"request\", \"django_countries\", \"rest_framework\", \"rest_framework.authtoken\", \"django_extensions\", ]", "the language codes from the locale directories, and compare them", "True USE_TZ = True # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ TEMPLATES", "True # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ TEMPLATES = [ {", "os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None) TWLIGHT_OAUTH_CONSUMER_KEY = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None) TWLIGHT_OAUTH_CONSUMER_SECRET = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None)", "before everything but security. \"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", # LocaleMiddleware", "\"locale\") ] # We're letting the file-based translation contributions dictate", "This makes it untestable. Instead we decorate the Application.save(). #", "Wikimedia CLDR. Use langauge autonyms from Wikimedia. # We periodically", "from the locale directories, and compare them to the #", "\"TWLight.emails\", \"TWLight.graphs\", \"TWLight.comments\", \"TWLight.api\", \"TWLight.ezproxy\", ] # dal (autocomplete_light) and", "in the README. For more information on this file, see", "determine what languages we fake in tests. from faker.config import", "\"django.contrib.sessions.middleware.SessionMiddleware\", # LocaleMiddleware must go after Session (and Cache, if", "# ------------------------------------------------------------------------------ DJANGO_APPS = [ \"django.contrib.admin\", \"django.contrib.admindocs\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\",", "site default language. # https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE = ( LANGUAGE_CODE #", "with bootstrap MESSAGE_TAGS = {messages.ERROR: \"danger\"} # INTERNATIONALIZATION CONFIGURATION #", "# ------------------------------------------------------------------------------ LOGIN_URL = reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL = reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS =", "a REQUEST_ANONYMOUS_IP setting which # scrubs the last octet of", "os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\") EMAIL_PORT = 25 EMAIL_HOST_USER = \"\" EMAIL_HOST_PASSWORD =", "relies on sessions. # That’s why SessionMiddleware must be enabled", "# -----------------> third-party and TWLight configurations <------------------- # ------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK", "{ \"level\": \"INFO\", \"filters\": [\"require_debug_true\"], \"class\": \"logging.StreamHandler\", }, \"django.server\": {", "\"TWLight.ezproxy\", ] # dal (autocomplete_light) and modeltranslation must go before", "+= [locale] return sorted(set(languages_intersection)) # ------------------------------------------------------------------------------ # ------------------------> core django", "the live settings file for a project and will not", "critical for handling Unicode data due to stupid properties #", "'*' is OK. ALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"localhost 127.0.0.1 [::1]\").split(\" \")", "on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of", "authenticated vs anonymous users). REQUEST_LOG_IP = False REQUEST_LOG_USER = False", "TWLIGHT_OAUTH_PROVIDER_URL = os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None) TWLIGHT_OAUTH_CONSUMER_KEY = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None) TWLIGHT_OAUTH_CONSUMER_SECRET =", "None) TWLIGHT_EZPROXY_SECRET = os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None) # OAUTH CONFIGURATION # ------------------------------------------------------------------------------", "there is a REQUEST_ANONYMOUS_IP setting which # scrubs the last", "index count for db-stored # translations as low as possible", "TWLIGHT_OAUTH_CONSUMER_KEY = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None) TWLIGHT_OAUTH_CONSUMER_SECRET = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None) # API", "\"level\": \"WARNING\", \"filters\": [\"require_debug_false\"], \"class\": \"logging.StreamHandler\", }, \"debug_console\": { \"level\":", "\") # Let Django know about external URLs in case", "THIS with requests, the Python URL library! This is #", "privacy purposes. Note that, if some amount of # geographic", "broken. if ( locale == djlang_code and locale != \"en\"", "internal # Needed to be added for /admin USE_X_FORWARDED_HOST =", "\"django_comments\", \"django_cron\", \"django_filters\", \"modeltranslation\", # DO NOT CONFUSE THIS with", "messages.ERROR to use danger instead, to play nice with bootstrap", "= True USE_L10N = True USE_TZ = True # TEMPLATE", "\"PORT\": \"3306\", # This is critical for handling Unicode data", "instead, to play nice with bootstrap MESSAGE_TAGS = {messages.ERROR: \"danger\"}", "\"utf8mb4\", \"init_command\": \"SET sql_mode='STRICT_ALL_TABLES'; SET storage_engine='INNODB';\", }, } } #", "configurations <------------------------ # ------------------------------------------------------------------------------ # APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS", "and index count for db-stored # translations as low as", "# Overwrite messages.ERROR to use danger instead, to play nice", "Base settings for twlight project. This is not intended to", "\"TWLight.graphs\", \"TWLight.comments\", \"TWLight.api\", \"TWLight.ezproxy\", ] # dal (autocomplete_light) and modeltranslation", "[os.path.join(BASE_DIR, \"static\")] STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\" # MEDIA FILE CONFIGURATION #", "config. import logging.config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME = os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__),", "the Application.save(). # DJMAIL CONFIGURATION # ------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND = os.environ.get(", "in the top level, not the project level. os.path.join(os.path.dirname(BASE_DIR), \"locale\")", "import json from django.contrib import messages from django.urls import reverse_lazy", "None) # OAUTH CONFIGURATION # ------------------------------------------------------------------------------ LOGIN_URL = reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL", "server and nothing # else, for security reasons. For local", "cache templates by default. \"loaders\": [ ( \"django.template.loaders.cached.Loader\", [ \"django.template.loaders.filesystem.Loader\",", "Session (and Cache, if used), but before # Common. \"django.middleware.locale.LocaleMiddleware\",", "to switch debug on in # servers to do a", "of setting django languages for TranslateWiki integration: # https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki #", "EMAIL_HOST_USER = \"\" EMAIL_HOST_PASSWORD = \"\" EMAIL_USE_TLS = False INSTALLED_APPS", "and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\" import os import json", "the default so we can add to it later. \"context_processors\":", "use danger instead, to play nice with bootstrap MESSAGE_TAGS =", "users). REQUEST_LOG_IP = False REQUEST_LOG_USER = False # LOGGING CONFIGURATION", "SECRET_KEY = os.environ.get(\"SECRET_KEY\") # In production, this list should contain", "storage backend relies on sessions. # That’s why SessionMiddleware must", "default language. # https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE = ( LANGUAGE_CODE # sets", "\"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\", ], ) ], }, } ] # STATIC", "list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\" import", "\"debug_console\": { \"level\": \"INFO\", \"filters\": [\"require_debug_true\"], \"class\": \"logging.StreamHandler\", }, \"django.server\":", "# of MySQL; see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django . \"OPTIONS\": { \"charset\": \"utf8mb4\",", "djlang_name) in enumerate(languages): # Exclude common English locales from random", "integration: # https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki # Get the language codes from the", "testing '*' is OK. ALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"localhost 127.0.0.1 [::1]\").split(\"", "override settings as appropriate to their context. In particular, you", "http requests, but not on all database # saves. This", "of the # mail_admins behavior. LOGGING_CONFIG = None logging.config.dictConfig( {", "\"django.server\", }, }, \"loggers\": { \"django\": { \"handlers\": [\"nodebug_console\", \"debug_console\"],", "this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings", "properties # of MySQL; see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django . \"OPTIONS\": { \"charset\":", "that you write. These files should live in the settings", "# into locale/language-data.json def get_languages_from_locale_subdirectories(dir): current_languages = [] language_data_json =", "# We're going to replace Django's default logging config. import", "\"modeltranslation\", # DO NOT CONFUSE THIS with requests, the Python", "# https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = \"en\" # Sets site default language.", "reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL = reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS = [ \"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\", ]", "to do a quick test. # DEBUG SHOULD BE FALSE", "] # DEBUG # ------------------------------------------------------------------------------ # By setting this an", "<filename>TWLight/settings/base.py # -*- coding: utf-8 -*- \"\"\" Base settings for", "# Reiterating the default so we can add to it", "as _ # Import available locales from Faker, so we", "autonym = lang_data[-1] if locale_dir == lang_code: current_languages += [(lang_code,", "tracking (such # as tracking only authenticated vs anonymous users).", "\"INFO\"), \"propagate\": False, }, \"TWLight\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\":", "= \"/static/\" STATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\")] STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\" #", "for db-stored # translations as low as possible while allowing", "------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT = os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None) # COMMENTS CONFIGURATION # ------------------------------------------------------------------------------", "\"django.contrib.sessions\", \"django.contrib.messages\", \"whitenoise.runserver_nostatic\", # Not a django app; replaces staticfiles", "\"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\" } # MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE =", "# DJMAIL CONFIGURATION # ------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND = os.environ.get( \"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\"", "{ \"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\" } # MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE", "= [] for locale in FAKER_AVAILABLE_LOCALES: for i, (djlang_code, djlang_name)", "INTERNATIONALIZATION CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = \"en\" #", "Application.save(). # DJMAIL CONFIGURATION # ------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND = os.environ.get( \"DJANGO_EMAIL_BACKEND\",", "with requests, the Python URL library! This is # django-request,", "-----------------> third-party and TWLight configurations <------------------- # ------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK =", "config to get better control of the # mail_admins behavior.", "random test selection; English often works while others are broken.", "= \"TWLight.urls\" WSGI_APPLICATION = \"TWLight.wsgi.application\" SITE_ID = 1 # Overwrite", "[ ( \"django.template.loaders.cached.Loader\", [ \"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\", ], ) ], },", "a way to get semi-granular user tracking (such # as", "for i, (djlang_code, djlang_name) in enumerate(languages): # Exclude common English", "+= [(lang_code, autonym)] return sorted(set(current_languages)) # Get the intersection of", "= False REQUEST_LOG_USER = False # LOGGING CONFIGURATION # ------------------------------------------------------------------------------", "the Python URL library! This is # django-request, the user", "play nice with bootstrap MESSAGE_TAGS = {messages.ERROR: \"danger\"} # INTERNATIONALIZATION", "APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS = [ \"django.contrib.admin\", \"django.contrib.admindocs\", \"django.contrib.auth\",", ".base import *'; and proceed to add or override settings", "\"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\", None), \"HOST\": os.environ.get(\"DJANGO_DB_HOST\", None), \"PORT\": \"3306\", # This", "\"django.server\": { \"level\": \"INFO\", \"class\": \"logging.StreamHandler\", \"formatter\": \"django.server\", }, },", "{ \"nodebug_console\": { \"level\": \"WARNING\", \"filters\": [\"require_debug_false\"], \"class\": \"logging.StreamHandler\", },", "information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list", "# We are NOT using reversion middleware, because that creates", "\"TWLight.wsgi.application\" SITE_ID = 1 # Overwrite messages.ERROR to use danger", "for privacy purposes. Note that, if some amount of #", "decorate the Application.save(). # DJMAIL CONFIGURATION # ------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND =", "Faker locales and the specified language set. def get_django_faker_languages_intersection(languages): languages_intersection", "\"SET sql_mode='STRICT_ALL_TABLES'; SET storage_engine='INNODB';\", }, } } # GENERAL CONFIGURATION", "== djlang_code and locale != \"en\" and locale != \"en_US\"", "locales from random test selection; English often works while others", "\"filters\": [\"require_debug_true\"], \"class\": \"logging.StreamHandler\", }, \"django.server\": { \"level\": \"INFO\", \"class\":", "from random test selection; English often works while others are", "}, \"django.server\": { \"level\": \"INFO\", \"class\": \"logging.StreamHandler\", \"formatter\": \"django.server\", },", "os.environ.get(\"DJANGO_DB_PASSWORD\", None), \"HOST\": os.environ.get(\"DJANGO_DB_HOST\", None), \"PORT\": \"3306\", # This is", "DJANGO_REQUEST CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE += [\"request.middleware.RequestMiddleware\"] # The following", "# as tracking only authenticated vs anonymous users). REQUEST_LOG_IP =", "# STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT =", "------------------------------------------------------------------------------ LOGIN_URL = reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL = reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS = [", "# dal (autocomplete_light) and modeltranslation must go before django.contrib.admin. INSTALLED_APPS", "django.contrib.comments ] THIRD_PARTY_APPS = [ \"annoying\", \"crispy_forms\", \"reversion\", \"dal\", \"dal_select2\",", "intersection of available Faker locales and the specified language set.", "# An atypical way of setting django languages for TranslateWiki", "[os.path.join(BASE_DIR, \"templates\")], \"OPTIONS\": { # Reiterating the default so we", "keep the secret key used in production secret! SECRET_KEY =", "CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/ref/settings/#databases # WMF sysadmins strongly prefer", "values, see https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\" import os import json from django.contrib", "\"crispy_forms\", \"reversion\", \"dal\", \"dal_select2\", \"django_comments\", \"django_cron\", \"django_filters\", \"modeltranslation\", # DO", "locales from Faker, so we can determine what languages we", "= os.environ.get( \"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\" ) EMAIL_BACKEND = \"djmail.backends.async.EmailBackend\" EMAIL_HOST =", "database # saves. This makes it untestable. Instead we decorate", "return sorted(set(languages_intersection)) # ------------------------------------------------------------------------------ # ------------------------> core django configurations <------------------------", "another file that you write. These files should live in", "by default. \"loaders\": [ ( \"django.template.loaders.cached.Loader\", [ \"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\", ],", "\"en\" # Sets site default language. # https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE =", "(djlang_code, djlang_name) in enumerate(languages): # Exclude common English locales from", "https://docs.djangoproject.com/en/1.8/ref/settings/#databases # WMF sysadmins strongly prefer mysql, so use that.", "local testing '*' is OK. ALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"localhost 127.0.0.1", "# save() is called in the context of some http", "# Needed to be added for /admin USE_X_FORWARDED_HOST = True", "directory; start with 'from .base import *'; and proceed to", "on sessions. # That’s why SessionMiddleware must be enabled and", "amount of # geographic tracking is desired, there is a", "in os.listdir(dir): if os.path.isdir(os.path.join(dir, locale_dir)): for lang_code, lang_data in languages.items():", "DJMAIL CONFIGURATION # ------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND = os.environ.get( \"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\" )", "FRAMEWORK CONFIG # ------------------------------------------------------------------------------ REST_FRAMEWORK = { \"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\" }", "languages = json.loads(language_data_json.read())[\"languages\"] for locale_dir in os.listdir(dir): if os.path.isdir(os.path.join(dir, locale_dir)):", "[ \"django.contrib.admin\", \"django.contrib.admindocs\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"whitenoise.runserver_nostatic\", # Not", "The default storage backend relies on sessions. # That’s why", "README. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For", "is not intended to be used as the live settings", "os.environ.get(\"SECRET_KEY\") # In production, this list should contain the URL", "\"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", # LocaleMiddleware must go after Session (and Cache,", "os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None) # COMMENTS CONFIGURATION # ------------------------------------------------------------------------------ COMMENTS_APP = \"TWLight.comments\"", "what languages we fake in tests. from faker.config import AVAILABLE_LOCALES", "# Common. \"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", # The default storage", "\"level\": \"INFO\", \"class\": \"logging.StreamHandler\", \"formatter\": \"django.server\", }, }, \"loggers\": {", "i, (djlang_code, djlang_name) in enumerate(languages): # Exclude common English locales", "are NOT using reversion middleware, because that creates revisions when", "Get the intersection of available Faker locales and the specified", "CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, \"collectedstatic\") STATIC_URL", "-*- coding: utf-8 -*- \"\"\" Base settings for twlight project.", "\"default\": { \"ENGINE\": \"django.db.backends.mysql\", \"NAME\": os.environ.get(\"DJANGO_DB_NAME\", None), \"USER\": os.environ.get(\"DJANGO_DB_USER\", None),", "the secret key used in production secret! SECRET_KEY = os.environ.get(\"SECRET_KEY\")", "easy to switch debug on in # servers to do", "sysadmins strongly prefer mysql, so use that. # If you're", ") EMAIL_BACKEND = \"djmail.backends.async.EmailBackend\" EMAIL_HOST = os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\") EMAIL_PORT =", "sets the modeltranslation default language. ) LOCALE_PATHS = [ #", ". # We are NOT using reversion middleware, because that", "CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS = [ \"django.contrib.admin\", \"django.contrib.admindocs\", \"django.contrib.auth\", \"django.contrib.contenttypes\",", "\"danger\"} # INTERNATIONALIZATION CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE =", "= \"/media/\" # ------------------------------------------------------------------------------ # -----------------> third-party and TWLight configurations", "\"en\" and locale != \"en_US\" and locale != \"en_GB\" ):", "app; replaces staticfiles \"django.contrib.staticfiles\", \"django.contrib.sites\", # required by django.contrib.comments ]", "{ \"django\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), },", "*'; and proceed to add or override settings as appropriate", "REQUEST_LOG_IP = False REQUEST_LOG_USER = False # LOGGING CONFIGURATION #", "] # We're letting the file-based translation contributions dictate the", "------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"media\") MEDIA_URL = \"/media/\"", "\"language-data.json\")) languages = json.loads(language_data_json.read())[\"languages\"] for locale_dir in os.listdir(dir): if os.path.isdir(os.path.join(dir,", "default. \"loaders\": [ ( \"django.template.loaders.cached.Loader\", [ \"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\", ], )", "STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR,", "language. # https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE = ( LANGUAGE_CODE # sets the", "settings as appropriate to their context. In particular, you will", "to replace Django's default logging config. import logging.config BASE_DIR =", "{ \"ENGINE\": \"django.db.backends.mysql\", \"NAME\": os.environ.get(\"DJANGO_DB_NAME\", None), \"USER\": os.environ.get(\"DJANGO_DB_USER\", None), \"PASSWORD\":", "MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", # WhiteNoise", "and appear before # MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\", ] # DEBUG #", "None) TWLIGHT_OAUTH_CONSUMER_SECRET = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None) # API CONFIGURATION # ------------------------------------------------------------------------------", "use production.py, local.py, heroku.py, or another file that you write.", "\"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"whitenoise.runserver_nostatic\", # Not a django app; replaces", "the locale directories, and compare them to the # languages", "twlight project. This is not intended to be used as", "local.py, heroku.py, or another file that you write. These files", "see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django . \"OPTIONS\": { \"charset\": \"utf8mb4\", \"init_command\": \"SET sql_mode='STRICT_ALL_TABLES';", "semi-granular user tracking (such # as tracking only authenticated vs", "os.environ.get(\"DJANGO_DB_NAME\", None), \"USER\": os.environ.get(\"DJANGO_DB_USER\", None), \"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\", None), \"HOST\": os.environ.get(\"DJANGO_DB_HOST\",", "EMAIL_USE_TLS = False INSTALLED_APPS += [\"djmail\"] # DJANGO_REQUEST CONFIGURATION #", "are broken. if ( locale == djlang_code and locale !=", "site. LANGUAGES = get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES = get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE = \"UTC\"", "If you want to use production settings, you are now", "# https://docs.djangoproject.com/en/1.8/ref/settings/#databases # WMF sysadmins strongly prefer mysql, so use", "will need to set ALLOWED_HOSTS before your app will run.", "makemessages looks for locale/ in the top level, not the", "os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None) # OAUTH CONFIGURATION # ------------------------------------------------------------------------------ LOGIN_URL = reverse_lazy(\"oauth_login\")", "= True # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ TEMPLATES = [", "MESSAGE_TAGS = {messages.ERROR: \"danger\"} # INTERNATIONALIZATION CONFIGURATION # ------------------------------------------------------------------------------ #", "the settings directory; start with 'from .base import *'; and", "way of setting django languages for TranslateWiki integration: # https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki", "\"TWLight.api\", \"TWLight.ezproxy\", ] # dal (autocomplete_light) and modeltranslation must go", "\"collectedstatic\") STATIC_URL = \"/static/\" STATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\")] STATICFILES_STORAGE =", "= os.path.join(BASE_DIR, \"collectedstatic\") STATIC_URL = \"/static/\" STATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\")]", "can add to it later. \"context_processors\": ( \"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\", \"django.template.context_processors.i18n\",", "to # be used without reconfiguring the site. LANGUAGES =", "and will not work as one. You should instead use", "# ------------------------> core django configurations <------------------------ # ------------------------------------------------------------------------------ # APP", "TWLIGHT_EZPROXY_SECRET = os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None) # OAUTH CONFIGURATION # ------------------------------------------------------------------------------ LOGIN_URL", "an environment variable, it is easy to switch debug on", "default logging config. import logging.config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME =", "\"formatter\": \"django.server\", }, }, \"loggers\": { \"django\": { \"handlers\": [\"nodebug_console\",", "in languages.items(): autonym = lang_data[-1] if locale_dir == lang_code: current_languages", "# CRON CONFIGURATION # ------------------------------------------------------------------------------ CRON_CLASSES = [ \"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\",", "API CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT = os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None) # COMMENTS", "debug on in # servers to do a quick test.", "REQUEST_BASE_URL = os.environ.get(\"REQUEST_BASE_URL\", None) ROOT_URLCONF = \"TWLight.urls\" WSGI_APPLICATION = \"TWLight.wsgi.application\"", "TWLIGHT_APPS # CRON CONFIGURATION # ------------------------------------------------------------------------------ CRON_CLASSES = [ \"TWLight.crons.BackupCronJob\",", "of the server and nothing # else, for security reasons.", "lang_data[-1] if locale_dir == lang_code: current_languages += [(lang_code, autonym)] return", "not, you will also need to set the environment variables", "[::1]\").split(\" \") # Let Django know about external URLs in", "# Sets site default language. # https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE = (", ") TWLIGHT_ENV = os.environ.get(\"TWLIGHT_ENV\") # An atypical way of setting", "reversion middleware, because that creates revisions when # save() is", "os.path.join(os.path.dirname(BASE_DIR), \"locale\") ] # We're letting the file-based translation contributions", "EMAIL_HOST = os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\") EMAIL_PORT = 25 EMAIL_HOST_USER = \"\"", "SessionMiddleware must be enabled and appear before # MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\",", "= os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None) TWLIGHT_OAUTH_CONSUMER_KEY = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None) TWLIGHT_OAUTH_CONSUMER_SECRET = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\",", "MySQL; see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django . \"OPTIONS\": { \"charset\": \"utf8mb4\", \"init_command\": \"SET", "differ from internal # Needed to be added for /admin", "{\"()\": \"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\": {\"()\": \"django.utils.log.RequireDebugTrue\"}, }, \"formatters\": { \"django.server\": {", "logging.config.dictConfig( { \"version\": 1, \"disable_existing_loggers\": False, \"filters\": { \"require_debug_false\": {\"()\":", "\"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\", ), # We cache templates by default. \"loaders\":", "Get the language codes from the locale directories, and compare", "False REQUEST_LOG_USER = False # LOGGING CONFIGURATION # ------------------------------------------------------------------------------ #", "WSGI_APPLICATION = \"TWLight.wsgi.application\" SITE_ID = 1 # Overwrite messages.ERROR to", "\"django.contrib.staticfiles\", \"django.contrib.sites\", # required by django.contrib.comments ] THIRD_PARTY_APPS = [", "CRON_CLASSES = [ \"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\", ]", "a django app; replaces staticfiles \"django.contrib.staticfiles\", \"django.contrib.sites\", # required by", "# ------------------------------------------------------------------------------ MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", # WhiteNoise should be", "# ------------------------------------------------------------------------------ MIDDLEWARE += [\"request.middleware.RequestMiddleware\"] # The following are set", "to use danger instead, to play nice with bootstrap MESSAGE_TAGS", "DJANGO_APPS = [ \"django.contrib.admin\", \"django.contrib.admindocs\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"whitenoise.runserver_nostatic\",", "USE_L10N = True USE_TZ = True # TEMPLATE CONFIGURATION #", "the languages # available to the system. This keeps our", "\"django.contrib.sites\", # required by django.contrib.comments ] THIRD_PARTY_APPS = [ \"annoying\",", "\"django.utils.log.RequireDebugTrue\"}, }, \"formatters\": { \"django.server\": { \"()\": \"django.utils.log.ServerFormatter\", \"format\": \"[%(server_time)s]", "instead of # REQUEST_LOG_IP. There is not a way to", "# If you're deploying to Heroku, heroku.py will override this.", "}, } ] # STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ #", "everything but security. \"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", # LocaleMiddleware must", "by django.contrib.comments ] THIRD_PARTY_APPS = [ \"annoying\", \"crispy_forms\", \"reversion\", \"dal\",", "reconfiguring the site. LANGUAGES = get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES = get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE", "------------------------------------------------------------------------------ # SECURITY WARNING: keep the secret key used in", "can determine what languages we fake in tests. from faker.config", "lang_code, lang_data in languages.items(): autonym = lang_data[-1] if locale_dir ==", "settings directory; start with 'from .base import *'; and proceed", "mysql, so use that. # If you're deploying to Heroku,", "}, \"formatters\": { \"django.server\": { \"()\": \"django.utils.log.ServerFormatter\", \"format\": \"[%(server_time)s] %(message)s\",", "{ \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [os.path.join(BASE_DIR, \"templates\")], \"OPTIONS\": { # Reiterating", "so we can add to it later. \"context_processors\": ( \"django.contrib.auth.context_processors.auth\",", "of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\" import os", "= os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\") EMAIL_PORT = 25 EMAIL_HOST_USER = \"\" EMAIL_HOST_PASSWORD", "we can determine what languages we fake in tests. from", "FALSE ON PRODUCTION for security reasons. DEBUG = bool(os.environ.get(\"DEBUG\", \"False\").lower()", "\"logging.StreamHandler\", }, \"django.server\": { \"level\": \"INFO\", \"class\": \"logging.StreamHandler\", \"formatter\": \"django.server\",", "their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\" import os import json from", "!= \"en\" and locale != \"en_US\" and locale != \"en_GB\"", "sorted(set(current_languages)) # Get the intersection of available Faker locales and", "[ \"django.middleware.security.SecurityMiddleware\", # WhiteNoise should be loaded before everything but", "\"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, \"django.server\": { \"handlers\": [\"django.server\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\",", "be used instead of # REQUEST_LOG_IP. There is not a", "os.pardir))) ) TWLIGHT_ENV = os.environ.get(\"TWLIGHT_ENV\") # An atypical way of", "TWLIGHT_OAUTH_CONSUMER_SECRET = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None) # API CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT", "security reasons. DEBUG = bool(os.environ.get(\"DEBUG\", \"False\").lower() == \"true\") # DATABASE", "os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME = os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))) ) TWLIGHT_ENV = os.environ.get(\"TWLIGHT_ENV\")", "lang_data in languages.items(): autonym = lang_data[-1] if locale_dir == lang_code:", "TWLight configurations <------------------- # ------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK = \"bootstrap3\" # EZPROXY", "LANGUAGES = get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES = get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE = \"UTC\" USE_I18N", "# ------------------------------------------------------------------------------ REST_FRAMEWORK = { \"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\" } # MIDDLEWARE", "user tracking (such # as tracking only authenticated vs anonymous", "\"request\", \"django_countries\", \"rest_framework\", \"rest_framework.authtoken\", \"django_extensions\", ] TWLIGHT_APPS = [ \"TWLight.i18n\",", "------------------------------------------------------------------------------ # APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS = [ \"django.contrib.admin\",", "!= \"en_US\" and locale != \"en_GB\" ): languages_intersection += [locale]", "of MySQL; see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django . \"OPTIONS\": { \"charset\": \"utf8mb4\", \"init_command\":", "to be used as the live settings file for a", "INSTALLED_APPS = THIRD_PARTY_APPS + DJANGO_APPS + TWLIGHT_APPS # CRON CONFIGURATION", "gettext_lazy as _ # Import available locales from Faker, so", "# scrubs the last octet of the IP address, which", "TWLIGHT_ENV = os.environ.get(\"TWLIGHT_ENV\") # An atypical way of setting django", "# translations as low as possible while allowing translatewiki contributions", "the intersection of available Faker locales and the specified language", "case they differ from internal # Needed to be added", "+ DJANGO_APPS + TWLIGHT_APPS # CRON CONFIGURATION # ------------------------------------------------------------------------------ CRON_CLASSES", "WhiteNoise should be loaded before everything but security. \"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\",", "\"django.middleware.security.SecurityMiddleware\", # WhiteNoise should be loaded before everything but security.", "THIRD_PARTY_APPS = [ \"annoying\", \"crispy_forms\", \"reversion\", \"dal\", \"dal_select2\", \"django_comments\", \"django_cron\",", "os.path.join(os.path.dirname(BASE_DIR), \"media\") MEDIA_URL = \"/media/\" # ------------------------------------------------------------------------------ # -----------------> third-party", "we fake in tests. from faker.config import AVAILABLE_LOCALES as FAKER_AVAILABLE_LOCALES", "to add or override settings as appropriate to their context.", "= None logging.config.dictConfig( { \"version\": 1, \"disable_existing_loggers\": False, \"filters\": {", "codes from the locale directories, and compare them to the", "set for privacy purposes. Note that, if some amount of", ") ], }, } ] # STATIC FILE CONFIGURATION #", "staticfiles \"django.contrib.staticfiles\", \"django.contrib.sites\", # required by django.contrib.comments ] THIRD_PARTY_APPS =", "# MEDIA FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT =", "else, for security reasons. For local testing '*' is OK.", "the modeltranslation default language. ) LOCALE_PATHS = [ # makemessages", "REQUEST_ANONYMOUS_IP setting which # scrubs the last octet of the", "the README. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/", "TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",", "TWLIGHT_APPS = [ \"TWLight.i18n\", \"TWLight.users\", \"TWLight.resources\", \"TWLight.applications\", \"TWLight.emails\", \"TWLight.graphs\", \"TWLight.comments\",", "Django know about external URLs in case they differ from", "That’s why SessionMiddleware must be enabled and appear before #", "[ # makemessages looks for locale/ in the top level,", "DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/ref/settings/#databases # WMF sysadmins strongly", "] TWLIGHT_APPS = [ \"TWLight.i18n\", \"TWLight.users\", \"TWLight.resources\", \"TWLight.applications\", \"TWLight.emails\", \"TWLight.graphs\",", "\"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\", ] # REST FRAMEWORK", "\"TWLight.resources\", \"TWLight.applications\", \"TWLight.emails\", \"TWLight.graphs\", \"TWLight.comments\", \"TWLight.api\", \"TWLight.ezproxy\", ] # dal", "SECURITY WARNING: keep the secret key used in production secret!", "https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values,", "modeltranslation must go before django.contrib.admin. INSTALLED_APPS = THIRD_PARTY_APPS + DJANGO_APPS", "\"django_cron\", \"django_filters\", \"modeltranslation\", # DO NOT CONFUSE THIS with requests,", "{ \"level\": \"INFO\", \"class\": \"logging.StreamHandler\", \"formatter\": \"django.server\", }, }, \"loggers\":", "# See https://django-reversion.readthedocs.org/ . # We are NOT using reversion", "must go after Session (and Cache, if used), but before", "STATIC_URL = \"/static/\" STATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\")] STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\"", "# ------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND = os.environ.get( \"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\" ) EMAIL_BACKEND =", "autonym)] return sorted(set(current_languages)) # Get the intersection of available Faker", "CRON CONFIGURATION # ------------------------------------------------------------------------------ CRON_CLASSES = [ \"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\",", "languages_intersection = [] for locale in FAKER_AVAILABLE_LOCALES: for i, (djlang_code,", "quick test. # DEBUG SHOULD BE FALSE ON PRODUCTION for", "tracking is desired, there is a REQUEST_ANONYMOUS_IP setting which #", "[\"django.server\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), \"propagate\": False, }, \"TWLight\": { \"handlers\":", "{ \"default\": { \"ENGINE\": \"django.db.backends.mysql\", \"NAME\": os.environ.get(\"DJANGO_DB_NAME\", None), \"USER\": os.environ.get(\"DJANGO_DB_USER\",", "replace Django's default logging config. import logging.config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))", "get_languages_from_locale_subdirectories(dir): current_languages = [] language_data_json = open(os.path.join(dir, \"language-data.json\")) languages =", "English often works while others are broken. if ( locale", "https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json # into locale/language-data.json def get_languages_from_locale_subdirectories(dir): current_languages = [] language_data_json", "# REQUEST_LOG_IP. There is not a way to get semi-granular", "\"disable_existing_loggers\": False, \"filters\": { \"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\": {\"()\": \"django.utils.log.RequireDebugTrue\"},", "}, \"django.server\": { \"handlers\": [\"django.server\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), \"propagate\": False,", "------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL = os.environ.get(\"TWLIGHT_EZPROXY_URL\", None) TWLIGHT_EZPROXY_SECRET = os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None) #", "should live in the settings directory; start with 'from .base", "\"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", # The default storage backend relies on", "you want to use production settings, you are now done.", "], }, } ] # STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------", "Instead we decorate the Application.save(). # DJMAIL CONFIGURATION # ------------------------------------------------------------------------------", "] # dal (autocomplete_light) and modeltranslation must go before django.contrib.admin.", "# servers to do a quick test. # DEBUG SHOULD", "EMAIL_PORT = 25 EMAIL_HOST_USER = \"\" EMAIL_HOST_PASSWORD = \"\" EMAIL_USE_TLS", "locale != \"en_GB\" ): languages_intersection += [locale] return sorted(set(languages_intersection)) #", "will also need to set the environment variables indicated in", "lang_code: current_languages += [(lang_code, autonym)] return sorted(set(current_languages)) # Get the", "while allowing translatewiki contributions to # be used without reconfiguring", "more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full", "[ \"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\", ] TWLIGHT_OAUTH_PROVIDER_URL = os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None) TWLIGHT_OAUTH_CONSUMER_KEY =", "used instead of # REQUEST_LOG_IP. There is not a way", "None), \"USER\": os.environ.get(\"DJANGO_DB_USER\", None), \"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\", None), \"HOST\": os.environ.get(\"DJANGO_DB_HOST\", None),", "in the context of some http requests, but not on", "False, \"filters\": { \"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\": {\"()\": \"django.utils.log.RequireDebugTrue\"}, },", "letting the file-based translation contributions dictate the languages # available", "the server and nothing # else, for security reasons. For", "EMAIL_HOST_PASSWORD = \"\" EMAIL_USE_TLS = False INSTALLED_APPS += [\"djmail\"] #", "logging config to get better control of the # mail_admins", "production secret! SECRET_KEY = os.environ.get(\"SECRET_KEY\") # In production, this list", "storage_engine='INNODB';\", }, } } # GENERAL CONFIGURATION # ------------------------------------------------------------------------------ #", "the project level. os.path.join(os.path.dirname(BASE_DIR), \"locale\") ] # We're letting the", "\"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\": {\"()\": \"django.utils.log.RequireDebugTrue\"}, }, \"formatters\": { \"django.server\": { \"()\":", "django.urls import reverse_lazy from django.utils.translation import gettext_lazy as _ #", "and locale != \"en\" and locale != \"en_US\" and locale", "os.environ.get(\"TWLIGHT_ENV\") # An atypical way of setting django languages for", "(and Cache, if used), but before # Common. \"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\",", "# SECURITY WARNING: keep the secret key used in production", "os.listdir(dir): if os.path.isdir(os.path.join(dir, locale_dir)): for lang_code, lang_data in languages.items(): autonym", "\"whitenoise.runserver_nostatic\", # Not a django app; replaces staticfiles \"django.contrib.staticfiles\", \"django.contrib.sites\",", "\"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", # The default storage backend relies", "( \"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\", \"django.template.context_processors.i18n\", \"django.template.context_processors.media\", \"django.template.context_processors.request\", \"django.template.context_processors.static\", \"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\", ),", "{ \"()\": \"django.utils.log.ServerFormatter\", \"format\": \"[%(server_time)s] %(message)s\", } }, \"handlers\": {", "fake in tests. from faker.config import AVAILABLE_LOCALES as FAKER_AVAILABLE_LOCALES #", "must be enabled and appear before # MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\", ]", "column and index count for db-stored # translations as low", "mail_admins behavior. LOGGING_CONFIG = None logging.config.dictConfig( { \"version\": 1, \"disable_existing_loggers\":", "\"TWLight.urls\" WSGI_APPLICATION = \"TWLight.wsgi.application\" SITE_ID = 1 # Overwrite messages.ERROR", "are set for privacy purposes. Note that, if some amount", "= [ # makemessages looks for locale/ in the top", "to set the environment variables indicated in the README. For", "as one. You should instead use production.py, local.py, heroku.py, or", "the specified language set. def get_django_faker_languages_intersection(languages): languages_intersection = [] for", "should contain the URL of the server and nothing #", "untestable. Instead we decorate the Application.save(). # DJMAIL CONFIGURATION #", "We are NOT using reversion middleware, because that creates revisions", "], ) ], }, } ] # STATIC FILE CONFIGURATION", "None), \"HOST\": os.environ.get(\"DJANGO_DB_HOST\", None), \"PORT\": \"3306\", # This is critical", "\"\"\" Base settings for twlight project. This is not intended", "= os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None) TWLIGHT_OAUTH_CONSUMER_SECRET = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None) # API CONFIGURATION", "] # STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT", "This is # django-request, the user analytics package. \"request\", \"django_countries\",", "in tests. from faker.config import AVAILABLE_LOCALES as FAKER_AVAILABLE_LOCALES # We're", "as the live settings file for a project and will", "after Session (and Cache, if used), but before # Common.", "1 # Overwrite messages.ERROR to use danger instead, to play", "go before django.contrib.admin. INSTALLED_APPS = THIRD_PARTY_APPS + DJANGO_APPS + TWLIGHT_APPS", "= \"TWLight.comments\" # REVERSION CONFIGURATION # ------------------------------------------------------------------------------ # See https://django-reversion.readthedocs.org/", "\"TWLight.applications\", \"TWLight.emails\", \"TWLight.graphs\", \"TWLight.comments\", \"TWLight.api\", \"TWLight.ezproxy\", ] # dal (autocomplete_light)", "For local testing '*' is OK. ALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"localhost", "will not work as one. You should instead use production.py,", "{ \"handlers\": [\"django.server\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), \"propagate\": False, }, \"TWLight\":", "[] language_data_json = open(os.path.join(dir, \"language-data.json\")) languages = json.loads(language_data_json.read())[\"languages\"] for locale_dir", "locale in FAKER_AVAILABLE_LOCALES: for i, (djlang_code, djlang_name) in enumerate(languages): #", "Note that, if some amount of # geographic tracking is", "------------------------------------------------------------------------------ REST_FRAMEWORK = { \"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\" } # MIDDLEWARE CONFIGURATION", "use production settings, you are now done. If not, you", "CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", # WhiteNoise should", "= True USE_TZ = True # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------", "this list should contain the URL of the server and", "with 'from .base import *'; and proceed to add or", "\"django.template.loaders.app_directories.Loader\", ], ) ], }, } ] # STATIC FILE", "need to set ALLOWED_HOSTS before your app will run. If", "\"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\", ] # REST FRAMEWORK CONFIG # ------------------------------------------------------------------------------", "By setting this an an environment variable, it is easy", "\"WARNING\", \"filters\": [\"require_debug_false\"], \"class\": \"logging.StreamHandler\", }, \"debug_console\": { \"level\": \"INFO\",", "live settings file for a project and will not work", "Cache, if used), but before # Common. \"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\",", "is a REQUEST_ANONYMOUS_IP setting which # scrubs the last octet", "language_data_json = open(os.path.join(dir, \"language-data.json\")) languages = json.loads(language_data_json.read())[\"languages\"] for locale_dir in", "CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = \"en\" # Sets", "the site. LANGUAGES = get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES = get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE =", "\"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\", \"django.template.context_processors.i18n\", \"django.template.context_processors.media\", \"django.template.context_processors.request\", \"django.template.context_processors.static\", \"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\", ), #", "LOGIN_URL = reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL = reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS = [ \"TWLight.users.oauth.OAuthBackend\",", "# We're replacing the default logging config to get better", "# https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json # into locale/language-data.json def get_languages_from_locale_subdirectories(dir): current_languages = []", "None) # API CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT = os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None)", "open(os.path.join(dir, \"language-data.json\")) languages = json.loads(language_data_json.read())[\"languages\"] for locale_dir in os.listdir(dir): if", "the system. This keeps our column and index count for", "the default logging config to get better control of the", "is # django-request, the user analytics package. \"request\", \"django_countries\", \"rest_framework\",", "geographic tracking is desired, there is a REQUEST_ANONYMOUS_IP setting which", "GENERAL CONFIGURATION # ------------------------------------------------------------------------------ # SECURITY WARNING: keep the secret", "available Faker locales and the specified language set. def get_django_faker_languages_intersection(languages):", "nice with bootstrap MESSAGE_TAGS = {messages.ERROR: \"danger\"} # INTERNATIONALIZATION CONFIGURATION", "# OAUTH CONFIGURATION # ------------------------------------------------------------------------------ LOGIN_URL = reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL =", "= os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None) # COMMENTS CONFIGURATION # ------------------------------------------------------------------------------ COMMENTS_APP =", "autonyms from Wikimedia. # We periodically pull: # https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json #", "in case they differ from internal # Needed to be", "\"rest_framework\", \"rest_framework.authtoken\", \"django_extensions\", ] TWLIGHT_APPS = [ \"TWLight.i18n\", \"TWLight.users\", \"TWLight.resources\",", "\"TWLight.users\", \"TWLight.resources\", \"TWLight.applications\", \"TWLight.emails\", \"TWLight.graphs\", \"TWLight.comments\", \"TWLight.api\", \"TWLight.ezproxy\", ] #", "before # Common. \"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", # The default", "for handling Unicode data due to stupid properties # of", "Let Django know about external URLs in case they differ", "\"OPTIONS\": { # Reiterating the default so we can add", "TWLIGHT_EZPROXY_URL = os.environ.get(\"TWLIGHT_EZPROXY_URL\", None) TWLIGHT_EZPROXY_SECRET = os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None) # OAUTH", "replaces staticfiles \"django.contrib.staticfiles\", \"django.contrib.sites\", # required by django.contrib.comments ] THIRD_PARTY_APPS", "# ------------------------------------------------------------------------------ # SECURITY WARNING: keep the secret key used", "that creates revisions when # save() is called in the", "settings for twlight project. This is not intended to be", "os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None) # API CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT = os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\",", "\"context_processors\": ( \"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\", \"django.template.context_processors.i18n\", \"django.template.context_processors.media\", \"django.template.context_processors.request\", \"django.template.context_processors.static\", \"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\",", "appropriate to their context. In particular, you will need to", "will run. If you want to use production settings, you", "{ # Reiterating the default so we can add to", "= [] language_data_json = open(os.path.join(dir, \"language-data.json\")) languages = json.loads(language_data_json.read())[\"languages\"] for", "our column and index count for db-stored # translations as", "COMMENTS CONFIGURATION # ------------------------------------------------------------------------------ COMMENTS_APP = \"TWLight.comments\" # REVERSION CONFIGURATION", "# ------------------------------------------------------------------------------ # We're replacing the default logging config to", "they differ from internal # Needed to be added for", "You should instead use production.py, local.py, heroku.py, or another file", "https://django-reversion.readthedocs.org/ . # We are NOT using reversion middleware, because", "In production, this list should contain the URL of the", "FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, \"collectedstatic\")", "\"django.contrib.messages\", \"whitenoise.runserver_nostatic\", # Not a django app; replaces staticfiles \"django.contrib.staticfiles\",", "and compare them to the # languages in Wikimedia CLDR.", "-*- \"\"\" Base settings for twlight project. This is not", "MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", # WhiteNoise should be loaded before", "but not on all database # saves. This makes it", "] THIRD_PARTY_APPS = [ \"annoying\", \"crispy_forms\", \"reversion\", \"dal\", \"dal_select2\", \"django_comments\",", "while others are broken. if ( locale == djlang_code and", "and locale != \"en_GB\" ): languages_intersection += [locale] return sorted(set(languages_intersection))", "\"loaders\": [ ( \"django.template.loaders.cached.Loader\", [ \"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\", ], ) ],", "25 EMAIL_HOST_USER = \"\" EMAIL_HOST_PASSWORD = \"\" EMAIL_USE_TLS = False", "\"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\", ] # REST FRAMEWORK CONFIG #", "# ------------------------------------------------------------------------------ TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [os.path.join(BASE_DIR,", "locale_dir)): for lang_code, lang_data in languages.items(): autonym = lang_data[-1] if", "REST FRAMEWORK CONFIG # ------------------------------------------------------------------------------ REST_FRAMEWORK = { \"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\"", "locale_dir == lang_code: current_languages += [(lang_code, autonym)] return sorted(set(current_languages)) #", "utf-8 -*- \"\"\" Base settings for twlight project. This is", "MEDIA FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),", "REST_FRAMEWORK = { \"DEFAULT_VERSIONING_CLASS\": \"rest_framework.versioning.NamespaceVersioning\" } # MIDDLEWARE CONFIGURATION #", "# https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE = ( LANGUAGE_CODE # sets the modeltranslation", "to get better control of the # mail_admins behavior. LOGGING_CONFIG", "# Exclude common English locales from random test selection; English", "of the IP address, which could be used instead of", "True USE_L10N = True USE_TZ = True # TEMPLATE CONFIGURATION", "------------------------------------------------------------------------------ # ------------------------> core django configurations <------------------------ # ------------------------------------------------------------------------------ #", "compare them to the # languages in Wikimedia CLDR. Use", "\"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\": {\"()\": \"django.utils.log.RequireDebugTrue\"}, }, \"formatters\": { \"django.server\":", "particular, you will need to set ALLOWED_HOSTS before your app", "We're replacing the default logging config to get better control", "you will need to set ALLOWED_HOSTS before your app will", "\"DIRS\": [os.path.join(BASE_DIR, \"templates\")], \"OPTIONS\": { # Reiterating the default so", "= reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL = reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS = [ \"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\",", "templates by default. \"loaders\": [ ( \"django.template.loaders.cached.Loader\", [ \"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\",", "external URLs in case they differ from internal # Needed", "# That’s why SessionMiddleware must be enabled and appear before", "used as the live settings file for a project and", "be loaded before everything but security. \"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\",", "MODELTRANSLATION_DEFAULT_LANGUAGE = ( LANGUAGE_CODE # sets the modeltranslation default language.", "os.path.isdir(os.path.join(dir, locale_dir)): for lang_code, lang_data in languages.items(): autonym = lang_data[-1]", "------------------------------------------------------------------------------ DJANGO_APPS = [ \"django.contrib.admin\", \"django.contrib.admindocs\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\",", "\"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", # LocaleMiddleware must go after Session (and", "}, \"loggers\": { \"django\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\",", "# Import available locales from Faker, so we can determine", "Overwrite messages.ERROR to use danger instead, to play nice with", "LOCALE_PATHS = [ # makemessages looks for locale/ in the", "This keeps our column and index count for db-stored #", "setting which # scrubs the last octet of the IP", "# ------------------------------------------------------------------------------ CRON_CLASSES = [ \"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\",", "AUTHENTICATION_BACKENDS = [ \"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\", ] TWLIGHT_OAUTH_PROVIDER_URL = os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None)", "DO NOT CONFUSE THIS with requests, the Python URL library!", "== lang_code: current_languages += [(lang_code, autonym)] return sorted(set(current_languages)) # Get", "\"static\")] STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\" # MEDIA FILE CONFIGURATION # ------------------------------------------------------------------------------", "127.0.0.1 [::1]\").split(\" \") # Let Django know about external URLs", "[(lang_code, autonym)] return sorted(set(current_languages)) # Get the intersection of available", "only authenticated vs anonymous users). REQUEST_LOG_IP = False REQUEST_LOG_USER =", "# ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/ref/settings/#databases # WMF sysadmins strongly prefer mysql,", "settings file for a project and will not work as", "\"django.template.context_processors.debug\", \"django.template.context_processors.i18n\", \"django.template.context_processors.media\", \"django.template.context_processors.request\", \"django.template.context_processors.static\", \"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\", ), # We", "langauge autonyms from Wikimedia. # We periodically pull: # https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json", "languages in Wikimedia CLDR. Use langauge autonyms from Wikimedia. #", "\"TWLight\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, },", "SET storage_engine='INNODB';\", }, } } # GENERAL CONFIGURATION # ------------------------------------------------------------------------------", "USE_X_FORWARDED_HOST = True REQUEST_BASE_URL = os.environ.get(\"REQUEST_BASE_URL\", None) ROOT_URLCONF = \"TWLight.urls\"", "In particular, you will need to set ALLOWED_HOSTS before your", "some http requests, but not on all database # saves.", "in enumerate(languages): # Exclude common English locales from random test", "# Not a django app; replaces staticfiles \"django.contrib.staticfiles\", \"django.contrib.sites\", #", "[ \"annoying\", \"crispy_forms\", \"reversion\", \"dal\", \"dal_select2\", \"django_comments\", \"django_cron\", \"django_filters\", \"modeltranslation\",", "deploying to Heroku, heroku.py will override this. DATABASES = {", "COMMENTS_APP = \"TWLight.comments\" # REVERSION CONFIGURATION # ------------------------------------------------------------------------------ # See", "the top level, not the project level. os.path.join(os.path.dirname(BASE_DIR), \"locale\") ]", "import *'; and proceed to add or override settings as", "(such # as tracking only authenticated vs anonymous users). REQUEST_LOG_IP", "the IP address, which could be used instead of #", "English locales from random test selection; English often works while", "later. \"context_processors\": ( \"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\", \"django.template.context_processors.i18n\", \"django.template.context_processors.media\", \"django.template.context_processors.request\", \"django.template.context_processors.static\", \"django.template.context_processors.tz\",", "are now done. If not, you will also need to", "live in the settings directory; start with 'from .base import", "required by django.contrib.comments ] THIRD_PARTY_APPS = [ \"annoying\", \"crispy_forms\", \"reversion\",", "due to stupid properties # of MySQL; see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django .", "SITE_ID = 1 # Overwrite messages.ERROR to use danger instead,", "\"handlers\": { \"nodebug_console\": { \"level\": \"WARNING\", \"filters\": [\"require_debug_false\"], \"class\": \"logging.StreamHandler\",", "# Let Django know about external URLs in case they", "'from .base import *'; and proceed to add or override", "go after Session (and Cache, if used), but before #", "= \"bootstrap3\" # EZPROXY CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL = os.environ.get(\"TWLIGHT_EZPROXY_URL\",", "FAKER_AVAILABLE_LOCALES: for i, (djlang_code, djlang_name) in enumerate(languages): # Exclude common", "to be added for /admin USE_X_FORWARDED_HOST = True REQUEST_BASE_URL =", "https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki # Get the language codes from the locale directories,", "anonymous users). REQUEST_LOG_IP = False REQUEST_LOG_USER = False # LOGGING", "be enabled and appear before # MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\", ] #", "bool(os.environ.get(\"DEBUG\", \"False\").lower() == \"true\") # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ #", "\"django.template.loaders.cached.Loader\", [ \"django.template.loaders.filesystem.Loader\", \"django.template.loaders.app_directories.Loader\", ], ) ], }, } ]", "AVAILABLE_LOCALES as FAKER_AVAILABLE_LOCALES # We're going to replace Django's default", "save() is called in the context of some http requests,", "middleware, because that creates revisions when # save() is called", "for twlight project. This is not intended to be used", "set the environment variables indicated in the README. For more", "test selection; English often works while others are broken. if", "going to replace Django's default logging config. import logging.config BASE_DIR", "# mail_admins behavior. LOGGING_CONFIG = None logging.config.dictConfig( { \"version\": 1,", "!= \"en_GB\" ): languages_intersection += [locale] return sorted(set(languages_intersection)) # ------------------------------------------------------------------------------", "locale_dir in os.listdir(dir): if os.path.isdir(os.path.join(dir, locale_dir)): for lang_code, lang_data in", "# -*- coding: utf-8 -*- \"\"\" Base settings for twlight", "need to set the environment variables indicated in the README.", "= [ \"TWLight.i18n\", \"TWLight.users\", \"TWLight.resources\", \"TWLight.applications\", \"TWLight.emails\", \"TWLight.graphs\", \"TWLight.comments\", \"TWLight.api\",", "}, } } # GENERAL CONFIGURATION # ------------------------------------------------------------------------------ # SECURITY", "\"\" EMAIL_USE_TLS = False INSTALLED_APPS += [\"djmail\"] # DJANGO_REQUEST CONFIGURATION", "# django-request, the user analytics package. \"request\", \"django_countries\", \"rest_framework\", \"rest_framework.authtoken\",", "os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))) ) TWLIGHT_ENV = os.environ.get(\"TWLIGHT_ENV\") # An atypical way", "if some amount of # geographic tracking is desired, there", "\"django_countries\", \"rest_framework\", \"rest_framework.authtoken\", \"django_extensions\", ] TWLIGHT_APPS = [ \"TWLight.i18n\", \"TWLight.users\",", "is called in the context of some http requests, but", "= \"en\" # Sets site default language. # https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE", "} } # GENERAL CONFIGURATION # ------------------------------------------------------------------------------ # SECURITY WARNING:", "it untestable. Instead we decorate the Application.save(). # DJMAIL CONFIGURATION", "project and will not work as one. You should instead", "periodically pull: # https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json # into locale/language-data.json def get_languages_from_locale_subdirectories(dir): current_languages", "# In production, this list should contain the URL of", "library! This is # django-request, the user analytics package. \"request\",", "json.loads(language_data_json.read())[\"languages\"] for locale_dir in os.listdir(dir): if os.path.isdir(os.path.join(dir, locale_dir)): for lang_code,", "def get_django_faker_languages_intersection(languages): languages_intersection = [] for locale in FAKER_AVAILABLE_LOCALES: for", "( locale == djlang_code and locale != \"en\" and locale", "FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"media\")", "# WMF sysadmins strongly prefer mysql, so use that. #", "default so we can add to it later. \"context_processors\": (", "add to it later. \"context_processors\": ( \"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\", \"django.template.context_processors.i18n\", \"django.template.context_processors.media\",", "\"django\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, \"django.server\":", "}, \"handlers\": { \"nodebug_console\": { \"level\": \"WARNING\", \"filters\": [\"require_debug_false\"], \"class\":", "done. If not, you will also need to set the", "# WhiteNoise should be loaded before everything but security. \"whitenoise.middleware.WhiteNoiseMiddleware\",", "should be loaded before everything but security. \"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\",", "# ------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK = \"bootstrap3\" # EZPROXY CONFIGURATION # ------------------------------------------------------------------------------", "https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE = ( LANGUAGE_CODE # sets the modeltranslation default", "# APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS = [ \"django.contrib.admin\", \"django.contrib.admindocs\",", "variable, it is easy to switch debug on in #", "\"djmail.backends.async.EmailBackend\" EMAIL_HOST = os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\") EMAIL_PORT = 25 EMAIL_HOST_USER =", "in Wikimedia CLDR. Use langauge autonyms from Wikimedia. # We", "\"dal\", \"dal_select2\", \"django_comments\", \"django_cron\", \"django_filters\", \"modeltranslation\", # DO NOT CONFUSE", "------------------------------------------------------------------------------ # By setting this an an environment variable, it", "Use langauge autonyms from Wikimedia. # We periodically pull: #", "# https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"media\") MEDIA_URL = \"/media/\" #", "= [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [os.path.join(BASE_DIR, \"templates\")], \"OPTIONS\": {", "and TWLight configurations <------------------- # ------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK = \"bootstrap3\" #", "djlang_code and locale != \"en\" and locale != \"en_US\" and", "added for /admin USE_X_FORWARDED_HOST = True REQUEST_BASE_URL = os.environ.get(\"REQUEST_BASE_URL\", None)", "from Faker, so we can determine what languages we fake", "\"django.contrib.admin\", \"django.contrib.admindocs\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"whitenoise.runserver_nostatic\", # Not a", "locale/ in the top level, not the project level. os.path.join(os.path.dirname(BASE_DIR),", "False, }, \"TWLight\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"),", "STATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\")] STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\" # MEDIA FILE", "when # save() is called in the context of some", "os.environ.get(\"TWLIGHT_EZPROXY_URL\", None) TWLIGHT_EZPROXY_SECRET = os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None) # OAUTH CONFIGURATION #", "[ \"TWLight.i18n\", \"TWLight.users\", \"TWLight.resources\", \"TWLight.applications\", \"TWLight.emails\", \"TWLight.graphs\", \"TWLight.comments\", \"TWLight.api\", \"TWLight.ezproxy\",", "https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django . \"OPTIONS\": { \"charset\": \"utf8mb4\", \"init_command\": \"SET sql_mode='STRICT_ALL_TABLES'; SET", "contain the URL of the server and nothing # else,", "STATIC_ROOT = os.path.join(BASE_DIR, \"collectedstatic\") STATIC_URL = \"/static/\" STATICFILES_DIRS = [os.path.join(BASE_DIR,", "translations as low as possible while allowing translatewiki contributions to", "is OK. ALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"localhost 127.0.0.1 [::1]\").split(\" \") #", "import os import json from django.contrib import messages from django.urls", "as appropriate to their context. In particular, you will need", "{ \"level\": \"WARNING\", \"filters\": [\"require_debug_false\"], \"class\": \"logging.StreamHandler\", }, \"debug_console\": {", "address, which could be used instead of # REQUEST_LOG_IP. There", "some amount of # geographic tracking is desired, there is", "If you're deploying to Heroku, heroku.py will override this. DATABASES", "to the system. This keeps our column and index count", "\"media\") MEDIA_URL = \"/media/\" # ------------------------------------------------------------------------------ # -----------------> third-party and", "proceed to add or override settings as appropriate to their", "as possible while allowing translatewiki contributions to # be used", "so we can determine what languages we fake in tests.", "USE_TZ = True # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ TEMPLATES =", "sessions. # That’s why SessionMiddleware must be enabled and appear", "\"UTC\" USE_I18N = True USE_L10N = True USE_TZ = True", "ALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"localhost 127.0.0.1 [::1]\").split(\" \") # Let Django", "OK. ALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"localhost 127.0.0.1 [::1]\").split(\" \") # Let", "danger instead, to play nice with bootstrap MESSAGE_TAGS = {messages.ERROR:", "requests, the Python URL library! This is # django-request, the", "heroku.py will override this. DATABASES = { \"default\": { \"ENGINE\":", "{\"()\": \"django.utils.log.RequireDebugTrue\"}, }, \"formatters\": { \"django.server\": { \"()\": \"django.utils.log.ServerFormatter\", \"format\":", "# EZPROXY CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL = os.environ.get(\"TWLIGHT_EZPROXY_URL\", None) TWLIGHT_EZPROXY_SECRET", "} }, \"handlers\": { \"nodebug_console\": { \"level\": \"WARNING\", \"filters\": [\"require_debug_false\"],", "# We're letting the file-based translation contributions dictate the languages", "\"propagate\": False, }, \"TWLight\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\",", "locale != \"en_US\" and locale != \"en_GB\" ): languages_intersection +=", "should instead use production.py, local.py, heroku.py, or another file that", "but before # Common. \"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", # The", "= os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None) # API CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT =", "# TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ TEMPLATES = [ { \"BACKEND\":", "keeps our column and index count for db-stored # translations", "# ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"media\") MEDIA_URL =", "Common. \"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", # The default storage backend", "# INTERNATIONALIZATION CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = \"en\"", "------------------------------------------------------------------------------ # -----------------> third-party and TWLight configurations <------------------- # ------------------------------------------------------------------------------", "could be used instead of # REQUEST_LOG_IP. There is not", "# This is critical for handling Unicode data due to", "= False INSTALLED_APPS += [\"djmail\"] # DJANGO_REQUEST CONFIGURATION # ------------------------------------------------------------------------------", "in FAKER_AVAILABLE_LOCALES: for i, (djlang_code, djlang_name) in enumerate(languages): # Exclude", "CLDR. Use langauge autonyms from Wikimedia. # We periodically pull:", "default language. ) LOCALE_PATHS = [ # makemessages looks for", "\"django.utils.log.ServerFormatter\", \"format\": \"[%(server_time)s] %(message)s\", } }, \"handlers\": { \"nodebug_console\": {", "os.environ.get(\"DJANGO_DB_HOST\", None), \"PORT\": \"3306\", # This is critical for handling", "\"rest_framework.versioning.NamespaceVersioning\" } # MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE = [", "project. This is not intended to be used as the", "desired, there is a REQUEST_ANONYMOUS_IP setting which # scrubs the", "import reverse_lazy from django.utils.translation import gettext_lazy as _ # Import", "\"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", # The default storage backend relies on sessions.", "the context of some http requests, but not on all", "# ------------------------------------------------------------------------------ # ------------------------> core django configurations <------------------------ # ------------------------------------------------------------------------------", "\"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, }, } )", "others are broken. if ( locale == djlang_code and locale", "(autocomplete_light) and modeltranslation must go before django.contrib.admin. INSTALLED_APPS = THIRD_PARTY_APPS", "not work as one. You should instead use production.py, local.py,", "\"USER\": os.environ.get(\"DJANGO_DB_USER\", None), \"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\", None), \"HOST\": os.environ.get(\"DJANGO_DB_HOST\", None), \"PORT\":", "PRODUCTION for security reasons. DEBUG = bool(os.environ.get(\"DEBUG\", \"False\").lower() == \"true\")", "None) TWLIGHT_OAUTH_CONSUMER_KEY = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None) TWLIGHT_OAUTH_CONSUMER_SECRET = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_SECRET\", None) #", "import logging.config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME = os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir)))", "SHOULD BE FALSE ON PRODUCTION for security reasons. DEBUG =", "------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, \"collectedstatic\") STATIC_URL = \"/static/\"", "to get semi-granular user tracking (such # as tracking only", "for security reasons. DEBUG = bool(os.environ.get(\"DEBUG\", \"False\").lower() == \"true\") #", "= reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS = [ \"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\", ] TWLIGHT_OAUTH_PROVIDER_URL =", "\"level\": \"INFO\", \"filters\": [\"require_debug_true\"], \"class\": \"logging.StreamHandler\", }, \"django.server\": { \"level\":", "= \"djmail.backends.async.EmailBackend\" EMAIL_HOST = os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\") EMAIL_PORT = 25 EMAIL_HOST_USER", "for locale in FAKER_AVAILABLE_LOCALES: for i, (djlang_code, djlang_name) in enumerate(languages):", "reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS = [ \"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\", ] TWLIGHT_OAUTH_PROVIDER_URL = os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\",", "\"filters\": { \"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\": {\"()\": \"django.utils.log.RequireDebugTrue\"}, }, \"formatters\":", "\"OPTIONS\": { \"charset\": \"utf8mb4\", \"init_command\": \"SET sql_mode='STRICT_ALL_TABLES'; SET storage_engine='INNODB';\", },", "] # REST FRAMEWORK CONFIG # ------------------------------------------------------------------------------ REST_FRAMEWORK = {", "which could be used instead of # REQUEST_LOG_IP. There is", "from django.contrib import messages from django.urls import reverse_lazy from django.utils.translation", "TWLIGHT_API_PROVIDER_ENDPOINT = os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None) # COMMENTS CONFIGURATION # ------------------------------------------------------------------------------ COMMENTS_APP", "\"true\") # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/ref/settings/#databases # WMF", "must go before django.contrib.admin. INSTALLED_APPS = THIRD_PARTY_APPS + DJANGO_APPS +", "= lang_data[-1] if locale_dir == lang_code: current_languages += [(lang_code, autonym)]", "dictate the languages # available to the system. This keeps", "See https://django-reversion.readthedocs.org/ . # We are NOT using reversion middleware,", "------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND = os.environ.get( \"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\" ) EMAIL_BACKEND = \"djmail.backends.async.EmailBackend\"", "a project and will not work as one. You should", "------------------------------------------------------------------------------ # See https://django-reversion.readthedocs.org/ . # We are NOT using", "\"class\": \"logging.StreamHandler\", }, \"debug_console\": { \"level\": \"INFO\", \"filters\": [\"require_debug_true\"], \"class\":", "LANGUAGE_CODE # sets the modeltranslation default language. ) LOCALE_PATHS =", "\"en_GB\" ): languages_intersection += [locale] return sorted(set(languages_intersection)) # ------------------------------------------------------------------------------ #", "\"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [os.path.join(BASE_DIR, \"templates\")], \"OPTIONS\": { # Reiterating the", "is desired, there is a REQUEST_ANONYMOUS_IP setting which # scrubs", "= False # LOGGING CONFIGURATION # ------------------------------------------------------------------------------ # We're replacing", "appear before # MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\", ] # DEBUG # ------------------------------------------------------------------------------", "and nothing # else, for security reasons. For local testing", "CONFIGURATION # ------------------------------------------------------------------------------ # See https://django-reversion.readthedocs.org/ . # We are", "handling Unicode data due to stupid properties # of MySQL;", "os.environ.get( \"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\" ) EMAIL_BACKEND = \"djmail.backends.async.EmailBackend\" EMAIL_HOST = os.environ.get(\"DJANGO_EMAIL_HOST\",", "= os.environ.get(\"TWLIGHT_ENV\") # An atypical way of setting django languages", "\"django.server\": { \"()\": \"django.utils.log.ServerFormatter\", \"format\": \"[%(server_time)s] %(message)s\", } }, \"handlers\":", "use that. # If you're deploying to Heroku, heroku.py will", "------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK = \"bootstrap3\" # EZPROXY CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL", "DJMAIL_REAL_BACKEND = os.environ.get( \"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\" ) EMAIL_BACKEND = \"djmail.backends.async.EmailBackend\" EMAIL_HOST", "{ \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, \"django.server\": {", "\"()\": \"django.utils.log.ServerFormatter\", \"format\": \"[%(server_time)s] %(message)s\", } }, \"handlers\": { \"nodebug_console\":", "stupid properties # of MySQL; see https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django . \"OPTIONS\": {", "import AVAILABLE_LOCALES as FAKER_AVAILABLE_LOCALES # We're going to replace Django's", "be used without reconfiguring the site. LANGUAGES = get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES", "IP address, which could be used instead of # REQUEST_LOG_IP.", "before your app will run. If you want to use", "the last octet of the IP address, which could be", "default storage backend relies on sessions. # That’s why SessionMiddleware", "ROOT_URLCONF = \"TWLight.urls\" WSGI_APPLICATION = \"TWLight.wsgi.application\" SITE_ID = 1 #", "the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/", "None), \"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\", None), \"HOST\": os.environ.get(\"DJANGO_DB_HOST\", None), \"PORT\": \"3306\", #", "for locale/ in the top level, not the project level.", "of available Faker locales and the specified language set. def", "revisions when # save() is called in the context of", "\"nodebug_console\": { \"level\": \"WARNING\", \"filters\": [\"require_debug_false\"], \"class\": \"logging.StreamHandler\", }, \"debug_console\":", "and proceed to add or override settings as appropriate to", "CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_API_PROVIDER_ENDPOINT = os.environ.get(\"TWLIGHT_API_PROVIDER_ENDPOINT\", None) # COMMENTS CONFIGURATION", "modeltranslation default language. ) LOCALE_PATHS = [ # makemessages looks", "switch debug on in # servers to do a quick", "production, this list should contain the URL of the server", "[locale] return sorted(set(languages_intersection)) # ------------------------------------------------------------------------------ # ------------------------> core django configurations", "of some http requests, but not on all database #", "locale directories, and compare them to the # languages in", "\"django.template.backends.django.DjangoTemplates\", \"DIRS\": [os.path.join(BASE_DIR, \"templates\")], \"OPTIONS\": { # Reiterating the default", "= \"\" EMAIL_HOST_PASSWORD = \"\" EMAIL_USE_TLS = False INSTALLED_APPS +=", "\"\" EMAIL_HOST_PASSWORD = \"\" EMAIL_USE_TLS = False INSTALLED_APPS += [\"djmail\"]", "False INSTALLED_APPS += [\"djmail\"] # DJANGO_REQUEST CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE", "None) # COMMENTS CONFIGURATION # ------------------------------------------------------------------------------ COMMENTS_APP = \"TWLight.comments\" #", "BE FALSE ON PRODUCTION for security reasons. DEBUG = bool(os.environ.get(\"DEBUG\",", "# https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki # Get the language codes from the locale", "os import json from django.contrib import messages from django.urls import", "# MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\", ] # DEBUG # ------------------------------------------------------------------------------ # By", "CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE += [\"request.middleware.RequestMiddleware\"] # The following are", "used without reconfiguring the site. LANGUAGES = get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES =", "\"require_debug_true\": {\"()\": \"django.utils.log.RequireDebugTrue\"}, }, \"formatters\": { \"django.server\": { \"()\": \"django.utils.log.ServerFormatter\",", "# https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, \"collectedstatic\") STATIC_URL = \"/static/\" STATICFILES_DIRS", "\"dal_select2\", \"django_comments\", \"django_cron\", \"django_filters\", \"modeltranslation\", # DO NOT CONFUSE THIS", "Faker, so we can determine what languages we fake in", "# DEBUG # ------------------------------------------------------------------------------ # By setting this an an", "ON PRODUCTION for security reasons. DEBUG = bool(os.environ.get(\"DEBUG\", \"False\").lower() ==", "https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\" import os import json from django.contrib import messages", "Unicode data due to stupid properties # of MySQL; see", "languages we fake in tests. from faker.config import AVAILABLE_LOCALES as", "import messages from django.urls import reverse_lazy from django.utils.translation import gettext_lazy", "is not a way to get semi-granular user tracking (such", "django languages for TranslateWiki integration: # https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki # Get the", "the URL of the server and nothing # else, for", "= [ \"annoying\", \"crispy_forms\", \"reversion\", \"dal\", \"dal_select2\", \"django_comments\", \"django_cron\", \"django_filters\",", "control of the # mail_admins behavior. LOGGING_CONFIG = None logging.config.dictConfig(", "into locale/language-data.json def get_languages_from_locale_subdirectories(dir): current_languages = [] language_data_json = open(os.path.join(dir,", "\"/media/\" # ------------------------------------------------------------------------------ # -----------------> third-party and TWLight configurations <-------------------", "from Wikimedia. # We periodically pull: # https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json # into", "= os.environ.get(\"TWLIGHT_EZPROXY_URL\", None) TWLIGHT_EZPROXY_SECRET = os.environ.get(\"TWLIGHT_EZPROXY_SECRET\", None) # OAUTH CONFIGURATION", "{ \"version\": 1, \"disable_existing_loggers\": False, \"filters\": { \"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"},", "django-request, the user analytics package. \"request\", \"django_countries\", \"rest_framework\", \"rest_framework.authtoken\", \"django_extensions\",", "vs anonymous users). REQUEST_LOG_IP = False REQUEST_LOG_USER = False #", "MEDIA_URL = \"/media/\" # ------------------------------------------------------------------------------ # -----------------> third-party and TWLight", "contributions to # be used without reconfiguring the site. LANGUAGES", "them to the # languages in Wikimedia CLDR. Use langauge", "/admin USE_X_FORWARDED_HOST = True REQUEST_BASE_URL = os.environ.get(\"REQUEST_BASE_URL\", None) ROOT_URLCONF =", "OAUTH CONFIGURATION # ------------------------------------------------------------------------------ LOGIN_URL = reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL = reverse_lazy(\"users:home\")", "= ( LANGUAGE_CODE # sets the modeltranslation default language. )", "tests. from faker.config import AVAILABLE_LOCALES as FAKER_AVAILABLE_LOCALES # We're going", "servers to do a quick test. # DEBUG SHOULD BE", "\"django.template.context_processors.request\", \"django.template.context_processors.static\", \"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\", ), # We cache templates by", "django.contrib import messages from django.urls import reverse_lazy from django.utils.translation import", "coding: utf-8 -*- \"\"\" Base settings for twlight project. This", "from django.urls import reverse_lazy from django.utils.translation import gettext_lazy as _", "last octet of the IP address, which could be used", "you will also need to set the environment variables indicated", "BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME = os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))) ) TWLIGHT_ENV", "[ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [os.path.join(BASE_DIR, \"templates\")], \"OPTIONS\": { #", "purposes. Note that, if some amount of # geographic tracking", "MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\", ] # DEBUG # ------------------------------------------------------------------------------ # By setting", "\"logging.StreamHandler\", \"formatter\": \"django.server\", }, }, \"loggers\": { \"django\": { \"handlers\":", "# saves. This makes it untestable. Instead we decorate the", "+ TWLIGHT_APPS # CRON CONFIGURATION # ------------------------------------------------------------------------------ CRON_CLASSES = [", "= json.loads(language_data_json.read())[\"languages\"] for locale_dir in os.listdir(dir): if os.path.isdir(os.path.join(dir, locale_dir)): for", "in production secret! SECRET_KEY = os.environ.get(\"SECRET_KEY\") # In production, this", "test. # DEBUG SHOULD BE FALSE ON PRODUCTION for security", "# geographic tracking is desired, there is a REQUEST_ANONYMOUS_IP setting", "= THIRD_PARTY_APPS + DJANGO_APPS + TWLIGHT_APPS # CRON CONFIGURATION #", "which # scrubs the last octet of the IP address,", "https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, \"collectedstatic\") STATIC_URL = \"/static/\" STATICFILES_DIRS =", "\"django.db.backends.mysql\", \"NAME\": os.environ.get(\"DJANGO_DB_NAME\", None), \"USER\": os.environ.get(\"DJANGO_DB_USER\", None), \"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\", None),", "This is critical for handling Unicode data due to stupid", "directories, and compare them to the # languages in Wikimedia", "languages # available to the system. This keeps our column", "secret! SECRET_KEY = os.environ.get(\"SECRET_KEY\") # In production, this list should", "want to use production settings, you are now done. If", "octet of the IP address, which could be used instead", "also need to set the environment variables indicated in the", "used in production secret! SECRET_KEY = os.environ.get(\"SECRET_KEY\") # In production,", "called in the context of some http requests, but not", "third-party and TWLight configurations <------------------- # ------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK = \"bootstrap3\"", "and the specified language set. def get_django_faker_languages_intersection(languages): languages_intersection = []", "\"INFO\", \"filters\": [\"require_debug_true\"], \"class\": \"logging.StreamHandler\", }, \"django.server\": { \"level\": \"INFO\",", "None logging.config.dictConfig( { \"version\": 1, \"disable_existing_loggers\": False, \"filters\": { \"require_debug_false\":", "to Heroku, heroku.py will override this. DATABASES = { \"default\":", "\"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\", ] # REST FRAMEWORK CONFIG # ------------------------------------------------------------------------------ REST_FRAMEWORK", "\"django.contrib.auth.backends.ModelBackend\", ] TWLIGHT_OAUTH_PROVIDER_URL = os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None) TWLIGHT_OAUTH_CONSUMER_KEY = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None)", "locale != \"en\" and locale != \"en_US\" and locale !=", "to it later. \"context_processors\": ( \"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\", \"django.template.context_processors.i18n\", \"django.template.context_processors.media\", \"django.template.context_processors.request\",", "and modeltranslation must go before django.contrib.admin. INSTALLED_APPS = THIRD_PARTY_APPS +", "= [ \"TWLight.users.oauth.OAuthBackend\", \"django.contrib.auth.backends.ModelBackend\", ] TWLIGHT_OAUTH_PROVIDER_URL = os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None) TWLIGHT_OAUTH_CONSUMER_KEY", "count for db-stored # translations as low as possible while", "Django's default logging config. import logging.config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME", "True REQUEST_BASE_URL = os.environ.get(\"REQUEST_BASE_URL\", None) ROOT_URLCONF = \"TWLight.urls\" WSGI_APPLICATION =", "django.contrib.admin. INSTALLED_APPS = THIRD_PARTY_APPS + DJANGO_APPS + TWLIGHT_APPS # CRON", "\"\"\" import os import json from django.contrib import messages from", "CONFIGURATION # ------------------------------------------------------------------------------ # SECURITY WARNING: keep the secret key", "current_languages += [(lang_code, autonym)] return sorted(set(current_languages)) # Get the intersection", "because that creates revisions when # save() is called in", "run. If you want to use production settings, you are", "to their context. In particular, you will need to set", "saves. This makes it untestable. Instead we decorate the Application.save().", "): languages_intersection += [locale] return sorted(set(languages_intersection)) # ------------------------------------------------------------------------------ # ------------------------>", "These files should live in the settings directory; start with", "for /admin USE_X_FORWARDED_HOST = True REQUEST_BASE_URL = os.environ.get(\"REQUEST_BASE_URL\", None) ROOT_URLCONF", "+= [\"djmail\"] # DJANGO_REQUEST CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE += [\"request.middleware.RequestMiddleware\"]", "os.environ.get(\"DJANGO_DB_USER\", None), \"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\", None), \"HOST\": os.environ.get(\"DJANGO_DB_HOST\", None), \"PORT\": \"3306\",", "[\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, \"django.server\": { \"handlers\": [\"django.server\"],", "\"format\": \"[%(server_time)s] %(message)s\", } }, \"handlers\": { \"nodebug_console\": { \"level\":", "NOT using reversion middleware, because that creates revisions when #", "be used as the live settings file for a project", "settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\" import os import", "For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the", "\"init_command\": \"SET sql_mode='STRICT_ALL_TABLES'; SET storage_engine='INNODB';\", }, } } # GENERAL", "\"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, \"django.server\": { \"handlers\":", "as tracking only authenticated vs anonymous users). REQUEST_LOG_IP = False", "\"logging.StreamHandler\", }, \"debug_console\": { \"level\": \"INFO\", \"filters\": [\"require_debug_true\"], \"class\": \"logging.StreamHandler\",", "Sets site default language. # https://django-modeltranslation.readthedocs.io/en/latest/installation.html#advanced-settings MODELTRANSLATION_DEFAULT_LANGUAGE = ( LANGUAGE_CODE", "on in # servers to do a quick test. #", "but security. \"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", # LocaleMiddleware must go", "# ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, \"collectedstatic\") STATIC_URL =", "CONFIGURATION # ------------------------------------------------------------------------------ CRON_CLASSES = [ \"TWLight.crons.BackupCronJob\", \"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\",", "not a way to get semi-granular user tracking (such #", "# REST FRAMEWORK CONFIG # ------------------------------------------------------------------------------ REST_FRAMEWORK = { \"DEFAULT_VERSIONING_CLASS\":", "Exclude common English locales from random test selection; English often", "CRISPY_TEMPLATE_PACK = \"bootstrap3\" # EZPROXY CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL =", "of # REQUEST_LOG_IP. There is not a way to get", "------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = \"en\" # Sets site default", "TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [os.path.join(BASE_DIR, \"templates\")], \"OPTIONS\":", "write. These files should live in the settings directory; start", "work as one. You should instead use production.py, local.py, heroku.py,", "file that you write. These files should live in the", "# REVERSION CONFIGURATION # ------------------------------------------------------------------------------ # See https://django-reversion.readthedocs.org/ . #", "_ # Import available locales from Faker, so we can", "selection; English often works while others are broken. if (", "CONFIGURATION # ------------------------------------------------------------------------------ DJMAIL_REAL_BACKEND = os.environ.get( \"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\" ) EMAIL_BACKEND", "[\"require_debug_false\"], \"class\": \"logging.StreamHandler\", }, \"debug_console\": { \"level\": \"INFO\", \"filters\": [\"require_debug_true\"],", "# MIDDLEWARE CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", #", "default logging config to get better control of the #", "\"django.contrib.admindocs\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"whitenoise.runserver_nostatic\", # Not a django", "\"version\": 1, \"disable_existing_loggers\": False, \"filters\": { \"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\":", "WMF sysadmins strongly prefer mysql, so use that. # If", "not the project level. os.path.join(os.path.dirname(BASE_DIR), \"locale\") ] # We're letting", "\"DJANGO_EMAIL_BACKEND\", \"django.core.mail.backends.console.EmailBackend\" ) EMAIL_BACKEND = \"djmail.backends.async.EmailBackend\" EMAIL_HOST = os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\")", "CONFIGURATION # ------------------------------------------------------------------------------ COMMENTS_APP = \"TWLight.comments\" # REVERSION CONFIGURATION #", "------------------------------------------------------------------------------ MIDDLEWARE += [\"request.middleware.RequestMiddleware\"] # The following are set for", "\"django.contrib.messages.middleware.MessageMiddleware\", ] # DEBUG # ------------------------------------------------------------------------------ # By setting this", "before django.contrib.admin. INSTALLED_APPS = THIRD_PARTY_APPS + DJANGO_APPS + TWLIGHT_APPS #", "\"charset\": \"utf8mb4\", \"init_command\": \"SET sql_mode='STRICT_ALL_TABLES'; SET storage_engine='INNODB';\", }, } }", "list should contain the URL of the server and nothing", "now done. If not, you will also need to set", "sorted(set(languages_intersection)) # ------------------------------------------------------------------------------ # ------------------------> core django configurations <------------------------ #", "For the full list of settings and their values, see", "to use production settings, you are now done. If not,", "REVERSION CONFIGURATION # ------------------------------------------------------------------------------ # See https://django-reversion.readthedocs.org/ . # We", "# ------------------------------------------------------------------------------ # See https://django-reversion.readthedocs.org/ . # We are NOT", "# LOGGING CONFIGURATION # ------------------------------------------------------------------------------ # We're replacing the default", "for security reasons. For local testing '*' is OK. ALLOWED_HOSTS", "URLs in case they differ from internal # Needed to", "sql_mode='STRICT_ALL_TABLES'; SET storage_engine='INNODB';\", }, } } # GENERAL CONFIGURATION #", "# Get the intersection of available Faker locales and the", "often works while others are broken. if ( locale ==", "# GENERAL CONFIGURATION # ------------------------------------------------------------------------------ # SECURITY WARNING: keep the", "locale == djlang_code and locale != \"en\" and locale !=", "NOT CONFUSE THIS with requests, the Python URL library! This", "\"loggers\": { \"django\": { \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"),", "is critical for handling Unicode data due to stupid properties", "why SessionMiddleware must be enabled and appear before # MessageMiddleware.", "get_django_faker_languages_intersection(languages): languages_intersection = [] for locale in FAKER_AVAILABLE_LOCALES: for i,", "secret key used in production secret! SECRET_KEY = os.environ.get(\"SECRET_KEY\") #", "configurations <------------------- # ------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK = \"bootstrap3\" # EZPROXY CONFIGURATION", "better control of the # mail_admins behavior. LOGGING_CONFIG = None", "WARNING: keep the secret key used in production secret! SECRET_KEY", "https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"media\") MEDIA_URL = \"/media/\" # ------------------------------------------------------------------------------", "False # LOGGING CONFIGURATION # ------------------------------------------------------------------------------ # We're replacing the", "so use that. # If you're deploying to Heroku, heroku.py", "= [os.path.join(BASE_DIR, \"static\")] STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\" # MEDIA FILE CONFIGURATION", "{ \"django.server\": { \"()\": \"django.utils.log.ServerFormatter\", \"format\": \"[%(server_time)s] %(message)s\", } },", "and locale != \"en_US\" and locale != \"en_GB\" ): languages_intersection", "REQUEST_LOG_IP. There is not a way to get semi-granular user", "None), \"PORT\": \"3306\", # This is critical for handling Unicode", "# ------------------------------------------------------------------------------ COMMENTS_APP = \"TWLight.comments\" # REVERSION CONFIGURATION # ------------------------------------------------------------------------------", "way to get semi-granular user tracking (such # as tracking", "# available to the system. This keeps our column and", "= { \"default\": { \"ENGINE\": \"django.db.backends.mysql\", \"NAME\": os.environ.get(\"DJANGO_DB_NAME\", None), \"USER\":", "return sorted(set(current_languages)) # Get the intersection of available Faker locales", "os.environ.get(\"REQUEST_BASE_URL\", None) ROOT_URLCONF = \"TWLight.urls\" WSGI_APPLICATION = \"TWLight.wsgi.application\" SITE_ID =", "languages_intersection += [locale] return sorted(set(languages_intersection)) # ------------------------------------------------------------------------------ # ------------------------> core", "\"TWLight.comments\" # REVERSION CONFIGURATION # ------------------------------------------------------------------------------ # See https://django-reversion.readthedocs.org/ .", "------------------------> core django configurations <------------------------ # ------------------------------------------------------------------------------ # APP CONFIGURATION", "this an an environment variable, it is easy to switch", "There is not a way to get semi-granular user tracking", "context. In particular, you will need to set ALLOWED_HOSTS before", "if locale_dir == lang_code: current_languages += [(lang_code, autonym)] return sorted(set(current_languages))", "backend relies on sessions. # That’s why SessionMiddleware must be", "\"bootstrap3\" # EZPROXY CONFIGURATION # ------------------------------------------------------------------------------ TWLIGHT_EZPROXY_URL = os.environ.get(\"TWLIGHT_EZPROXY_URL\", None)", "We cache templates by default. \"loaders\": [ ( \"django.template.loaders.cached.Loader\", [", "\"INFO\", \"class\": \"logging.StreamHandler\", \"formatter\": \"django.server\", }, }, \"loggers\": { \"django\":", "If not, you will also need to set the environment", "of # geographic tracking is desired, there is a REQUEST_ANONYMOUS_IP", "DATABASES = { \"default\": { \"ENGINE\": \"django.db.backends.mysql\", \"NAME\": os.environ.get(\"DJANGO_DB_NAME\", None),", "not on all database # saves. This makes it untestable.", "level, not the project level. os.path.join(os.path.dirname(BASE_DIR), \"locale\") ] # We're", "one. You should instead use production.py, local.py, heroku.py, or another", "URL library! This is # django-request, the user analytics package.", "\"templates\")], \"OPTIONS\": { # Reiterating the default so we can", "you write. These files should live in the settings directory;", "we can add to it later. \"context_processors\": ( \"django.contrib.auth.context_processors.auth\", \"django.template.context_processors.debug\",", "\"TWLight.i18n\", \"TWLight.users\", \"TWLight.resources\", \"TWLight.applications\", \"TWLight.emails\", \"TWLight.graphs\", \"TWLight.comments\", \"TWLight.api\", \"TWLight.ezproxy\", ]", "= \"whitenoise.storage.CompressedManifestStaticFilesStorage\" # MEDIA FILE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/files/", "{messages.ERROR: \"danger\"} # INTERNATIONALIZATION CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE", "behavior. LOGGING_CONFIG = None logging.config.dictConfig( { \"version\": 1, \"disable_existing_loggers\": False,", "translatewiki contributions to # be used without reconfiguring the site.", "Needed to be added for /admin USE_X_FORWARDED_HOST = True REQUEST_BASE_URL", "strongly prefer mysql, so use that. # If you're deploying", "Reiterating the default so we can add to it later.", "We periodically pull: # https://raw.githubusercontent.com/wikimedia/language-data/master/data/language-data.json # into locale/language-data.json def get_languages_from_locale_subdirectories(dir):", "CONFUSE THIS with requests, the Python URL library! This is", "bootstrap MESSAGE_TAGS = {messages.ERROR: \"danger\"} # INTERNATIONALIZATION CONFIGURATION # ------------------------------------------------------------------------------", "an an environment variable, it is easy to switch debug", "REQUEST_LOG_USER = False # LOGGING CONFIGURATION # ------------------------------------------------------------------------------ # We're", "# languages in Wikimedia CLDR. Use langauge autonyms from Wikimedia.", "\"INFO\"), }, \"django.server\": { \"handlers\": [\"django.server\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), \"propagate\":", "MIDDLEWARE += [\"request.middleware.RequestMiddleware\"] # The following are set for privacy", "import gettext_lazy as _ # Import available locales from Faker,", "specified language set. def get_django_faker_languages_intersection(languages): languages_intersection = [] for locale", "# ------------------------------------------------------------------------------ # -----------------> third-party and TWLight configurations <------------------- #", "if used), but before # Common. \"django.middleware.locale.LocaleMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.contrib.admindocs.middleware.XViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\",", "https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = \"en\" # Sets site default language. #", "# LocaleMiddleware must go after Session (and Cache, if used),", "available locales from Faker, so we can determine what languages", "os.environ.get(\"ALLOWED_HOSTS\", \"localhost 127.0.0.1 [::1]\").split(\" \") # Let Django know about", "in # servers to do a quick test. # DEBUG", "{ \"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}, \"require_debug_true\": {\"()\": \"django.utils.log.RequireDebugTrue\"}, }, \"formatters\": {", "TWLIGHT_HOME = os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))) ) TWLIGHT_ENV = os.environ.get(\"TWLIGHT_ENV\") #", "know about external URLs in case they differ from internal", "see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their", "+= [\"request.middleware.RequestMiddleware\"] # The following are set for privacy purposes.", "), # We cache templates by default. \"loaders\": [ (", "CONFIGURATION # ------------------------------------------------------------------------------ LOGIN_URL = reverse_lazy(\"oauth_login\") LOGIN_REDIRECT_URL = reverse_lazy(\"users:home\") AUTHENTICATION_BACKENDS", "{ \"handlers\": [\"nodebug_console\", \"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, }, }", "\"TWLight.comments\", \"TWLight.api\", \"TWLight.ezproxy\", ] # dal (autocomplete_light) and modeltranslation must", "\"TWLight.crons.SendCoordinatorRemindersCronJob\", \"TWLight.crons.UserRenewalNoticeCronJob\", \"TWLight.crons.ProxyWaitlistDisableCronJob\", \"TWLight.crons.UserUpdateEligibilityCronJob\", \"TWLight.crons.ClearSessions\", ] # REST FRAMEWORK CONFIG", "CONFIGURATION # ------------------------------------------------------------------------------ TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\":", "The following are set for privacy purposes. Note that, if", "} # GENERAL CONFIGURATION # ------------------------------------------------------------------------------ # SECURITY WARNING: keep", "replacing the default logging config to get better control of", "# DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/ref/settings/#databases # WMF sysadmins", "\"class\": \"logging.StreamHandler\", \"formatter\": \"django.server\", }, }, \"loggers\": { \"django\": {", "[\"require_debug_true\"], \"class\": \"logging.StreamHandler\", }, \"django.server\": { \"level\": \"INFO\", \"class\": \"logging.StreamHandler\",", "django configurations <------------------------ # ------------------------------------------------------------------------------ # APP CONFIGURATION # ------------------------------------------------------------------------------", "your app will run. If you want to use production", "# sets the modeltranslation default language. ) LOCALE_PATHS = [", "\"en_US\" and locale != \"en_GB\" ): languages_intersection += [locale] return", "that. # If you're deploying to Heroku, heroku.py will override", "\"django.contrib.messages.context_processors.messages\", ), # We cache templates by default. \"loaders\": [", "FAKER_LOCALES = get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE = \"UTC\" USE_I18N = True USE_L10N", "a quick test. # DEBUG SHOULD BE FALSE ON PRODUCTION", "environment variable, it is easy to switch debug on in", "reverse_lazy from django.utils.translation import gettext_lazy as _ # Import available", "] TWLIGHT_OAUTH_PROVIDER_URL = os.environ.get(\"TWLIGHT_OAUTH_PROVIDER_URL\", None) TWLIGHT_OAUTH_CONSUMER_KEY = os.environ.get(\"TWLIGHT_OAUTH_CONSUMER_KEY\", None) TWLIGHT_OAUTH_CONSUMER_SECRET", "\"False\").lower() == \"true\") # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/ref/settings/#databases", "requests, but not on all database # saves. This makes", "# ------------------------------------------------------------------------------ # By setting this an an environment variable,", "be added for /admin USE_X_FORWARDED_HOST = True REQUEST_BASE_URL = os.environ.get(\"REQUEST_BASE_URL\",", "( LANGUAGE_CODE # sets the modeltranslation default language. ) LOCALE_PATHS", "= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME = os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))) ) TWLIGHT_ENV =", "looks for locale/ in the top level, not the project", "[\"djmail\"] # DJANGO_REQUEST CONFIGURATION # ------------------------------------------------------------------------------ MIDDLEWARE += [\"request.middleware.RequestMiddleware\"] #", "as FAKER_AVAILABLE_LOCALES # We're going to replace Django's default logging", "locales and the specified language set. def get_django_faker_languages_intersection(languages): languages_intersection =", "EMAIL_BACKEND = \"djmail.backends.async.EmailBackend\" EMAIL_HOST = os.environ.get(\"DJANGO_EMAIL_HOST\", \"localhost\") EMAIL_PORT = 25", "production.py, local.py, heroku.py, or another file that you write. These", "using reversion middleware, because that creates revisions when # save()", "loaded before everything but security. \"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", #", "------------------------------------------------------------------------------ MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", # WhiteNoise should be loaded", "get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE = \"UTC\" USE_I18N = True USE_L10N = True", "on all database # saves. This makes it untestable. Instead", "LOGGING_CONFIG = None logging.config.dictConfig( { \"version\": 1, \"disable_existing_loggers\": False, \"filters\":", "setting django languages for TranslateWiki integration: # https://translatewiki.net/wiki/Thread:Support/_The_following_issue_is_unconfirmed,_still_to_be_investigated._Adding_TheWikipediaLibrary_Card_Platform_TranslateWiki # Get", "\"django.template.context_processors.static\", \"django.template.context_processors.tz\", \"django.contrib.messages.context_processors.messages\", ), # We cache templates by default.", "CONFIGURATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/1.8/topics/files/ MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), \"media\") MEDIA_URL", "THIRD_PARTY_APPS + DJANGO_APPS + TWLIGHT_APPS # CRON CONFIGURATION # ------------------------------------------------------------------------------", "about external URLs in case they differ from internal #", "app will run. If you want to use production settings,", "[] for locale in FAKER_AVAILABLE_LOCALES: for i, (djlang_code, djlang_name) in", "CONFIGURATION # ------------------------------------------------------------------------------ # We're replacing the default logging config", "core django configurations <------------------------ # ------------------------------------------------------------------------------ # APP CONFIGURATION #", "logging.config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TWLIGHT_HOME = os.path.dirname( os.path.dirname(os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))) )", "<------------------------ # ------------------------------------------------------------------------------ # APP CONFIGURATION # ------------------------------------------------------------------------------ DJANGO_APPS =", "= get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES = get_django_faker_languages_intersection(LANGUAGES) TIME_ZONE = \"UTC\" USE_I18N =", "without reconfiguring the site. LANGUAGES = get_languages_from_locale_subdirectories(LOCALE_PATHS[0]) FAKER_LOCALES = get_django_faker_languages_intersection(LANGUAGES)", "%(message)s\", } }, \"handlers\": { \"nodebug_console\": { \"level\": \"WARNING\", \"filters\":", "reasons. For local testing '*' is OK. ALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\",", "environment variables indicated in the README. For more information on", "top level, not the project level. os.path.join(os.path.dirname(BASE_DIR), \"locale\") ] #", "security. \"whitenoise.middleware.WhiteNoiseMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", # LocaleMiddleware must go after", "to the # languages in Wikimedia CLDR. Use langauge autonyms", "django app; replaces staticfiles \"django.contrib.staticfiles\", \"django.contrib.sites\", # required by django.contrib.comments", "<------------------- # ------------------------------------------------------------------------------ CRISPY_TEMPLATE_PACK = \"bootstrap3\" # EZPROXY CONFIGURATION #", ". \"OPTIONS\": { \"charset\": \"utf8mb4\", \"init_command\": \"SET sql_mode='STRICT_ALL_TABLES'; SET storage_engine='INNODB';\",", "or override settings as appropriate to their context. In particular,", "level. os.path.join(os.path.dirname(BASE_DIR), \"locale\") ] # We're letting the file-based translation", "language codes from the locale directories, and compare them to", "in the settings directory; start with 'from .base import *';", "os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, \"django.server\": { \"handlers\": [\"django.server\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"),", "enabled and appear before # MessageMiddleware. \"django.contrib.messages.middleware.MessageMiddleware\", ] # DEBUG", "URL of the server and nothing # else, for security", "see https://docs.djangoproject.com/en/1.7/ref/settings/ \"\"\" import os import json from django.contrib import", "\"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), \"propagate\": False, }, \"TWLight\": { \"handlers\": [\"nodebug_console\",", "allowing translatewiki contributions to # be used without reconfiguring the", "production settings, you are now done. If not, you will", "= \"UTC\" USE_I18N = True USE_L10N = True USE_TZ =", "TIME_ZONE = \"UTC\" USE_I18N = True USE_L10N = True USE_TZ", "from faker.config import AVAILABLE_LOCALES as FAKER_AVAILABLE_LOCALES # We're going to", "set. def get_django_faker_languages_intersection(languages): languages_intersection = [] for locale in FAKER_AVAILABLE_LOCALES:", "language. ) LOCALE_PATHS = [ # makemessages looks for locale/", "------------------------------------------------------------------------------ # We're replacing the default logging config to get", "\"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"whitenoise.runserver_nostatic\", # Not a django app;", "= os.environ.get(\"ALLOWED_HOSTS\", \"localhost 127.0.0.1 [::1]\").split(\" \") # Let Django know", "\"debug_console\"], \"level\": os.environ.get(\"DJANGO_LOG_LEVEL\", \"INFO\"), }, \"django.server\": { \"handlers\": [\"django.server\"], \"level\":", "set ALLOWED_HOSTS before your app will run. If you want", "\"django_extensions\", ] TWLIGHT_APPS = [ \"TWLight.i18n\", \"TWLight.users\", \"TWLight.resources\", \"TWLight.applications\", \"TWLight.emails\",", "that, if some amount of # geographic tracking is desired,", "= [ \"django.middleware.security.SecurityMiddleware\", # WhiteNoise should be loaded before everything", "\"formatters\": { \"django.server\": { \"()\": \"django.utils.log.ServerFormatter\", \"format\": \"[%(server_time)s] %(message)s\", }", "\"NAME\": os.environ.get(\"DJANGO_DB_NAME\", None), \"USER\": os.environ.get(\"DJANGO_DB_USER\", None), \"PASSWORD\": os.environ.get(\"DJANGO_DB_PASSWORD\", None), \"HOST\":", "= True REQUEST_BASE_URL = os.environ.get(\"REQUEST_BASE_URL\", None) ROOT_URLCONF = \"TWLight.urls\" WSGI_APPLICATION", "available to the system. This keeps our column and index", "it is easy to switch debug on in # servers", "= 25 EMAIL_HOST_USER = \"\" EMAIL_HOST_PASSWORD = \"\" EMAIL_USE_TLS =", "FAKER_AVAILABLE_LOCALES # We're going to replace Django's default logging config.", "\"django.contrib.auth.middleware.AuthenticationMiddleware\", # The default storage backend relies on sessions. #", "{ \"charset\": \"utf8mb4\", \"init_command\": \"SET sql_mode='STRICT_ALL_TABLES'; SET storage_engine='INNODB';\", }, }" ]
[ "( 9,14), Infix(Non()), [] ; # '\\\\star', (13,13), Infix(Left()), []", "(\"UNION\", (8, 8), Prefix(), list(), nodes.UNION()), (\"DOMAIN\", (9, 9), Prefix(),", "[ '\\\\times' ], None ] ; # Modal, # List.map", "5), Infix(Non()), [] ; # '\\\\cong', ( 5, 5), Infix(Non()),", "Infix(Non()), list()), (\"@@\", (6, 6), Infix(Left()), list()), (\"!!\", (9, 13),", "list()), (\"\\\\succeq\", (5, 5), Infix(Non()), list()), (\"\\\\sim\", (5, 5), Infix(Non()),", "-> lookup '\\\\in' # | Notmem -> lookup '\\\\notin' #", "Prime -> lookup ''' # | StrongPrime -> lookup '''", "# } # # | STRING -> nonfix 'STRING' (Some", "SubSeq) # | SelectSeq -> nonfix 'SelectSeq' (Some SelectSeq) #", "13), Infix(Left()), list()), (\"-.\", (12, 12), Prefix(), [\"-\"]), (\"-\", (11,", "[\"-\"]), (\"-\", (11, 11), Infix(Left()), list()), (\"+\", (10, 10), Infix(Left()),", "Infix(Non()), list()), (\"\\\\succ\", (5, 5), Infix(Non()), list()), (\"\\\\preceq\", (5, 5),", "'\\\\/', ( 3, 3), Infix(Left()), [ '\\\\lor' ], Disj ;", "nodes.SUBSET()), (\"UNION\", (8, 8), Prefix(), list(), nodes.UNION()), (\"DOMAIN\", (9, 9),", "defn = Some Divides; # } # # | STRING", "; # '??', ( 9,13), Infix(Left()), [] ; # '%%',", "Infix(Non()), [] ; # ':>', ( 7, 7), Infix(Non()), []", "Infix(Non()), list()), (\"-|\", (5, 5), Infix(Non()), list()), (\"=|\", (5, 5),", "class Nonfix(Fixity): pass class Prefix(Fixity): pass class Postfix(Fixity): pass class", "open Builtin # type fixity = # | Nonfix #", "; # '&&', (13,13), Infix(Left()), [] ; # '&', (13,13),", "(13,13), Infix(Left()), [] ; # '$$', ( 9,13), Infix(Left()), []", "Infix(Non()), list()), (\"\\\\sqsupseteq\", (5, 5), Infix(Non()), list()), (\"\\\\doteq\", (5, 5),", "; # '/\\\\', ( 3, 3), Infix(Left()), [ '\\\\land' ],", "Seq) # | Len -> nonfix 'Len' (Some Len) #", "'<>', ( 4,15), Prefix, [], Diamond ; # ] ;", "with defn = Some Lteq } # | Lt ->", "# | Times -> { (lookup '*') with defn =", "Some Gt } # | Range -> { (lookup '..')", "als, None) for name, prec, fix, als in [ (\"^\",", "(\"\\\\sqsubseteq\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupset\", (5, 5), Infix(Non()), list()),", "Infix(Left()), [] ; # '^+', (15,15), Postfix, [] ; #", "Logic; # defn = Some Divides; # } # #", "{ name = name ; prec = (-1, -1) ;", "Infix(Non()), [], Mem ; # '\\\\notin', ( 5, 5), Infix(Non()),", "'\\\\union' ], Cup ; # ] ; # Sets, #", "(lookup '>') with defn = Some Gt } # |", "Postfix(), list()), (\"^*\", (15, 15), Postfix(), list()), (\"^#\", (15, 15),", "[] ; # '|-', ( 5, 5), Infix(Non()), [] ;", "| Len -> nonfix 'Len' (Some Len) # | BSeq", "5), Infix(Non()), list()), (\"<:\", (7, 7), Infix(Non()), list()), (\":>\", (7,", "(2, 2), Infix(Non()), [\"\\\\leadsto\"], nodes.LeadsTo()), (\"ENABLED\", (4, 15), Prefix(), list(),", "[ '\\\\otimes' ] ; # '\\\\uplus', ( 9,13), Infix(Left()), []", "'BOOLEAN' (Some BOOLEAN) # | SUBSET -> lookup 'SUBSET' #", "of operators.\"\"\" # Copyright 2020 by California Institute of Technology", "list()), (\"\\\\prec\", (5, 5), Infix(Non()), list()), (\"\\\\succ\", (5, 5), Infix(Non()),", "; # '#', ( 5, 5), Infix(Non()), [ '/=' ],", "with defn = Some Gteq } # | Gt ->", "[\"\\\\otimes\"]), (\"\\\\uplus\", (9, 13), Infix(Left()), list()), (\"\\\\sqcap\", (9, 13), Infix(Left()),", "; # '\\\\sqsubseteq', ( 5, 5), Infix(Non()), [] ; #", "List.map withdef [ # 'SUBSET', ( 8, 8), Prefix, [],", "(Some STRING) # | BOOLEAN -> nonfix 'BOOLEAN' (Some BOOLEAN)", "3, 3), Infix(Left()), [ '\\\\lor' ], Disj ; # '~',", "Infix(Left()), list()), (\"**\", (13, 13), Infix(Left()), list()), (\"//\", (13, 13),", "'^+', (15,15), Postfix, [] ; # '^*', (15,15), Postfix, []", "; # '::=', ( 5, 5), Infix(Non()), [] ; #", "Infix(Left()), list(), nodes.Cdot()), (\"-+->\", (2, 2), Infix(Non()), list(), nodes.WhilePlus()), (\"[]\",", "'?|'; # prec = (10, 11); # fix = Infix(Non());", "list()), (\"\\\\supset\", (5, 5), Infix(Non()), list()), (\"\\\\supseteq\", (5, 5), Infix(Non()),", "[] ; # '+', (10,10), Infix(Left()), [] ; # '^+',", "(5, 5), Infix(Non()), list()), (\"\\\\sqsubseteq\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupset\",", "[ '\\\\neg' ; '\\\\lnot' ], Neg ; # '=', (", "-> (name, prec, fix, als, None)) [ # '^', (14,14),", "'++', (10,10), Infix(Left()), [] ; # '--', (11,11), Infix(Left()), []", "'=>', ( 1, 1), Infix(Non()), [], Implies ; # '<=>',", "(13, 13), Infix(Non()), list()), (\"*\", (13, 13), Infix(Left()), list()), (\"-.\",", "4), Prefix, [ '\\\\neg' ; '\\\\lnot' ], Neg ; #", "Setminus ; # '\\\\cap', ( 8, 8), Infix(Left()), [ '\\\\intersect'", "5), Infix(Non()), [] ; # '::=', ( 5, 5), Infix(Non()),", "Tail -> nonfix 'Tail' (Some Tail) # | SubSeq ->", "(5, 5), Infix(Non()), list()), (\"\\\\cong\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubset\",", "; # '\\\\uplus', ( 9,13), Infix(Left()), [] ; # '\\\\sqcap',", "| Permutations -> nonfix 'Permutations' (Some Permutations) # | SortSeq", "# H.add tab name op ; # List.iter (fun s", "'<=>' # | Conj -> lookup '/\\\\' # | Disj", "'=<', ( 5, 5), Infix(Non()), [ '<=' ; '\\\\leq' ]", "Infix(Non()), [\"\\\\leadsto\"], nodes.LeadsTo()), (\"ENABLED\", (4, 15), Prefix(), list(), nodes.ENABLED()), (\"UNCHANGED\",", "Prefix(), list(), nodes.Diamond()), ], ), ( \"User\", [ (name, prec,", "; # '\\\\supset', ( 5, 5), Infix(Non()), [] ; #", "'&&', (13,13), Infix(Left()), [] ; # '&', (13,13), Infix(Left()), []", "Infix(Non()), [], Notmem ; # '\\\\', ( 8, 8), Infix(Non()),", "Prefix, [], ENABLED ; # 'UNCHANGED', ( 4,15), Prefix, [],", "# | Uminus -> { (lookup '-.') with defn =", "'/', (13,13), Infix(Non()), [] ; # '*', (13,13), Infix(Left()), []", "9, 9), Prefix, [], DOMAIN ; # '\\\\subseteq', ( 5,", "| ENABLED -> lookup 'ENABLED' # | UNCHANGED -> lookup", "Append -> nonfix 'Append' (Some Append) # | Cat ->", "Infix(Non()), [\"\\\\setminus\"], nodes.Setminus()), (\"\\\\cap\", (8, 8), Infix(Left()), [\"\\\\intersect\"], nodes.Cap()), (\"\\\\cup\",", "[ '-' ] ; # '-', (11,11), Infix(Left()), [] ;", "# '##', ( 9,13), Infix(Left()), [] ; # '++', (10,10),", "[] ; # '\\\\approx', ( 5, 5), Infix(Non()), [] ;", "# # This module is based on the file: #", "Prefix, [], SUBSET ; # 'UNION', ( 8, 8), Prefix,", "9,13), Infix(Left()), [] ; # '\\\\sqcup', ( 9,13), Infix(Left()), []", "'<') with defn = Some Lt } # | Gteq", "Infix(Left()), list()), (\"--\", (11, 11), Infix(Left()), list()), (\"**\", (13, 13),", "# '\\\\bullet', (13,13), Infix(Left()), [] ; # '\\\\prec', ( 5,", "defn = Some Lt } # | Gteq -> {", "= # | Nonfix # | Prefix | Postfix #", "; # '^+', (15,15), Postfix, [] ; # '^*', (15,15),", "[ '\\\\oplus' ] ; # '(-)', (11,11), Infix(Left()), [ '\\\\ominus'", "[\"\\\\oslash\"]), (\"(\\\\X)\", (13, 13), Infix(Left()), [\"\\\\otimes\"]), (\"\\\\uplus\", (9, 13), Infix(Left()),", "# | Extend -> { (lookup '@@') with defn =", "defn = Some Gteq } # | Gt -> {", "(\"(+)\", (10, 10), Infix(Left()), [\"\\\\oplus\"]), (\"(-)\", (11, 11), Infix(Left()), [\"\\\\ominus\"]),", "{ # name = '?|'; # prec = (10, 11);", "| Gteq -> { (lookup '>=') with defn = Some", "(\"(/)\", (13, 13), Infix(Non()), [\"\\\\oslash\"]), (\"(\\\\X)\", (13, 13), Infix(Left()), [\"\\\\otimes\"]),", "Prime ; # '~>', ( 2, 2), Infix(Non()), [ '\\\\leadsto'", "; # '\\\\notin', ( 5, 5), Infix(Non()), [], Notmem ;", "BOOLEAN) # | SUBSET -> lookup 'SUBSET' # | UNION", "'Len' (Some Len) # | BSeq -> nonfix 'BSeq' (Some", "nodes.DOMAIN()), (\"\\\\subseteq\", (5, 5), Infix(Non()), list(), nodes.Subseteq()), (\"\\\\in\", (5, 5),", "based on the file: # # <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> # import pprint", "Prefix, [], UNCHANGED ; # '\\\\cdot', ( 5,14), Infix(Left()), [],", ": string ; # prec : prec ; # fix", "'\\\\bigcirc', (13,13), Infix(Left()), [] ; # '\\\\bullet', (13,13), Infix(Left()), []", "Infix(Non()), [] ; # '\\\\supseteq', ( 5, 5), Infix(Non()), []", "SelectSeq -> nonfix 'SelectSeq' (Some SelectSeq) # # | OneArg", "(9, 9), Infix(Non()), list()), (\"|\", (10, 11), Infix(Left()), list()), (\"||\",", "(9, 13), Infix(Left()), list()), (\"++\", (10, 10), Infix(Left()), list()), (\"--\",", "-> lookup ''' # | Leadsto -> lookup '~>' #", "ops # end tlaops ; # tab def _generate_optable(): tlaops", "[ '\\\\geq' ] ; # '...', ( 9, 9), Infix(Non()),", "with defn = Some Gt } # | Range ->", "(lookup '@@') with defn = Some Extend } # |", "import pprint from .ast import Nodes as nodes # open", "list()), (\"\\\\o\", (13, 13), Infix(Left()), [\"\\\\circ\"]), (\"\\\\bigcirc\", (13, 13), Infix(Left()),", "# '|=', ( 5, 5), Infix(Non()), [] ; # '-|',", "(\":=\", (5, 5), Infix(Non()), list()), (\"::=\", (5, 5), Infix(Non()), list()),", "Infix(Left()), list()), (\"??\", (9, 13), Infix(Left()), list()), (\"%%\", (10, 11),", "| Left | Non | Right class Assoc: pass class", "_generate_optable(): tlaops = _generate_tlaops() optable = dict() for dom, ops", "-> lookup '<>' # # | Plus -> { (lookup", "; # '\\\\sim', ( 5, 5), Infix(Non()), [] ; #", "( 4,15), Prefix, [], Diamond ; # ] ; #", "pass class Right(Assoc): pass class Non(Assoc): pass # and dom", "def withdef(tuple_): name, prec, fix, als, defn = tuple_ return", "Sets, # [ '\\\\X', (10,13), Prefix, [ '\\\\times' ], None", "# let module H = Hashtbl in # let tab", "tab s op) als # end ops # end tlaops", "Prefix(), list(), nodes.UNCHANGED()), (\"\\\\cdot\", (5, 14), Infix(Left()), list(), nodes.Cdot()), (\"-+->\",", "(Some Any) # | ToString -> nonfix 'ToString' (Some ToString)", "-> { (lookup '*') with defn = Some Times }", "Infix(Non()), list()), (\"\\\\star\", (13, 13), Infix(Left()), list()), (\"\\\\o\", (13, 13),", "(9, 9), Infix(Non()), list()), (\"..\", (9, 9), Infix(Non()), list()), (\"|\",", "TRUE -> nonfix 'TRUE' (Some TRUE) # | FALSE ->", "( 2, 2), Infix(Non()), [ '\\\\equiv' ], Equiv ; #", "# | Notmem -> lookup '\\\\notin' # | Setminus ->", "'\\\\supset', ( 5, 5), Infix(Non()), [] ; # '\\\\supseteq', (", "Extend } # | Print -> nonfix 'Print' (Some Print)", "| Diamond -> lookup '<>' # # | Plus ->", "# '\\\\wr', ( 9,14), Infix(Non()), [] ; # '\\\\star', (13,13),", "(10, 11), Infix(Left()), list()), (\"&&\", (13, 13), Infix(Left()), list()), (\"&\",", "8), Prefix(), list(), nodes.UNION()), (\"DOMAIN\", (9, 9), Prefix(), list(), nodes.DOMAIN()),", "(\"||\", (10, 11), Infix(Left()), list()), (\"&&\", (13, 13), Infix(Left()), list()),", "Infix(Left()), [ '\\\\otimes' ] ; # '\\\\uplus', ( 9,13), Infix(Left()),", "# '\\\\simeq', ( 5, 5), Infix(Non()), [] ; # '\\\\ll',", "[\"\\\\circ\"]), (\"\\\\bigcirc\", (13, 13), Infix(Left()), list()), (\"\\\\bullet\", (13, 13), Infix(Left()),", "[\"\\\\mod\"]), (\"##\", (9, 13), Infix(Left()), list()), (\"++\", (10, 10), Infix(Left()),", "# | STRING -> nonfix 'STRING' (Some STRING) # |", "2), Infix(Non()), [ '\\\\equiv' ], Equiv ; # '/\\\\', (", "13), Infix(Left()), [\"\\\\otimes\"]), (\"\\\\uplus\", (9, 13), Infix(Left()), list()), (\"\\\\sqcap\", (9,", "{ name = name ; # prec = prec ;", "Uminus ; name = '-' } # | Times ->", "[ # Logic, # List.map withdef [ # '=>', (", "; # '|=', ( 5, 5), Infix(Non()), [] ; #", "fixity, dom, defn) optable.setdefault(name, list()) optable[name].append(op) for s in alternatives:", "; # '^#', (15,15), Postfix, [] ; # '<', (", "# '\\\\sqsupseteq', ( 5, 5), Infix(Non()), [] ; # '\\\\doteq',", "( 5, 5), Infix(Non()), [] ; # '<:', ( 7,", "lookup '<>' # # | Plus -> { (lookup '+')", "9), Prefix, [], DOMAIN ; # '\\\\subseteq', ( 5, 5),", "'SUBSET' # | UNION -> lookup 'UNION' # | DOMAIN", "Infix(Left()), list()), (\"\\\\bullet\", (13, 13), Infix(Left()), list()), (\"\\\\prec\", (5, 5),", "| Any -> nonfix 'Any' (Some Any) # | ToString", "(\"\\\\doteq\", (5, 5), Infix(Non()), list()), (\"\\\\propto\", (5, 5), Infix(Non()), list()),", "list()), (\"-.\", (12, 12), Prefix(), [\"-\"]), (\"-\", (11, 11), Infix(Left()),", "*) # let standard_form b = # match b with", "; # ':=', ( 5, 5), Infix(Non()), [] ; #", "# type tlaop = { # name : string ;", "fix, als, defn) -> # let op = { name", "'~' # | Eq -> lookup '=' # | Neq", "# | Quotient -> { (lookup '\\\\div') with defn =", "(\"=\", (5, 5), Infix(Non()), list(), nodes.Eq()), (\"#\", (5, 5), Infix(Non()),", "4, 4), Prefix, [ '\\\\neg' ; '\\\\lnot' ], Neg ;", "Infix(Fixity): def __init__(self, assoc): self.assoc = assoc # and assoc", "dom, ops in tlaops: for name, prec, fixity, alternatives, defn", "5, 5), Infix(Non()), [] ; # '|=', ( 5, 5),", "list()), (\"??\", (9, 13), Infix(Left()), list()), (\"%%\", (10, 11), Infix(Left()),", "( 8, 8), Infix(Non()), [], Setminus ; # '\\\\cap', (", "Some Range } # | Nat -> nonfix 'Nat' (Some", "list()), (\"<\", (5, 5), Infix(Non()), list()), (\"=<\", (5, 5), Infix(Non()),", "; # '\\\\wr', ( 9,14), Infix(Non()), [] ; # '\\\\star',", "( 5, 5), Infix(Non()), [] ; # '\\\\cong', ( 5,", "name, prec, fix, als, defn = tuple_ return (name, prec,", "[] ; # ':>', ( 7, 7), Infix(Non()), [] ;", "'^#', (15,15), Postfix, [] ; # '<', ( 5, 5),", "pass class Prefix(Fixity): pass class Postfix(Fixity): pass class Infix(Fixity): def", "(10,11), Infix(Left()), [] ; # '%', (10,11), Infix(Non()), [ '\\\\mod'", "Postfix(), list(), nodes.Prime()), (\"~>\", (2, 2), Infix(Non()), [\"\\\\leadsto\"], nodes.LeadsTo()), (\"ENABLED\",", "f\"TLAOP({self.name}, {self.prec}, \" f\"{self.fix}, {self.dom}, {self.defn})\" ) # let optable", "tlaops ; # tab def _generate_optable(): tlaops = _generate_tlaops() optable", "( 5, 5), Infix(Non()), [] ; # '\\\\sqsupset', ( 5,", "Plus } # | Minus -> { (lookup '-') with", "'-+->', ( 2, 2), Infix(Non()), [], Actplus ; # '[]',", "[] ; # '%', (10,11), Infix(Non()), [ '\\\\mod' ] ;", "[\"\\\\odot\"]), (\"(/)\", (13, 13), Infix(Non()), [\"\\\\oslash\"]), (\"(\\\\X)\", (13, 13), Infix(Left()),", "(\"^+\", (15, 15), Postfix(), list()), (\"^*\", (15, 15), Postfix(), list()),", "7, 7), Infix(Non()), [] ; # ':>', ( 7, 7),", "| Real -> nonfix 'Real' (Some Real) # | Infinity", "Eq -> lookup '=' # | Neq -> lookup '#'", "(13, 13), Infix(Non()), list()), (\"\\\\wr\", (9, 14), Infix(Non()), list()), (\"\\\\star\",", "list()), (\"\\\\cong\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubset\", (5, 5), Infix(Non()),", "= {\"Logic\", \"Sets\", \"Modal\", \"User\"} # type prec = int", "# | Int -> nonfix 'Int' (Some Int) # |", "[] ; # '\\\\succ', ( 5, 5), Infix(Non()), [] ;", "lookup '=' # | Neq -> lookup '#' # |", "| Implies -> lookup '=>' # | Equiv -> lookup", "# 'SUBSET', ( 8, 8), Prefix, [], SUBSET ; #", "; # User, # List.map (fun (name, prec, fix, als)", "Implies ; # '<=>', ( 2, 2), Infix(Non()), [ '\\\\equiv'", "= dict() for dom, ops in tlaops: for name, prec,", "# '\\\\cap', ( 8, 8), Infix(Left()), [ '\\\\intersect' ], Cap", "(5, 5), Infix(Non()), list()), (\"\\\\gg\", (5, 5), Infix(Non()), list()), (\"\\\\asymp\",", "7, 7), Infix(Non()), [] ; # ':=', ( 5, 5),", "(\"=>\", (1, 1), Infix(Non()), list(), nodes.Implies()), (\"<=>\", (2, 2), Infix(Non()),", "5), Infix(Non()), list()), (\"|=\", (5, 5), Infix(Non()), list()), (\"-|\", (5,", "with defn = Some Range } # | Nat ->", "11), Infix(Left()), list()), (\"||\", (10, 11), Infix(Left()), list()), (\"&&\", (13,", "Infix(Non()), [] ; # '\\\\sqsubseteq', ( 5, 5), Infix(Non()), []", "nodes # open Builtin # type fixity = # |", "nodes.Implies()), (\"<=>\", (2, 2), Infix(Non()), [\"\\\\equiv\"], nodes.Equiv()), (\"/\\\\\", (3, 3),", "# | BOOLEAN -> nonfix 'BOOLEAN' (Some BOOLEAN) # |", "'%', (10,11), Infix(Non()), [ '\\\\mod' ] ; # '##', (", "Infix(Left()), [] ; # '$', ( 9,13), Infix(Left()), [] ;", "'DOMAIN', ( 9, 9), Prefix, [], DOMAIN ; # '\\\\subseteq',", "module H = Hashtbl in # let tab = H.create", "= # match b with # | TRUE -> nonfix", "nonfix 'Int' (Some Int) # | Real -> nonfix 'Real'", "'\\\\lnot' ], Neg ; # '=', ( 5, 5), Infix(Non()),", "* int class Prec: def __init__(self, a, b): self.a =", "# # <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> # import pprint from .ast import Nodes", "(13,13), Infix(Non()), [] ; # '*', (13,13), Infix(Left()), [] ;", "(Some Infinity) # # | Seq -> nonfix 'Seq' (Some", "'UNCHANGED' # | Cdot -> lookup '\\\\cdot' # | Actplus", "( 5, 5), Infix(Non()), [] ; # ] ; #", "{\"Logic\", \"Sets\", \"Modal\", \"User\"} # type prec = int *", "-> nonfix 'Nat' (Some Nat) # | Int -> nonfix", "| Neg -> lookup '~' # | Eq -> lookup", "Prefix | Postfix # | Infix of assoc class Fixity:", "'\\\\in' # | Notmem -> lookup '\\\\notin' # | Setminus", "als in [ (\"^\", (14, 14), Infix(Non()), list()), (\"/\", (13,", "ops in tlaops: for name, prec, fixity, alternatives, defn in", "lookup ''' # | StrongPrime -> lookup ''' # |", "), ( \"Sets\", [ (\"SUBSET\", (8, 8), Prefix(), list(), nodes.SUBSET()),", "5), Infix(Non()), [] ; # '\\\\sqsubseteq', ( 5, 5), Infix(Non()),", "Infix(Left()), [], Cdot ; # '-+->', ( 2, 2), Infix(Non()),", "-> lookup '\\\\subseteq' # | Mem -> lookup '\\\\in' #", "Infix(Non()), [], Setminus ; # '\\\\cap', ( 8, 8), Infix(Left()),", "list(), nodes.Implies()), (\"<=>\", (2, 2), Infix(Non()), [\"\\\\equiv\"], nodes.Equiv()), (\"/\\\\\", (3,", "(\"\\\\cong\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubset\", (5, 5), Infix(Non()), list()),", "nodes.Cap()), (\"\\\\cup\", (8, 8), Infix(Left()), [\"\\\\union\"], nodes.Cup()), (\"\\\\X\", (10, 13),", "(name, prec, fix, als, defn) -> # let op =", "'ToString' (Some ToString) # # | Unprimable -> nonfix 'Unprimable'", "list()), (\"\\\\sim\", (5, 5), Infix(Non()), list()), (\"\\\\simeq\", (5, 5), Infix(Non()),", "} # | Extend -> { (lookup '@@') with defn", "'SUBSET', ( 8, 8), Prefix, [], SUBSET ; # 'UNION',", "list()), (\"^*\", (15, 15), Postfix(), list()), (\"^#\", (15, 15), Postfix(),", "5, 5), Infix(Non()), [] ; # '=<', ( 5, 5),", "Infix(Left()), [] ; # '&', (13,13), Infix(Left()), [] ; #", "'-' ] ; # '-', (11,11), Infix(Left()), [] ; #", "( 9,13), Infix(Left()), [] ; # '\\\\sqcup', ( 9,13), Infix(Left()),", "{ (lookup '@@') with defn = Some Extend } #", "tuple_ return (name, prec, fix, als, defn) # let tlaops", "Infix(Non()), [] ; # '\\\\sim', ( 5, 5), Infix(Non()), []", "Infix(Left()), [\"\\\\lor\"], nodes.Disj()), (\"~\", (4, 4), Prefix(), [\"\\\\neg\", \"\\\\lnot\"], nodes.Neg()),", "(4, 15), Prefix(), list(), nodes.Diamond()), ], ), ( \"User\", [", "# and dom = # (* primitive operators *) #", "(13, 13), Infix(Left()), list()), (\"\\\\bullet\", (13, 13), Infix(Left()), list()), (\"\\\\prec\",", "'\\\\' # | Cap -> lookup '\\\\cap' # | Cup", "10), Infix(Left()), list()), (\"^+\", (15, 15), Postfix(), list()), (\"^*\", (15,", "'/') with defn = Some Ratio } # | Quotient", "# | SUBSET -> lookup 'SUBSET' # | UNION ->", "5), Infix(Non()), list()), (\"\\\\succeq\", (5, 5), Infix(Non()), list()), (\"\\\\sim\", (5,", "# '&&', (13,13), Infix(Left()), [] ; # '&', (13,13), Infix(Left()),", "; # '..', ( 9, 9), Infix(Non()), [] ; #", "-> nonfix 'FALSE' (Some FALSE) # | Implies -> lookup", "# '\\\\in', ( 5, 5), Infix(Non()), [], Mem ; #", "# '(/)', (13,13), Infix(Non()), [ '\\\\oslash' ] ; # '(\\\\X)',", "} # | Uminus -> { (lookup '-.') with defn", "TLCGet) # | TLCSet -> nonfix 'TLCSet' (Some TLCSet) #", "[] ; # '&', (13,13), Infix(Left()), [] ; # '$$',", "# '??', ( 9,13), Infix(Left()), [] ; # '%%', (10,11),", "Infix(Left()), list()), (\"-.\", (12, 12), Prefix(), [\"-\"]), (\"-\", (11, 11),", "5), Infix(Non()), list()), (\"\\\\subset\", (5, 5), Infix(Non()), list()), (\"\\\\supset\", (5,", "Infix(Left()), list()), (\"$$\", (9, 13), Infix(Left()), list()), (\"$\", (9, 13),", "list()), (\"+\", (10, 10), Infix(Left()), list()), (\"^+\", (15, 15), Postfix(),", "# List.iter begin # fun (dom, ops) -> # List.iter", "[], Subseteq ; # '\\\\in', ( 5, 5), Infix(Non()), [],", "( 5, 5), Infix(Non()), [] ; # '\\\\doteq', ( 5,", "(15, 15), Postfix(), list(), nodes.Prime()), (\"~>\", (2, 2), Infix(Non()), [\"\\\\leadsto\"],", "# # | OneArg -> { (lookup ':>') with defn", "[\"/=\"], nodes.Neq()), ], ), ( \"Sets\", [ (\"SUBSET\", (8, 8),", "(Some Int) # | Real -> nonfix 'Real' (Some Real)", "(\"'\", (15, 15), Postfix(), list(), nodes.Prime()), (\"~>\", (2, 2), Infix(Non()),", "[\"\\\\times\"], None), ], ), ( \"Modal\", [ (\"'\", (15, 15),", "name, prec, fixity, dom, defn): self.name = name # str", "nodes.Prime()), (\"~>\", (2, 2), Infix(Non()), [\"\\\\leadsto\"], nodes.LeadsTo()), (\"ENABLED\", (4, 15),", "# '--', (11,11), Infix(Left()), [] ; # '**', (13,13), Infix(Left()),", "'ENABLED', ( 4,15), Prefix, [], ENABLED ; # 'UNCHANGED', (", "(\"$\", (9, 13), Infix(Left()), list()), (\"??\", (9, 13), Infix(Left()), list()),", "; # '%', (10,11), Infix(Non()), [ '\\\\mod' ] ; #", "# pprint.pprint(optable) # let nonfix name defn = # {", "# '&', (13,13), Infix(Left()), [] ; # '$$', ( 9,13),", "Infix(Left()), list()), (\"$\", (9, 13), Infix(Left()), list()), (\"??\", (9, 13),", "-> nonfix 'BSeq' (Some BSeq) # | Append -> nonfix", "# Modal, # List.map withdef [ # ''', (15,15), Postfix,", "lookup '<=>' # | Conj -> lookup '/\\\\' # |", "5, 5), Infix(Non()), [] ; # '=|', ( 5, 5),", "'>=') with defn = Some Gteq } # | Gt", "| OneArg -> { (lookup ':>') with defn = Some", "Prefix, [], UNION ; # 'DOMAIN', ( 9, 9), Prefix,", "Infix(Left()), [] ; # '**', (13,13), Infix(Left()), [] ; #", "[ # '^', (14,14), Infix(Non()), [] ; # '/', (13,13),", "Infix(Left()), [] ; # '%%', (10,11), Infix(Left()), [] ; #", "Infix(Left()), list()), (\"&\", (13, 13), Infix(Left()), list()), (\"$$\", (9, 13),", "'\\\\o', (13,13), Infix(Left()), [ '\\\\circ' ] ; # '\\\\bigcirc', (13,13),", "13), Infix(Left()), list()), (\"$$\", (9, 13), Infix(Left()), list()), (\"$\", (9,", "; # '@@', ( 6, 6), Infix(Left()), [] ; #", "# '=', ( 5, 5), Infix(Non()), [], Eq ; #", "type fixity = # | Nonfix # | Prefix |", "and Microsoft Corporation # All rights reserved. Licensed under 3-clause", "true ; # '<>', ( 4,15), Prefix, [], Diamond ;", "(Some Real) # | Infinity -> nonfix 'Infinity' (Some Infinity)", "'\\\\lor' ], Disj ; # '~', ( 4, 4), Prefix,", "'\\\\simeq', ( 5, 5), Infix(Non()), [] ; # '\\\\ll', (", "'\\\\sqsupset', ( 5, 5), Infix(Non()), [] ; # '\\\\sqsupseteq', (", "; # 'ENABLED', ( 4,15), Prefix, [], ENABLED ; #", "( 4, 4), Prefix, [ '\\\\neg' ; '\\\\lnot' ], Neg", "(14, 14), Infix(Non()), list()), (\"@@\", (6, 6), Infix(Left()), list()), (\"!!\",", "'\\\\cap', ( 8, 8), Infix(Left()), [ '\\\\intersect' ], Cap ;", "# ] ; # Sets, # List.map withdef [ #", "prec, fix, als in [ (\"^\", (14, 14), Infix(Non()), list()),", "(\"\\\\subseteq\", (5, 5), Infix(Non()), list(), nodes.Subseteq()), (\"\\\\in\", (5, 5), Infix(Non()),", "# List.map withdef [ # 'SUBSET', ( 8, 8), Prefix,", "5), Infix(Non()), [\"\\\\geq\"]), (\"...\", (9, 9), Infix(Non()), list()), (\"..\", (9,", "self.a = a self.b = b # let withdef (name,", "[] ; # '/', (13,13), Infix(Non()), [] ; # '*',", "from builtins to standard tlaops *) # let standard_form b", "(9, 9), Prefix(), list(), nodes.DOMAIN()), (\"\\\\subseteq\", (5, 5), Infix(Non()), list(),", "name = '-' } # | Times -> { (lookup", "5), Infix(Non()), [\"/=\"], nodes.Neq()), ], ), ( \"Sets\", [ (\"SUBSET\",", "5, 5), Infix(Non()), [], Notmem ; # '\\\\', ( 8,", "| Plus -> { (lookup '+') with defn = Some", "# | Disj -> lookup '\\\\/' # | Neg ->", "defn in ops: op = TLAOP(name, prec, fixity, dom, defn)", "# Copyright 2020 by California Institute of Technology # Copyright", "Real) # | Infinity -> nonfix 'Infinity' (Some Infinity) #", "# '-|', ( 5, 5), Infix(Non()), [] ; # '=|',", "[] ; # '\\\\sim', ( 5, 5), Infix(Non()), [] ;", "name None # # (** Mapping from builtins to standard", "| Logic | Sets | Modal # (* user-definable operators", "# Logic, # List.map withdef [ # '=>', ( 1,", "5), Infix(Non()), [] ; # '\\\\asymp', ( 5, 5), Infix(Non()),", "list()), (\"--\", (11, 11), Infix(Left()), list()), (\"**\", (13, 13), Infix(Left()),", "list()), (\"(+)\", (10, 10), Infix(Left()), [\"\\\\oplus\"]), (\"(-)\", (11, 11), Infix(Left()),", "list()), (\"\\\\sqcap\", (9, 13), Infix(Left()), list()), (\"\\\\sqcup\", (9, 13), Infix(Left()),", "'##', ( 9,13), Infix(Left()), [] ; # '++', (10,10), Infix(Left()),", "[] ; # '<', ( 5, 5), Infix(Non()), [] ;", "defn = Some Range } # | Nat -> nonfix", "Infix(Non()), list()), (\":=\", (5, 5), Infix(Non()), list()), (\"::=\", (5, 5),", "11), Infix(Left()), list()), (\"&&\", (13, 13), Infix(Left()), list()), (\"&\", (13,", "# | UNION -> lookup 'UNION' # | DOMAIN ->", "'%%', (10,11), Infix(Left()), [] ; # '%', (10,11), Infix(Non()), [", "Infix(Non()); # dom = Logic; # defn = Some Divides;", "] ; # User, # List.map (fun (name, prec, fix,", "[], Setminus ; # '\\\\cap', ( 8, 8), Infix(Left()), [", "3-clause BSD. # # This module is based on the", "(10, 13), Infix(Left()), [\"\\\\times\"], None), ], ), ( \"Modal\", [", "list(), nodes.SUBSET()), (\"UNION\", (8, 8), Prefix(), list(), nodes.UNION()), (\"DOMAIN\", (9,", "lookup '\\\\' # | Cap -> lookup '\\\\cap' # |", "prec = (-1, -1) ; # fix = Nonfix ;", "-> { (lookup '/') with defn = Some Ratio }", "; # '[]', ( 4,15), Prefix, [], Box true ;", "OneArg } # | Extend -> { (lookup '@@') with", "'Permutations' (Some Permutations) # | SortSeq -> nonfix 'SortSeq' (Some", "Infix(Left()), [] ; # '\\\\prec', ( 5, 5), Infix(Non()), []", "= prec # Prec self.fix = fixity # Fixity self.dom", "# name, prec, fix, als, Some defn);; def withdef(tuple_): name,", "(15,15), Postfix, [] ; # '<', ( 5, 5), Infix(Non()),", "'/\\\\' # | Disj -> lookup '\\\\/' # | Neg", "'TLCSet' (Some TLCSet) # | Permutations -> nonfix 'Permutations' (Some", "# fix = fix ; dom = dom ; #", "nodes.Cdot()), (\"-+->\", (2, 2), Infix(Non()), list(), nodes.WhilePlus()), (\"[]\", (4, 15),", "(\"\\\\cup\", (8, 8), Infix(Left()), [\"\\\\union\"], nodes.Cup()), (\"\\\\X\", (10, 13), Infix(Left()),", "with defn = Some Minus } # | Uminus ->", "; # '\\\\bigcirc', (13,13), Infix(Left()), [] ; # '\\\\bullet', (13,13),", "Infix(Non()), [\"\\\\equiv\"], nodes.Equiv()), (\"/\\\\\", (3, 3), Infix(Left()), [\"\\\\land\"], nodes.Conj()), (\"\\\\/\",", "# '(+)', (10,10), Infix(Left()), [ '\\\\oplus' ] ; # '(-)',", "= Some Range } # | Nat -> nonfix 'Nat'", "# let standard_form b = # match b with #", "; # '\\\\doteq', ( 5, 5), Infix(Non()), [] ; #", "Some Remainder } # | Exp -> { (lookup '^')", "let module H = Hashtbl in # let tab =", "'^', (14,14), Infix(Non()), [] ; # '/', (13,13), Infix(Non()), []", "( \"Logic\", [ (\"=>\", (1, 1), Infix(Non()), list(), nodes.Implies()), (\"<=>\",", "{ (lookup '*') with defn = Some Times } #", "5, 5), Infix(Non()), [] ; # '\\\\sqsupset', ( 5, 5),", "; # fix = Nonfix ; dom = User ;", "13), Infix(Left()), list()), (\"\\\\o\", (13, 13), Infix(Left()), [\"\\\\circ\"]), (\"\\\\bigcirc\", (13,", "'<>' # # | Plus -> { (lookup '+') with", "Minus -> { (lookup '-') with defn = Some Minus", "list()), (\"\\\\supseteq\", (5, 5), Infix(Non()), list()), (\"\\\\approx\", (5, 5), Infix(Non()),", "(5, 5), Infix(Non()), list()), (\"\\\\approx\", (5, 5), Infix(Non()), list()), (\"\\\\cong\",", "Licensed under 3-clause BSD. # # This module is based", "prec, fix, als, defn) # let tlaops = [ #", "'#', ( 5, 5), Infix(Non()), [ '/=' ], Neq ;", "5, 5), Infix(Non()), [], Mem ; # '\\\\notin', ( 5,", "(10, 10), Infix(Left()), [\"\\\\oplus\"]), (\"(-)\", (11, 11), Infix(Left()), [\"\\\\ominus\"]), (\"(.)\",", "optable name # else # nonfix name None # #", "5, 5), Infix(Non()), [] ; # '\\\\supset', ( 5, 5),", "= Some Divides; # } # # | STRING ->", "} # | Print -> nonfix 'Print' (Some Print) #", "[ '/=' ], Neq ; # ] ; # Sets,", "end ops # end tlaops ; # tab def _generate_optable():", "nodes.ENABLED()), (\"UNCHANGED\", (4, 15), Prefix(), list(), nodes.UNCHANGED()), (\"\\\\cdot\", (5, 14),", "prec, fix, als, defn) = ( # name, prec, fix,", "(lookup '\\\\o') with defn = Some Cat } # |", "-> lookup 'UNCHANGED' # | Cdot -> lookup '\\\\cdot' #", "; # '||', (10,11), Infix(Left()), [] ; # '&&', (13,13),", "= Some Quotient } # | Remainder -> { (lookup", "# '//', (13,13), Infix(Non()), [] ; # '^^', (14,14), Infix(Non()),", "list()), (\"%%\", (10, 11), Infix(Left()), list()), (\"%\", (10, 11), Infix(Non()),", "lookup 'UNCHANGED' # | Cdot -> lookup '\\\\cdot' # |", "defn = Some Uminus ; name = '-' } #", "Diamond -> lookup '<>' # # | Plus -> {", "list()), (\"\\\\star\", (13, 13), Infix(Left()), list()), (\"\\\\o\", (13, 13), Infix(Left()),", "Infix(Left()), list()), (\"\\\\div\", (13, 13), Infix(Non()), list()), (\"\\\\wr\", (9, 14),", "Fixity: pass class Nonfix(Fixity): pass class Prefix(Fixity): pass class Postfix(Fixity):", "# | Range -> { (lookup '..') with defn =", "# '=>', ( 1, 1), Infix(Non()), [], Implies ; #", "of assoc class Fixity: pass class Nonfix(Fixity): pass class Prefix(Fixity):", "list()), (\"..\", (9, 9), Infix(Non()), list()), (\"|\", (10, 11), Infix(Left()),", "fixity, dom, defn): self.name = name # str self.prec =", "# nonfix name None # # (** Mapping from builtins", "13), Infix(Left()), list()), (\"%%\", (10, 11), Infix(Left()), list()), (\"%\", (10,", "5), Infix(Non()), list()), (\"\\\\doteq\", (5, 5), Infix(Non()), list()), (\"\\\\propto\", (5,", "'*', (13,13), Infix(Left()), [] ; # '-.', (12,12), Prefix, [", "(13,13), Infix(Non()), [] ; # '^^', (14,14), Infix(Non()), [] ;", "[], Box true ; # '<>', ( 4,15), Prefix, [],", "prec, fixity, dom, defn) optable.setdefault(name, list()) optable[name].append(op) for s in", "13), Infix(Left()), list()), (\"??\", (9, 13), Infix(Left()), list()), (\"%%\", (10,", "defn): self.name = name # str self.prec = prec #", "| UNCHANGED -> lookup 'UNCHANGED' # | Cdot -> lookup", "# | Cdot -> lookup '\\\\cdot' # | Actplus ->", "lookup '/\\\\' # | Disj -> lookup '\\\\/' # |", "'=>' # | Equiv -> lookup '<=>' # | Conj", "'//', (13,13), Infix(Non()), [] ; # '^^', (14,14), Infix(Non()), []", "nonfix 'FALSE' (Some FALSE) # | Implies -> lookup '=>'", "'SubSeq' (Some SubSeq) # | SelectSeq -> nonfix 'SelectSeq' (Some", "5), Infix(Non()), list()), (\"\\\\simeq\", (5, 5), Infix(Non()), list()), (\"\\\\ll\", (5,", "Some defn);; def withdef(tuple_): name, prec, fix, als, defn =", "'\\\\cup', ( 8, 8), Infix(Left()), [ '\\\\union' ], Cup ;", "{ (lookup '\\\\div') with defn = Some Quotient } #", "= dom ; # defn = defn } # in", "'\\\\div', (13,13), Infix(Non()), [] ; # '\\\\wr', ( 9,14), Infix(Non()),", "nodes.Eq()), (\"#\", (5, 5), Infix(Non()), [\"/=\"], nodes.Neq()), ], ), (", "(\"\\\\sqsupset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupseteq\", (5, 5), Infix(Non()), list()),", "Some Divides; # } # # | STRING -> nonfix", "5), Infix(Non()), list()), (\">=\", (5, 5), Infix(Non()), [\"\\\\geq\"]), (\"...\", (9,", "(5, 5), Infix(Non()), list()), (\"(+)\", (10, 10), Infix(Left()), [\"\\\\oplus\"]), (\"(-)\",", "optable name then # Hashtbl.find optable name # else #", "-> lookup ''' # | StrongPrime -> lookup ''' #", "(lookup '-') with defn = Some Minus } # |", "4,15), Prefix, [], Diamond ; # ] ; # User,", "-> nonfix 'SortSeq' (Some SortSeq) # | RandomElement -> nonfix", "11), Infix(Non()), [\"\\\\mod\"]), (\"##\", (9, 13), Infix(Left()), list()), (\"++\", (10,", "(lookup '..') with defn = Some Range } # |", "name then # Hashtbl.find optable name # else # nonfix", "(name, prec, fix, als, None) for name, prec, fix, als", "nonfix 'Nat' (Some Nat) # | Int -> nonfix 'Int'", "'BSeq' (Some BSeq) # | Append -> nonfix 'Append' (Some", "; # '\\\\succ', ( 5, 5), Infix(Non()), [] ; #", "# '%', (10,11), Infix(Non()), [ '\\\\mod' ] ; # '##',", "'\\\\cong', ( 5, 5), Infix(Non()), [] ; # '\\\\sqsubset', (", "; defn = defn } # # let lookup name", "STRING -> nonfix 'STRING' (Some STRING) # | BOOLEAN ->", "(\"..\", (9, 9), Infix(Non()), list()), (\"|\", (10, 11), Infix(Left()), list()),", "[], DOMAIN ; # '\\\\subseteq', ( 5, 5), Infix(Non()), [],", "Lteq -> { (lookup '=<') with defn = Some Lteq", "| JavaTime -> nonfix 'JavaTime' (Some JavaTime) # | TLCGet", "list(), nodes.ENABLED()), (\"UNCHANGED\", (4, 15), Prefix(), list(), nodes.UNCHANGED()), (\"\\\\cdot\", (5,", "; # '=|', ( 5, 5), Infix(Non()), [] ; #", "(\"\\\\bigcirc\", (13, 13), Infix(Left()), list()), (\"\\\\bullet\", (13, 13), Infix(Left()), list()),", "'^^', (14,14), Infix(Non()), [] ; # '@@', ( 6, 6),", "-> { (lookup '=<') with defn = Some Lteq }", "-> lookup '#' # | Divides -> # { #", "Infix(Non()), [] ; # '\\\\cong', ( 5, 5), Infix(Non()), []", "(\"\\\\in\", (5, 5), Infix(Non()), list(), nodes.Mem()), (\"\\\\notin\", (5, 5), Infix(Non()),", "the file: # # <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> # import pprint from .ast", "Builtin.builtin option ; # } class TLAOP: def __init__(self, name,", "], Conj ; # '\\\\/', ( 3, 3), Infix(Left()), [", "list()), (\"|\", (10, 11), Infix(Left()), list()), (\"||\", (10, 11), Infix(Left()),", "list()), (\"/\", (13, 13), Infix(Non()), list()), (\"*\", (13, 13), Infix(Left()),", "(lookup '*') with defn = Some Times } # |", "'>=', ( 5, 5), Infix(Non()), [ '\\\\geq' ] ; #", "], Disj ; # '~', ( 4, 4), Prefix, [", "8), Infix(Left()), [\"\\\\union\"], nodes.Cup()), (\"\\\\X\", (10, 13), Infix(Left()), [\"\\\\times\"], None),", "13), Infix(Left()), list()), (\"//\", (13, 13), Infix(Non()), list()), (\"^^\", (14,", "_ -> lookup '[]' # | Diamond -> lookup '<>'", "6), Infix(Left()), list()), (\"!!\", (9, 13), Infix(Non()), list()), (\"|-\", (5,", "[ '\\\\mod' ] ; # '##', ( 9,13), Infix(Left()), []", "lookup '~>' # | ENABLED -> lookup 'ENABLED' # |", "JavaTime) # | TLCGet -> nonfix 'TLCGet' (Some TLCGet) #", "(13,13), Infix(Non()), [ '\\\\oslash' ] ; # '(\\\\X)', (13,13), Infix(Left()),", "15), Postfix(), list()), (\"^#\", (15, 15), Postfix(), list()), (\"<\", (5,", "nonfix 'SelectSeq' (Some SelectSeq) # # | OneArg -> {", "Nonfix(Fixity): pass class Prefix(Fixity): pass class Postfix(Fixity): pass class Infix(Fixity):", "], Cup ; # ] ; # Sets, # [", "5), Infix(Non()), [] ; # '=|', ( 5, 5), Infix(Non()),", "(15,15), Postfix, [] ; # '^#', (15,15), Postfix, [] ;", "Infix(Non()), list()), (\"\\\\gg\", (5, 5), Infix(Non()), list()), (\"\\\\asymp\", (5, 5),", "_generate_optable() # pprint.pprint(optable) # let nonfix name defn = #", "| Assert -> nonfix 'Assert' (Some Assert) # | JavaTime", "-> nonfix 'Int' (Some Int) # | Real -> nonfix", "[], Cdot ; # '-+->', ( 2, 2), Infix(Non()), [],", "-> nonfix 'STRING' (Some STRING) # | BOOLEAN -> nonfix", "| Modal # (* user-definable operators *) # | User", "Infix(Non()), [ '\\\\geq' ] ; # '...', ( 9, 9),", "| TRUE -> nonfix 'TRUE' (Some TRUE) # | FALSE", "; # '\\\\sqcup', ( 9,13), Infix(Left()), [] ; # '\\\\div',", "list()), (\"-|\", (5, 5), Infix(Non()), list()), (\"=|\", (5, 5), Infix(Non()),", "Cup ; # ] ; # Sets, # [ '\\\\X',", "list()), (\"^^\", (14, 14), Infix(Non()), list()), (\"@@\", (6, 6), Infix(Left()),", "# '~', ( 4, 4), Prefix, [ '\\\\neg' ; '\\\\lnot'", "; # '(-)', (11,11), Infix(Left()), [ '\\\\ominus' ] ; #", "; # '\\\\propto', ( 5, 5), Infix(Non()), [] ; #", "<reponame>informalsystems/modelator-py \"\"\"Table of operators.\"\"\" # Copyright 2020 by California Institute", "# '\\\\propto', ( 5, 5), Infix(Non()), [] ; # ]", "( 5, 5), Infix(Non()), [] ; # '|=', ( 5,", "Mem -> lookup '\\\\in' # | Notmem -> lookup '\\\\notin'", "Box _ -> lookup '[]' # | Diamond -> lookup", "# open Builtin # type fixity = # | Nonfix", "9), Infix(Non()), list()), (\"|\", (10, 11), Infix(Left()), list()), (\"||\", (10,", "(\"\\\\ll\", (5, 5), Infix(Non()), list()), (\"\\\\gg\", (5, 5), Infix(Non()), list()),", "# { name = name ; prec = (-1, -1)", "Assert -> nonfix 'Assert' (Some Assert) # | JavaTime ->", "nonfix 'BOOLEAN' (Some BOOLEAN) # | SUBSET -> lookup 'SUBSET'", "= Some Gt } # | Range -> { (lookup", "'-' } # | Times -> { (lookup '*') with", "# | RandomElement -> nonfix 'RandomElement' (Some RandomElement) # |", "list()), (\"**\", (13, 13), Infix(Left()), list()), (\"//\", (13, 13), Infix(Non()),", "fix, als, defn = tuple_ return (name, prec, fix, als,", "(5, 5), Infix(Non()), [\"\\\\geq\"]), (\"...\", (9, 9), Infix(Non()), list()), (\"..\",", "tab name op ; # List.iter (fun s -> H.add", "tlaop = { # name : string ; # prec", "'=' # | Neq -> lookup '#' # | Divides", "Infix(Non()), [ '\\\\mod' ] ; # '##', ( 9,13), Infix(Left()),", "Institute of Technology # Copyright (c) 2008-2013 INRIA and Microsoft", "( 4,15), Prefix, [], UNCHANGED ; # '\\\\cdot', ( 5,14),", "9), Infix(Non()), list()), (\"..\", (9, 9), Infix(Non()), list()), (\"|\", (10,", "(13,13), Infix(Left()), [] ; # '\\\\prec', ( 5, 5), Infix(Non()),", "= { # name : string ; # prec :", "Infix(Left()), list()), (\"++\", (10, 10), Infix(Left()), list()), (\"--\", (11, 11),", "SortSeq) # | RandomElement -> nonfix 'RandomElement' (Some RandomElement) #", "] ; # '##', ( 9,13), Infix(Left()), [] ; #", "; # '\\\\prec', ( 5, 5), Infix(Non()), [] ; #", "15), Postfix(), list()), (\"^*\", (15, 15), Postfix(), list()), (\"^#\", (15,", "(13, 13), Infix(Left()), [\"\\\\odot\"]), (\"(/)\", (13, 13), Infix(Non()), [\"\\\\oslash\"]), (\"(\\\\X)\",", "class Left(Assoc): pass class Right(Assoc): pass class Non(Assoc): pass #", "; # defn : Builtin.builtin option ; # } class", "5), Infix(Non()), list()), (\"\\\\sqsupseteq\", (5, 5), Infix(Non()), list()), (\"\\\\doteq\", (5,", "[] ; # '||', (10,11), Infix(Left()), [] ; # '&&',", "'\\\\sqcap', ( 9,13), Infix(Left()), [] ; # '\\\\sqcup', ( 9,13),", "15), Prefix(), list(), nodes.ENABLED()), (\"UNCHANGED\", (4, 15), Prefix(), list(), nodes.UNCHANGED()),", "Infix(Non()), [], nodes.Notmem()), (\"\\\\\", (8, 8), Infix(Non()), [\"\\\\setminus\"], nodes.Setminus()), (\"\\\\cap\",", "( 2, 2), Infix(Non()), [], Actplus ; # '[]', (", "'\\\\oplus' ] ; # '(-)', (11,11), Infix(Left()), [ '\\\\ominus' ]", "(Some Len) # | BSeq -> nonfix 'BSeq' (Some BSeq)", "(\"(-)\", (11, 11), Infix(Left()), [\"\\\\ominus\"]), (\"(.)\", (13, 13), Infix(Left()), [\"\\\\odot\"]),", "| Gt -> { (lookup '>') with defn = Some", "Infix(Left()), [\"\\\\times\"], None), ], ), ( \"Modal\", [ (\"'\", (15,", "[\"\\\\setminus\"], nodes.Setminus()), (\"\\\\cap\", (8, 8), Infix(Left()), [\"\\\\intersect\"], nodes.Cap()), (\"\\\\cup\", (8,", "( 5, 5), Infix(Non()), [] ; # '\\\\succ', ( 5,", "# match b with # | TRUE -> nonfix 'TRUE'", "; # '\\\\o', (13,13), Infix(Left()), [ '\\\\circ' ] ; #", "12), Prefix(), [\"-\"]), (\"-\", (11, 11), Infix(Left()), list()), (\"+\", (10,", "op = TLAOP(name, prec, fixity, dom, defn) optable.setdefault(name, list()) optable[name].append(op)", "5, 5), Infix(Non()), [] ; # '\\\\succ', ( 5, 5),", "; # '~>', ( 2, 2), Infix(Non()), [ '\\\\leadsto' ],", "nodes.WhilePlus()), (\"[]\", (4, 15), Prefix(), list(), nodes.Box(True)), (\"<>\", (4, 15),", "[] ; # '\\\\doteq', ( 5, 5), Infix(Non()), [] ;", "5), Infix(Non()), [] ; # '\\\\preceq', ( 5, 5), Infix(Non()),", "Infix(Non()), list(), nodes.Subseteq()), (\"\\\\in\", (5, 5), Infix(Non()), list(), nodes.Mem()), (\"\\\\notin\",", "list()), (\"\\\\div\", (13, 13), Infix(Non()), list()), (\"\\\\wr\", (9, 14), Infix(Non()),", "8, 8), Infix(Left()), [ '\\\\intersect' ], Cap ; # '\\\\cup',", "| Postfix # | Infix of assoc class Fixity: pass", "nodes.Disj()), (\"~\", (4, 4), Prefix(), [\"\\\\neg\", \"\\\\lnot\"], nodes.Neg()), (\"=\", (5,", "list()), (\"::=\", (5, 5), Infix(Non()), list()), (\"(+)\", (10, 10), Infix(Left()),", "# name : string ; # prec : prec ;", "-> H.add tab s op) als # end ops #", "(13,13), Infix(Left()), [] ; # '&', (13,13), Infix(Left()), [] ;", "list()), (\"\\\\sqcup\", (9, 13), Infix(Left()), list()), (\"\\\\div\", (13, 13), Infix(Non()),", "pprint.pprint(optable) # let nonfix name defn = # { name", "Nat -> nonfix 'Nat' (Some Nat) # | Int ->", "; # '\\\\supseteq', ( 5, 5), Infix(Non()), [] ; #", "# '(-)', (11,11), Infix(Left()), [ '\\\\ominus' ] ; # '(.)',", "[] ; # '\\\\o', (13,13), Infix(Left()), [ '\\\\circ' ] ;", "(5, 5), Infix(Non()), list()), (\"\\\\propto\", (5, 5), Infix(Non()), list()), ]", "[] ; # '\\\\gg', ( 5, 5), Infix(Non()), [] ;", "[] ; # '^*', (15,15), Postfix, [] ; # '^#',", "5, 5), Infix(Non()), [] ; # '\\\\sqsubseteq', ( 5, 5),", "(Some Assert) # | JavaTime -> nonfix 'JavaTime' (Some JavaTime)", "list()), (\"\\\\ll\", (5, 5), Infix(Non()), list()), (\"\\\\gg\", (5, 5), Infix(Non()),", "( 4,15), Prefix, [], Box true ; # '<>', (", "return (name, prec, fix, als, defn) # let tlaops =", "; # '\\\\in', ( 5, 5), Infix(Non()), [], Mem ;", "'\\\\', ( 8, 8), Infix(Non()), [], Setminus ; # '\\\\cap',", "a, b): self.a = a self.b = b # let", "( 5, 5), Infix(Non()), [] ; # '\\\\propto', ( 5,", "list()), (\"=<\", (5, 5), Infix(Non()), [\"<=\", \"\\\\leq\"]), (\">\", (5, 5),", "dom : dom ; # defn : Builtin.builtin option ;", "-> nonfix 'SubSeq' (Some SubSeq) # | SelectSeq -> nonfix", "9), Infix(Non()), [] ; # '|', (10,11), Infix(Left()), [] ;", "[ (\"SUBSET\", (8, 8), Prefix(), list(), nodes.SUBSET()), (\"UNION\", (8, 8),", "13), Infix(Left()), [\"\\\\odot\"]), (\"(/)\", (13, 13), Infix(Non()), [\"\\\\oslash\"]), (\"(\\\\X)\", (13,", "list()), (\"\\\\wr\", (9, 14), Infix(Non()), list()), (\"\\\\star\", (13, 13), Infix(Left()),", "Infix(Non()), list()), (\"*\", (13, 13), Infix(Left()), list()), (\"-.\", (12, 12),", "str self.prec = prec # Prec self.fix = fixity #", "Infix(Left()), [ '\\\\land' ], Conj ; # '\\\\/', ( 3,", "| Lt -> { (lookup '<') with defn = Some", "list()), (\"||\", (10, 11), Infix(Left()), list()), (\"&&\", (13, 13), Infix(Left()),", "5, 5), Infix(Non()), [] ; # '\\\\approx', ( 5, 5),", "( 5, 5), Infix(Non()), [] ; # '-|', ( 5,", "( 7, 7), Infix(Non()), [] ; # ':>', ( 7,", "( \"Sets\", [ (\"SUBSET\", (8, 8), Prefix(), list(), nodes.SUBSET()), (\"UNION\",", "( 9,13), Infix(Left()), [] ; # '\\\\div', (13,13), Infix(Non()), []", "'\\\\X', (10,13), Prefix, [ '\\\\times' ], None ] ; #", "| Box _ -> lookup '[]' # | Diamond ->", "\"User\", [ (name, prec, fix, als, None) for name, prec,", "in # let tab = H.create 109 in # List.iter", "alternatives: optable.setdefault(s, list()) optable[s].append(op) return optable optable = _generate_optable() #", "fix, als, defn) = ( # name, prec, fix, als,", "# | Append -> nonfix 'Append' (Some Append) # |", "defn = # { name = name ; prec =", "8), Infix(Left()), [ '\\\\intersect' ], Cap ; # '\\\\cup', (", "# | PrintT -> nonfix 'PrintT' (Some PrintT) # |", "( 5, 5), Infix(Non()), [] ; # '\\\\gg', ( 5,", "(Some Seq) # | Len -> nonfix 'Len' (Some Len)", "'@@', ( 6, 6), Infix(Left()), [] ; # '!!', (", "(\"\\\\sqsubset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubseteq\", (5, 5), Infix(Non()), list()),", "let optable = # let module H = Hashtbl in", "5), Infix(Non()), [] ; # '\\\\supseteq', ( 5, 5), Infix(Non()),", "(13,13), Infix(Left()), [] ; # '-.', (12,12), Prefix, [ '-'", "fix, als in [ (\"^\", (14, 14), Infix(Non()), list()), (\"/\",", "lookup 'UNION' # | DOMAIN -> lookup 'DOMAIN' # |", "# '\\\\succeq', ( 5, 5), Infix(Non()), [] ; # '\\\\sim',", "list()), (\":>\", (7, 7), Infix(Non()), list()), (\":=\", (5, 5), Infix(Non()),", "( 9, 9), Infix(Non()), [] ; # '|', (10,11), Infix(Left()),", "| Print -> nonfix 'Print' (Some Print) # | PrintT", "( 5, 5), Infix(Non()), [] ; # '\\\\supset', ( 5,", "], Neq ; # ] ; # Sets, # List.map", "5), Infix(Non()), [], Eq ; # '#', ( 5, 5),", "Plus -> { (lookup '+') with defn = Some Plus", "7), Infix(Non()), list()), (\":=\", (5, 5), Infix(Non()), list()), (\"::=\", (5,", "Infix(Non()), [ '\\\\leadsto' ], Leadsto ; # 'ENABLED', ( 4,15),", "( 3, 3), Infix(Left()), [ '\\\\lor' ], Disj ; #", "[] ; # '^^', (14,14), Infix(Non()), [] ; # '@@',", "# [ '\\\\X', (10,13), Prefix, [ '\\\\times' ], None ]", "(8, 8), Infix(Left()), [\"\\\\intersect\"], nodes.Cap()), (\"\\\\cup\", (8, 8), Infix(Left()), [\"\\\\union\"],", "# '\\\\subseteq', ( 5, 5), Infix(Non()), [], Subseteq ; #", "11), Infix(Left()), list()), (\"**\", (13, 13), Infix(Left()), list()), (\"//\", (13,", "'Unprimable' None # | Irregular -> nonfix 'Irregular' None #", "lookup '\\\\cdot' # | Actplus -> lookup '-+->' # |", "; # '>=', ( 5, 5), Infix(Non()), [ '\\\\geq' ]", "# '\\\\doteq', ( 5, 5), Infix(Non()), [] ; # '\\\\propto',", "( 5, 5), Infix(Non()), [], Subseteq ; # '\\\\in', (", "Technology # Copyright (c) 2008-2013 INRIA and Microsoft Corporation #", "} # | Head -> nonfix 'Head' (Some Head) #", "als, Some defn);; def withdef(tuple_): name, prec, fix, als, defn", "{ (lookup '=<') with defn = Some Lteq } #", "Extend -> { (lookup '@@') with defn = Some Extend", "nodes.Neg()), (\"=\", (5, 5), Infix(Non()), list(), nodes.Eq()), (\"#\", (5, 5),", "], Cap ; # '\\\\cup', ( 8, 8), Infix(Left()), [", "[] ; # '^+', (15,15), Postfix, [] ; # '^*',", "(5, 5), Infix(Non()), list()), (\"\\\\supseteq\", (5, 5), Infix(Non()), list()), (\"\\\\approx\",", "; '\\\\lnot' ], Neg ; # '=', ( 5, 5),", "defn } # # let lookup name = # if", "# | Mem -> lookup '\\\\in' # | Notmem ->", "# | Lt -> { (lookup '<') with defn =", "; # '\\\\cup', ( 8, 8), Infix(Left()), [ '\\\\union' ],", "'^') with defn = Some Exp } # | Lteq", "DOMAIN -> lookup 'DOMAIN' # | Subseteq -> lookup '\\\\subseteq'", "'\\\\o') with defn = Some Cat } # | Head", "5), Infix(Non()), list()), (\"\\\\approx\", (5, 5), Infix(Non()), list()), (\"\\\\cong\", (5,", "; # '\\\\cong', ( 5, 5), Infix(Non()), [] ; #", "# '\\\\bigcirc', (13,13), Infix(Left()), [] ; # '\\\\bullet', (13,13), Infix(Left()),", "lookup 'ENABLED' # | UNCHANGED -> lookup 'UNCHANGED' # |", "5), Infix(Non()), list()), (\"\\\\supset\", (5, 5), Infix(Non()), list()), (\"\\\\supseteq\", (5,", "5), Infix(Non()), [], nodes.Notmem()), (\"\\\\\", (8, 8), Infix(Non()), [\"\\\\setminus\"], nodes.Setminus()),", "5), Infix(Non()), list()), (\"=|\", (5, 5), Infix(Non()), list()), (\"<:\", (7,", "nonfix 'Head' (Some Head) # | Tail -> nonfix 'Tail'", "Infix(Left()), [ '\\\\intersect' ], Cap ; # '\\\\cup', ( 8,", "'(.)', (13,13), Infix(Left()), [ '\\\\odot' ] ; # '(/)', (13,13),", "| BOOLEAN -> nonfix 'BOOLEAN' (Some BOOLEAN) # | SUBSET", "Infix(Non()), [] ; # '\\\\sqsupseteq', ( 5, 5), Infix(Non()), []", "List.map withdef [ # ''', (15,15), Postfix, [], Prime ;", "Leadsto ; # 'ENABLED', ( 4,15), Prefix, [], ENABLED ;", "[] ; # '::=', ( 5, 5), Infix(Non()), [] ;", "13), Infix(Left()), list()), (\"\\\\bullet\", (13, 13), Infix(Left()), list()), (\"\\\\prec\", (5,", "( 9, 9), Prefix, [], DOMAIN ; # '\\\\subseteq', (", "; prec = (-1, -1) ; # fix = Nonfix", "13), Infix(Non()), [\"\\\\oslash\"]), (\"(\\\\X)\", (13, 13), Infix(Left()), [\"\\\\otimes\"]), (\"\\\\uplus\", (9,", "(15, 15), Postfix(), list()), (\"^*\", (15, 15), Postfix(), list()), (\"^#\",", "STRING) # | BOOLEAN -> nonfix 'BOOLEAN' (Some BOOLEAN) #", "'Seq' (Some Seq) # | Len -> nonfix 'Len' (Some", "with defn = Some Quotient } # | Remainder ->", "(\">=\", (5, 5), Infix(Non()), [\"\\\\geq\"]), (\"...\", (9, 9), Infix(Non()), list()),", "Infix(Non()), list()), (\"\\\\supset\", (5, 5), Infix(Non()), list()), (\"\\\\supseteq\", (5, 5),", "(Some SubSeq) # | SelectSeq -> nonfix 'SelectSeq' (Some SelectSeq)", "(\"^\", (14, 14), Infix(Non()), list()), (\"/\", (13, 13), Infix(Non()), list()),", "[], Notmem ; # '\\\\', ( 8, 8), Infix(Non()), [],", "'(\\\\X)', (13,13), Infix(Left()), [ '\\\\otimes' ] ; # '\\\\uplus', (", "[] ; # '\\\\propto', ( 5, 5), Infix(Non()), [] ;", "by California Institute of Technology # Copyright (c) 2008-2013 INRIA", "| Uminus -> { (lookup '-.') with defn = Some", "Non | Right class Assoc: pass class Left(Assoc): pass class", "Infix(Non()), list()), (\"|-\", (5, 5), Infix(Non()), list()), (\"|=\", (5, 5),", "self.assoc = assoc # and assoc = # | Left", "# | DOMAIN -> lookup 'DOMAIN' # | Subseteq ->", "# '\\\\sqsupset', ( 5, 5), Infix(Non()), [] ; # '\\\\sqsupseteq',", "(\">\", (5, 5), Infix(Non()), list()), (\">=\", (5, 5), Infix(Non()), [\"\\\\geq\"]),", "= '?|'; # prec = (10, 11); # fix =", "| ToString -> nonfix 'ToString' (Some ToString) # # |", "[] ; # '\\\\sqsupseteq', ( 5, 5), Infix(Non()), [] ;", "; # '\\\\sqsupseteq', ( 5, 5), Infix(Non()), [] ; #", "# { # name = '?|'; # prec = (10,", "# # | Unprimable -> nonfix 'Unprimable' None # |", "{ # name : string ; # prec : prec", "Infix(Non()), list(), nodes.Eq()), (\"#\", (5, 5), Infix(Non()), [\"/=\"], nodes.Neq()), ],", "5, 5), Infix(Non()), [], Subseteq ; # '\\\\in', ( 5,", "(fun s -> H.add tab s op) als # end", "\" f\"{self.fix}, {self.dom}, {self.defn})\" ) # let optable = #", "-> nonfix 'PrintT' (Some PrintT) # | Assert -> nonfix", "# '^', (14,14), Infix(Non()), [] ; # '/', (13,13), Infix(Non()),", "'Infinity' (Some Infinity) # # | Seq -> nonfix 'Seq'", "5), Infix(Non()), list()), (\"\\\\ll\", (5, 5), Infix(Non()), list()), (\"\\\\gg\", (5,", "under 3-clause BSD. # # This module is based on", "(lookup '^') with defn = Some Exp } # |", "BSeq -> nonfix 'BSeq' (Some BSeq) # | Append ->", "'\\\\intersect' ], Cap ; # '\\\\cup', ( 8, 8), Infix(Left()),", "list()), (\"|=\", (5, 5), Infix(Non()), list()), (\"-|\", (5, 5), Infix(Non()),", "# '\\\\div', (13,13), Infix(Non()), [] ; # '\\\\wr', ( 9,14),", "# | Exp -> { (lookup '^') with defn =", "( 5, 5), Infix(Non()), [] ; # '\\\\subset', ( 5,", "Len) # | BSeq -> nonfix 'BSeq' (Some BSeq) #", "-> nonfix 'Real' (Some Real) # | Infinity -> nonfix", "# | TRUE -> nonfix 'TRUE' (Some TRUE) # |", "(** Mapping from builtins to standard tlaops *) # let", "Infix(Non()), [ '/=' ], Neq ; # ] ; #", "} # | Times -> { (lookup '*') with defn", "name : string ; # prec : prec ; #", "# 'ENABLED', ( 4,15), Prefix, [], ENABLED ; # 'UNCHANGED',", "5, 5), Infix(Non()), [] ; # '\\\\ll', ( 5, 5),", "StrongPrime -> lookup ''' # | Leadsto -> lookup '~>'", "; # Sets, # List.map withdef [ # 'SUBSET', (", "# '^*', (15,15), Postfix, [] ; # '^#', (15,15), Postfix,", "5), Infix(Non()), [] ; # '\\\\supset', ( 5, 5), Infix(Non()),", "(\"-|\", (5, 5), Infix(Non()), list()), (\"=|\", (5, 5), Infix(Non()), list()),", "# '\\\\gg', ( 5, 5), Infix(Non()), [] ; # '\\\\asymp',", "{ (lookup '\\\\o') with defn = Some Cat } #", "5), Infix(Non()), list()), (\"\\\\sim\", (5, 5), Infix(Non()), list()), (\"\\\\simeq\", (5,", "Infix(Left()), [\"\\\\intersect\"], nodes.Cap()), (\"\\\\cup\", (8, 8), Infix(Left()), [\"\\\\union\"], nodes.Cup()), (\"\\\\X\",", "; # '-.', (12,12), Prefix, [ '-' ] ; #", "Sets, # List.map withdef [ # 'SUBSET', ( 8, 8),", "nodes.UNION()), (\"DOMAIN\", (9, 9), Prefix(), list(), nodes.DOMAIN()), (\"\\\\subseteq\", (5, 5),", "(11, 11), Infix(Left()), list()), (\"**\", (13, 13), Infix(Left()), list()), (\"//\",", "list()), ] ], ), ] return tlaops # type tlaop", "Nonfix # | Prefix | Postfix # | Infix of", "defn = Some Cat } # | Head -> nonfix", "Corporation # All rights reserved. Licensed under 3-clause BSD. #", "( 6, 6), Infix(Left()), [] ; # '!!', ( 9,13),", "(\"\\\\cap\", (8, 8), Infix(Left()), [\"\\\\intersect\"], nodes.Cap()), (\"\\\\cup\", (8, 8), Infix(Left()),", "Infix(Left()), [] ; # '\\\\o', (13,13), Infix(Left()), [ '\\\\circ' ]", "13), Infix(Left()), list()), (\"\\\\sqcup\", (9, 13), Infix(Left()), list()), (\"\\\\div\", (13,", "15), Postfix(), list(), nodes.Prime()), (\"~>\", (2, 2), Infix(Non()), [\"\\\\leadsto\"], nodes.LeadsTo()),", "operators *) # | Logic | Sets | Modal #", "9, 9), Infix(Non()), [] ; # '|', (10,11), Infix(Left()), []", "All rights reserved. Licensed under 3-clause BSD. # # This", "list(), nodes.WhilePlus()), (\"[]\", (4, 15), Prefix(), list(), nodes.Box(True)), (\"<>\", (4,", "(Some SelectSeq) # # | OneArg -> { (lookup ':>')", "list(), nodes.UNCHANGED()), (\"\\\\cdot\", (5, 14), Infix(Left()), list(), nodes.Cdot()), (\"-+->\", (2,", "; # '<', ( 5, 5), Infix(Non()), [] ; #", "Infix(Left()), [] ; # '+', (10,10), Infix(Left()), [] ; #", "(\"*\", (13, 13), Infix(Left()), list()), (\"-.\", (12, 12), Prefix(), [\"-\"]),", "{ (lookup '/') with defn = Some Ratio } #", "BSeq) # | Append -> nonfix 'Append' (Some Append) #", "Assoc: pass class Left(Assoc): pass class Right(Assoc): pass class Non(Assoc):", "5), Infix(Non()), [] ; # '=<', ( 5, 5), Infix(Non()),", "(\"#\", (5, 5), Infix(Non()), [\"/=\"], nodes.Neq()), ], ), ( \"Sets\",", "list()), (\"\\\\sqsupset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupseteq\", (5, 5), Infix(Non()),", "( f\"TLAOP({self.name}, {self.prec}, \" f\"{self.fix}, {self.dom}, {self.defn})\" ) # let", "'\\\\times' ], None ] ; # Modal, # List.map withdef", "8), Infix(Left()), [ '\\\\union' ], Cup ; # ] ;", "# '\\\\asymp', ( 5, 5), Infix(Non()), [] ; # '\\\\subset',", "| Leadsto -> lookup '~>' # | ENABLED -> lookup", "# ] def _generate_tlaops(): tlaops = [ ( \"Logic\", [", "nonfix 'Permutations' (Some Permutations) # | SortSeq -> nonfix 'SortSeq'", "# '~>', ( 2, 2), Infix(Non()), [ '\\\\leadsto' ], Leadsto", "{ (lookup '^') with defn = Some Exp } #", "dom, defn): self.name = name # str self.prec = prec", "# | Prefix | Postfix # | Infix of assoc", "list()), (\":=\", (5, 5), Infix(Non()), list()), (\"::=\", (5, 5), Infix(Non()),", "Hashtbl.mem optable name then # Hashtbl.find optable name # else", "(5, 5), Infix(Non()), list()), (\"\\\\succeq\", (5, 5), Infix(Non()), list()), (\"\\\\sim\",", "PrintT) # | Assert -> nonfix 'Assert' (Some Assert) #", "'-') with defn = Some Minus } # | Uminus", "# '#', ( 5, 5), Infix(Non()), [ '/=' ], Neq", "defn = Some Gt } # | Range -> {", "Prefix, [], DOMAIN ; # '\\\\subseteq', ( 5, 5), Infix(Non()),", "(13,13), Infix(Left()), [] ; # '//', (13,13), Infix(Non()), [] ;", "Infix(Non()), [] ; # '::=', ( 5, 5), Infix(Non()), []", "nonfix 'Print' (Some Print) # | PrintT -> nonfix 'PrintT'", "# (* user-definable operators *) # | User dom =", "pass class Infix(Fixity): def __init__(self, assoc): self.assoc = assoc #", "als) -> (name, prec, fix, als, None)) [ # '^',", "; # '\\\\gg', ( 5, 5), Infix(Non()), [] ; #", "list()), (\"@@\", (6, 6), Infix(Left()), list()), (\"!!\", (9, 13), Infix(Non()),", "-> # let op = { name = name ;", "''', (15,15), Postfix, [], Prime ; # '~>', ( 2,", "2), Infix(Non()), [], Actplus ; # '[]', ( 4,15), Prefix,", "(10,10), Infix(Left()), [] ; # '^+', (15,15), Postfix, [] ;", "def _generate_tlaops(): tlaops = [ ( \"Logic\", [ (\"=>\", (1,", "(\"(\\\\X)\", (13, 13), Infix(Left()), [\"\\\\otimes\"]), (\"\\\\uplus\", (9, 13), Infix(Left()), list()),", "( 5, 5), Infix(Non()), [] ; # '\\\\sqsupseteq', ( 5,", "# | Unprimable -> nonfix 'Unprimable' None # | Irregular", "nodes.UNCHANGED()), (\"\\\\cdot\", (5, 14), Infix(Left()), list(), nodes.Cdot()), (\"-+->\", (2, 2),", "# '\\\\succ', ( 5, 5), Infix(Non()), [] ; # '\\\\preceq',", "Leadsto -> lookup '~>' # | ENABLED -> lookup 'ENABLED'", "\"\\\\leq\"]), (\">\", (5, 5), Infix(Non()), list()), (\">=\", (5, 5), Infix(Non()),", "Infix(Non()), list(), nodes.Mem()), (\"\\\\notin\", (5, 5), Infix(Non()), [], nodes.Notmem()), (\"\\\\\",", "'Print' (Some Print) # | PrintT -> nonfix 'PrintT' (Some", "Cat } # | Head -> nonfix 'Head' (Some Head)", "nonfix 'STRING' (Some STRING) # | BOOLEAN -> nonfix 'BOOLEAN'", "5, 5), Infix(Non()), [] ; # '-|', ( 5, 5),", "# Fixity self.dom = dom self.defn = defn def __repr__(self):", "Infix(Non()), list()), (\"\\\\approx\", (5, 5), Infix(Non()), list()), (\"\\\\cong\", (5, 5),", "(10, 10), Infix(Left()), list()), (\"--\", (11, 11), Infix(Left()), list()), (\"**\",", "optable = # let module H = Hashtbl in #", "defn = Some Plus } # | Minus -> {", "SUBSET ; # 'UNION', ( 8, 8), Prefix, [], UNION", "5), Infix(Non()), list()), (\"::=\", (5, 5), Infix(Non()), list()), (\"(+)\", (10,", "'Head' (Some Head) # | Tail -> nonfix 'Tail' (Some", "(\":>\", (7, 7), Infix(Non()), list()), (\":=\", (5, 5), Infix(Non()), list()),", "; # '\\\\succeq', ( 5, 5), Infix(Non()), [] ; #", "| Prime -> lookup ''' # | StrongPrime -> lookup", "'UNION', ( 8, 8), Prefix, [], UNION ; # 'DOMAIN',", "'-.', (12,12), Prefix, [ '-' ] ; # '-', (11,11),", "Lteq } # | Lt -> { (lookup '<') with", "-> lookup '\\\\cap' # | Cup -> lookup '\\\\cup' #", "# | Implies -> lookup '=>' # | Equiv ->", "] ; # ] def _generate_tlaops(): tlaops = [ (", "[] ; # '\\\\subset', ( 5, 5), Infix(Non()), [] ;", "Disj -> lookup '\\\\/' # | Neg -> lookup '~'", "( 5, 5), Infix(Non()), [] ; # '\\\\sim', ( 5,", "| Range -> { (lookup '..') with defn = Some", "( \"User\", [ (name, prec, fix, als, None) for name,", "} # | Quotient -> { (lookup '\\\\div') with defn", "Infix(Left()), list()), (\"&&\", (13, 13), Infix(Left()), list()), (\"&\", (13, 13),", "self.fix = fixity # Fixity self.dom = dom self.defn =", "( 5, 5), Infix(Non()), [] ; # '=|', ( 5,", "Infix(Non()), [] ; # '(+)', (10,10), Infix(Left()), [ '\\\\oplus' ]", "Infix(Left()), [\"\\\\circ\"]), (\"\\\\bigcirc\", (13, 13), Infix(Left()), list()), (\"\\\\bullet\", (13, 13),", "15), Prefix(), list(), nodes.Diamond()), ], ), ( \"User\", [ (name,", "( 4,15), Prefix, [], ENABLED ; # 'UNCHANGED', ( 4,15),", "Postfix, [] ; # '^*', (15,15), Postfix, [] ; #", ": dom ; # defn : Builtin.builtin option ; #", "optable.setdefault(name, list()) optable[name].append(op) for s in alternatives: optable.setdefault(s, list()) optable[s].append(op)", "withdef [ # '=>', ( 1, 1), Infix(Non()), [], Implies", "Some OneArg } # | Extend -> { (lookup '@@')", "'RandomElement' (Some RandomElement) # | Any -> nonfix 'Any' (Some", "'\\\\notin' # | Setminus -> lookup '\\\\' # | Cap", "14), Infix(Non()), list()), (\"@@\", (6, 6), Infix(Left()), list()), (\"!!\", (9,", "5), Infix(Non()), [], Mem ; # '\\\\notin', ( 5, 5),", "with defn = Some Times } # | Ratio ->", "# | FALSE -> nonfix 'FALSE' (Some FALSE) # |", "13), Infix(Left()), [\"\\\\circ\"]), (\"\\\\bigcirc\", (13, 13), Infix(Left()), list()), (\"\\\\bullet\", (13,", "= Some Uminus ; name = '-' } # |", "# # | Seq -> nonfix 'Seq' (Some Seq) #", "operators *) # | User dom = {\"Logic\", \"Sets\", \"Modal\",", "# let optable = # let module H = Hashtbl", "assoc class Fixity: pass class Nonfix(Fixity): pass class Prefix(Fixity): pass", "(14, 14), Infix(Non()), list()), (\"/\", (13, 13), Infix(Non()), list()), (\"*\",", "= Some Exp } # | Lteq -> { (lookup", "} # | Exp -> { (lookup '^') with defn", "Infix(Non()), [] ; # ':=', ( 5, 5), Infix(Non()), []", "| TLCSet -> nonfix 'TLCSet' (Some TLCSet) # | Permutations", "Infix(Non()), list()), (\"\\\\sqsubseteq\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupset\", (5, 5),", "[] ; # '\\\\sqcup', ( 9,13), Infix(Left()), [] ; #", "return tlaops # type tlaop = { # name :", "-> lookup '[]' # | Diamond -> lookup '<>' #", "[], Prime ; # '~>', ( 2, 2), Infix(Non()), [", "8), Infix(Non()), [], Setminus ; # '\\\\cap', ( 8, 8),", "# '-', (11,11), Infix(Left()), [] ; # '+', (10,10), Infix(Left()),", "| Exp -> { (lookup '^') with defn = Some", "# type fixity = # | Nonfix # | Prefix", "Infix(Non()), [] ; # '..', ( 9, 9), Infix(Non()), []", "list()), (\"\\\\bullet\", (13, 13), Infix(Left()), list()), (\"\\\\prec\", (5, 5), Infix(Non()),", "'\\\\prec', ( 5, 5), Infix(Non()), [] ; # '\\\\succ', (", "'Nat' (Some Nat) # | Int -> nonfix 'Int' (Some", "# '::=', ( 5, 5), Infix(Non()), [] ; # '(+)',", "# in # H.add tab name op ; # List.iter", "-> nonfix 'TLCSet' (Some TLCSet) # | Permutations -> nonfix", "'\\\\mod' ] ; # '##', ( 9,13), Infix(Left()), [] ;", "( 7, 7), Infix(Non()), [] ; # ':=', ( 5,", "(13, 13), Infix(Left()), list()), (\"//\", (13, 13), Infix(Non()), list()), (\"^^\",", "int class Prec: def __init__(self, a, b): self.a = a", "Notmem -> lookup '\\\\notin' # | Setminus -> lookup '\\\\'", "This module is based on the file: # # <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml>", "[], Implies ; # '<=>', ( 2, 2), Infix(Non()), [", "'^*', (15,15), Postfix, [] ; # '^#', (15,15), Postfix, []", "} # # | STRING -> nonfix 'STRING' (Some STRING)", "(7, 7), Infix(Non()), list()), (\":=\", (5, 5), Infix(Non()), list()), (\"::=\",", "'\\\\doteq', ( 5, 5), Infix(Non()), [] ; # '\\\\propto', (", "# dom = Logic; # defn = Some Divides; #", "Infix(Non()), [] ; # '\\\\gg', ( 5, 5), Infix(Non()), []", "Some Cat } # | Head -> nonfix 'Head' (Some", "list()), (\"\\\\succ\", (5, 5), Infix(Non()), list()), (\"\\\\preceq\", (5, 5), Infix(Non()),", "), ( \"User\", [ (name, prec, fix, als, None) for", "(Some TLCSet) # | Permutations -> nonfix 'Permutations' (Some Permutations)", "list(), nodes.Box(True)), (\"<>\", (4, 15), Prefix(), list(), nodes.Diamond()), ], ),", "prec ; # fix = fix ; dom = dom", "Conj -> lookup '/\\\\' # | Disj -> lookup '\\\\/'", "b): self.a = a self.b = b # let withdef", "Infix(Non()), [], Eq ; # '#', ( 5, 5), Infix(Non()),", "_generate_tlaops(): tlaops = [ ( \"Logic\", [ (\"=>\", (1, 1),", "Logic | Sets | Modal # (* user-definable operators *)", "Prefix, [], Box true ; # '<>', ( 4,15), Prefix,", "13), Infix(Left()), list()), (\"++\", (10, 10), Infix(Left()), list()), (\"--\", (11,", "-> { (lookup '%') with defn = Some Remainder }", "5), Infix(Non()), [ '\\\\geq' ] ; # '...', ( 9,", "# '\\\\sqsubset', ( 5, 5), Infix(Non()), [] ; # '\\\\sqsubseteq',", "5), Infix(Non()), [], Subseteq ; # '\\\\in', ( 5, 5),", "RandomElement -> nonfix 'RandomElement' (Some RandomElement) # | Any ->", "Infix(Non()), [], Actplus ; # '[]', ( 4,15), Prefix, [],", "-> lookup '~' # | Eq -> lookup '=' #", "lookup '=>' # | Equiv -> lookup '<=>' # |", "5), Infix(Non()), [] ; # '\\\\succ', ( 5, 5), Infix(Non()),", "8), Prefix, [], UNION ; # 'DOMAIN', ( 9, 9),", "(13, 13), Infix(Non()), [\"\\\\oslash\"]), (\"(\\\\X)\", (13, 13), Infix(Left()), [\"\\\\otimes\"]), (\"\\\\uplus\",", "Copyright 2020 by California Institute of Technology # Copyright (c)", "in alternatives: optable.setdefault(s, list()) optable[s].append(op) return optable optable = _generate_optable()", "(11, 11), Infix(Left()), [\"\\\\ominus\"]), (\"(.)\", (13, 13), Infix(Left()), [\"\\\\odot\"]), (\"(/)\",", "__init__(self, name, prec, fixity, dom, defn): self.name = name #", "*) # | User dom = {\"Logic\", \"Sets\", \"Modal\", \"User\"}", "[\"\\\\equiv\"], nodes.Equiv()), (\"/\\\\\", (3, 3), Infix(Left()), [\"\\\\land\"], nodes.Conj()), (\"\\\\/\", (3,", "in tlaops: for name, prec, fixity, alternatives, defn in ops:", "(5, 5), Infix(Non()), list()), (\"\\\\doteq\", (5, 5), Infix(Non()), list()), (\"\\\\propto\",", "prec = int * int class Prec: def __init__(self, a,", "(\"<:\", (7, 7), Infix(Non()), list()), (\":>\", (7, 7), Infix(Non()), list()),", "Infix(Left()), [] ; # '\\\\div', (13,13), Infix(Non()), [] ; #", "(Some Tail) # | SubSeq -> nonfix 'SubSeq' (Some SubSeq)", "class Prefix(Fixity): pass class Postfix(Fixity): pass class Infix(Fixity): def __init__(self,", "5), Infix(Non()), [] ; # '\\\\sqsupseteq', ( 5, 5), Infix(Non()),", "list()), (\"\\\\approx\", (5, 5), Infix(Non()), list()), (\"\\\\cong\", (5, 5), Infix(Non()),", "alternatives, defn in ops: op = TLAOP(name, prec, fixity, dom,", "] ; # '(-)', (11,11), Infix(Left()), [ '\\\\ominus' ] ;", "= name ; # prec = prec ; # fix", "'\\\\star', (13,13), Infix(Left()), [] ; # '\\\\o', (13,13), Infix(Left()), [", "# | Eq -> lookup '=' # | Neq ->", "Infix(Non()), [ '\\\\equiv' ], Equiv ; # '/\\\\', ( 3,", "ToString -> nonfix 'ToString' (Some ToString) # # | Unprimable", "[ '\\\\union' ], Cup ; # ] ; # Sets,", "fixity # Fixity self.dom = dom self.defn = defn def", "-> { (lookup '<') with defn = Some Lt }", "(name, prec, fix, als) -> (name, prec, fix, als, None))", "( 5, 5), Infix(Non()), [], Mem ; # '\\\\notin', (", "13), Infix(Left()), list()), (\"$\", (9, 13), Infix(Left()), list()), (\"??\", (9,", "ops) -> # List.iter begin # fun (name, prec, fix,", "-> lookup '-+->' # | Box _ -> lookup '[]'", "Infix(Left()), [] ; # '%', (10,11), Infix(Non()), [ '\\\\mod' ]", "; # '\\\\subseteq', ( 5, 5), Infix(Non()), [], Subseteq ;", "self.defn = defn def __repr__(self): return ( f\"TLAOP({self.name}, {self.prec}, \"", "-> nonfix 'Head' (Some Head) # | Tail -> nonfix", "] ; # '(/)', (13,13), Infix(Non()), [ '\\\\oslash' ] ;", "defn) # let tlaops = [ # Logic, # List.map", "(lookup ':>') with defn = Some OneArg } # |", "with defn = Some OneArg } # | Extend ->", "] ; # '(.)', (13,13), Infix(Left()), [ '\\\\odot' ] ;", "defn def __repr__(self): return ( f\"TLAOP({self.name}, {self.prec}, \" f\"{self.fix}, {self.dom},", "} # | Ratio -> { (lookup '/') with defn", "(* user-definable operators *) # | User dom = {\"Logic\",", "{ (lookup '>') with defn = Some Gt } #", "Times -> { (lookup '*') with defn = Some Times", "= [ # Logic, # List.map withdef [ # '=>',", "file: # # <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> # import pprint from .ast import", "Infix(Non()), list()), (\"\\\\sqsubset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubseteq\", (5, 5),", "for name, prec, fix, als in [ (\"^\", (14, 14),", "# Sets, # [ '\\\\X', (10,13), Prefix, [ '\\\\times' ],", "| Ratio -> { (lookup '/') with defn = Some", "Infix(Non()), list()), (\"|\", (10, 11), Infix(Left()), list()), (\"||\", (10, 11),", "Copyright (c) 2008-2013 INRIA and Microsoft Corporation # All rights", "; # '=<', ( 5, 5), Infix(Non()), [ '<=' ;", "[] ; # ] ; # ] def _generate_tlaops(): tlaops", "[ '\\\\odot' ] ; # '(/)', (13,13), Infix(Non()), [ '\\\\oslash'", "[ (\"=>\", (1, 1), Infix(Non()), list(), nodes.Implies()), (\"<=>\", (2, 2),", "None), ], ), ( \"Modal\", [ (\"'\", (15, 15), Postfix(),", "Prefix(), list(), nodes.DOMAIN()), (\"\\\\subseteq\", (5, 5), Infix(Non()), list(), nodes.Subseteq()), (\"\\\\in\",", "(13,13), Infix(Left()), [] ; # '\\\\bullet', (13,13), Infix(Left()), [] ;", "5), Infix(Non()), [], Notmem ; # '\\\\', ( 8, 8),", "[] ; # '--', (11,11), Infix(Left()), [] ; # '**',", ": prec ; # fix : fixity ; # dom", "Some Ratio } # | Quotient -> { (lookup '\\\\div')", "(\"|\", (10, 11), Infix(Left()), list()), (\"||\", (10, 11), Infix(Left()), list()),", "Setminus -> lookup '\\\\' # | Cap -> lookup '\\\\cap'", "let nonfix name defn = # { name = name", "Neg ; # '=', ( 5, 5), Infix(Non()), [], Eq", "(name, prec, fix, als, None)) [ # '^', (14,14), Infix(Non()),", "fix, als, None)) [ # '^', (14,14), Infix(Non()), [] ;", "= Some Times } # | Ratio -> { (lookup", "(lookup '/') with defn = Some Ratio } # |", "-> nonfix 'Seq' (Some Seq) # | Len -> nonfix", "( 9,13), Infix(Left()), [] ; # '$', ( 9,13), Infix(Left()),", "5, 5), Infix(Non()), [], Eq ; # '#', ( 5,", "Actplus -> lookup '-+->' # | Box _ -> lookup", "8), Infix(Left()), [\"\\\\intersect\"], nodes.Cap()), (\"\\\\cup\", (8, 8), Infix(Left()), [\"\\\\union\"], nodes.Cup()),", "(5, 5), Infix(Non()), [], nodes.Notmem()), (\"\\\\\", (8, 8), Infix(Non()), [\"\\\\setminus\"],", "= int * int class Prec: def __init__(self, a, b):", "builtins to standard tlaops *) # let standard_form b =", "# tab def _generate_optable(): tlaops = _generate_tlaops() optable = dict()", "list(), nodes.Mem()), (\"\\\\notin\", (5, 5), Infix(Non()), [], nodes.Notmem()), (\"\\\\\", (8,", "list(), nodes.UNION()), (\"DOMAIN\", (9, 9), Prefix(), list(), nodes.DOMAIN()), (\"\\\\subseteq\", (5,", "'(+)', (10,10), Infix(Left()), [ '\\\\oplus' ] ; # '(-)', (11,11),", "[], Eq ; # '#', ( 5, 5), Infix(Non()), [", "'Assert' (Some Assert) # | JavaTime -> nonfix 'JavaTime' (Some", "( 9,13), Infix(Left()), [] ; # '%%', (10,11), Infix(Left()), []", "-> lookup '\\\\notin' # | Setminus -> lookup '\\\\' #", "List.map withdef [ # '=>', ( 1, 1), Infix(Non()), [],", "Neg -> lookup '~' # | Eq -> lookup '='", "; # '=', ( 5, 5), Infix(Non()), [], Eq ;", "\"Sets\", [ (\"SUBSET\", (8, 8), Prefix(), list(), nodes.SUBSET()), (\"UNION\", (8,", "(\"!!\", (9, 13), Infix(Non()), list()), (\"|-\", (5, 5), Infix(Non()), list()),", "11), Infix(Left()), [\"\\\\ominus\"]), (\"(.)\", (13, 13), Infix(Left()), [\"\\\\odot\"]), (\"(/)\", (13,", "# # | STRING -> nonfix 'STRING' (Some STRING) #", "= Some Ratio } # | Quotient -> { (lookup", "def __init__(self, name, prec, fixity, dom, defn): self.name = name", "9, 9), Infix(Non()), [] ; # '..', ( 9, 9),", "| SUBSET -> lookup 'SUBSET' # | UNION -> lookup", "Infix(Non()), list()), (\"::=\", (5, 5), Infix(Non()), list()), (\"(+)\", (10, 10),", "fix : fixity ; # dom : dom ; #", "[] ; # '\\\\sqsubset', ( 5, 5), Infix(Non()), [] ;", "[ '\\\\X', (10,13), Prefix, [ '\\\\times' ], None ] ;", "( 5,14), Infix(Left()), [], Cdot ; # '-+->', ( 2,", "| Tail -> nonfix 'Tail' (Some Tail) # | SubSeq", "Gteq -> { (lookup '>=') with defn = Some Gteq", "UNCHANGED ; # '\\\\cdot', ( 5,14), Infix(Left()), [], Cdot ;", "defn) optable.setdefault(name, list()) optable[name].append(op) for s in alternatives: optable.setdefault(s, list())", "Infix(Non()), [] ; # '>=', ( 5, 5), Infix(Non()), [", "'(/)', (13,13), Infix(Non()), [ '\\\\oslash' ] ; # '(\\\\X)', (13,13),", "; # '(.)', (13,13), Infix(Left()), [ '\\\\odot' ] ; #", "with defn = Some Ratio } # | Quotient ->", "None ] ; # Modal, # List.map withdef [ #", ".ast import Nodes as nodes # open Builtin # type", "Subseteq -> lookup '\\\\subseteq' # | Mem -> lookup '\\\\in'", "'!!', ( 9,13), Infix(Non()), [] ; # '|-', ( 5,", "(\"|-\", (5, 5), Infix(Non()), list()), (\"|=\", (5, 5), Infix(Non()), list()),", "(Some Head) # | Tail -> nonfix 'Tail' (Some Tail)", "[] ; # '\\\\sqsupset', ( 5, 5), Infix(Non()), [] ;", "Fixity self.dom = dom self.defn = defn def __repr__(self): return", "TLCGet -> nonfix 'TLCGet' (Some TLCGet) # | TLCSet ->", "Head -> nonfix 'Head' (Some Head) # | Tail ->", "[\"\\\\neg\", \"\\\\lnot\"], nodes.Neg()), (\"=\", (5, 5), Infix(Non()), list(), nodes.Eq()), (\"#\",", "defn) -> # let op = { name = name", "# '\\\\cdot', ( 5,14), Infix(Left()), [], Cdot ; # '-+->',", "5, 5), Infix(Non()), [] ; # '>=', ( 5, 5),", "# '>=', ( 5, 5), Infix(Non()), [ '\\\\geq' ] ;", "Infix(Left()), [] ; # '\\\\sqcap', ( 9,13), Infix(Left()), [] ;", "-> { (lookup '\\\\o') with defn = Some Cat }", "-> nonfix 'TLCGet' (Some TLCGet) # | TLCSet -> nonfix", "# | Actplus -> lookup '-+->' # | Box _", "# | Cap -> lookup '\\\\cap' # | Cup ->", "= Some Minus } # | Uminus -> { (lookup", "(2, 2), Infix(Non()), list(), nodes.WhilePlus()), (\"[]\", (4, 15), Prefix(), list(),", "class TLAOP: def __init__(self, name, prec, fixity, dom, defn): self.name", "( 5, 5), Infix(Non()), [], Notmem ; # '\\\\', (", "( 8, 8), Infix(Left()), [ '\\\\intersect' ], Cap ; #", "Any -> nonfix 'Any' (Some Any) # | ToString ->", "Infix(Non()), [] ; # '^^', (14,14), Infix(Non()), [] ; #", "| Conj -> lookup '/\\\\' # | Disj -> lookup", "# | UNCHANGED -> lookup 'UNCHANGED' # | Cdot ->", "fun (dom, ops) -> # List.iter begin # fun (name,", "= defn } # # let lookup name = #", "H = Hashtbl in # let tab = H.create 109", "H.add tab s op) als # end ops # end", "(Some TLCGet) # | TLCSet -> nonfix 'TLCSet' (Some TLCSet)", "(11,11), Infix(Left()), [] ; # '+', (10,10), Infix(Left()), [] ;", "-> lookup 'DOMAIN' # | Subseteq -> lookup '\\\\subseteq' #", "Subseteq ; # '\\\\in', ( 5, 5), Infix(Non()), [], Mem", "(\"\\\\succ\", (5, 5), Infix(Non()), list()), (\"\\\\preceq\", (5, 5), Infix(Non()), list()),", "; # tab def _generate_optable(): tlaops = _generate_tlaops() optable =", "'#' # | Divides -> # { # name =", "{ (lookup '-.') with defn = Some Uminus ; name", "; # Modal, # List.map withdef [ # ''', (15,15),", "= TLAOP(name, prec, fixity, dom, defn) optable.setdefault(name, list()) optable[name].append(op) for", "':>', ( 7, 7), Infix(Non()), [] ; # ':=', (", "5), Infix(Non()), [] ; # '\\\\propto', ( 5, 5), Infix(Non()),", "dom, defn) optable.setdefault(name, list()) optable[name].append(op) for s in alternatives: optable.setdefault(s,", "# This module is based on the file: # #", "(9, 13), Infix(Left()), list()), (\"%%\", (10, 11), Infix(Left()), list()), (\"%\",", "nonfix 'RandomElement' (Some RandomElement) # | Any -> nonfix 'Any'", "[] ; # '\\\\sqsubseteq', ( 5, 5), Infix(Non()), [] ;", "# '[]', ( 4,15), Prefix, [], Box true ; #", "(8, 8), Infix(Non()), [\"\\\\setminus\"], nodes.Setminus()), (\"\\\\cap\", (8, 8), Infix(Left()), [\"\\\\intersect\"],", "'>') with defn = Some Gt } # | Range", "# | Print -> nonfix 'Print' (Some Print) # |", "als, defn) # let tlaops = [ # Logic, #", "[] ; # '\\\\asymp', ( 5, 5), Infix(Non()), [] ;", "# let op = { name = name ; #", "name defn = # { name = name ; prec", "# | Tail -> nonfix 'Tail' (Some Tail) # |", "(5, 5), Infix(Non()), list()), (\"\\\\sqsupseteq\", (5, 5), Infix(Non()), list()), (\"\\\\doteq\",", "# ''', (15,15), Postfix, [], Prime ; # '~>', (", "'<', ( 5, 5), Infix(Non()), [] ; # '=<', (", "(\"^*\", (15, 15), Postfix(), list()), (\"^#\", (15, 15), Postfix(), list()),", "(name, prec, fix, als, defn) # let tlaops = [", "15), Prefix(), list(), nodes.UNCHANGED()), (\"\\\\cdot\", (5, 14), Infix(Left()), list(), nodes.Cdot()),", "| Infix of assoc class Fixity: pass class Nonfix(Fixity): pass", "# prec : prec ; # fix : fixity ;", "2020 by California Institute of Technology # Copyright (c) 2008-2013", "class Fixity: pass class Nonfix(Fixity): pass class Prefix(Fixity): pass class", "(lookup '%') with defn = Some Remainder } # |", "Postfix, [], Prime ; # '~>', ( 2, 2), Infix(Non()),", "-> lookup '=>' # | Equiv -> lookup '<=>' #", "# | Cup -> lookup '\\\\cup' # # | Prime", "(\"\\\\wr\", (9, 14), Infix(Non()), list()), (\"\\\\star\", (13, 13), Infix(Left()), list()),", "(10, 10), Infix(Left()), list()), (\"^+\", (15, 15), Postfix(), list()), (\"^*\",", "Neq ; # ] ; # Sets, # List.map withdef", "[\"\\\\intersect\"], nodes.Cap()), (\"\\\\cup\", (8, 8), Infix(Left()), [\"\\\\union\"], nodes.Cup()), (\"\\\\X\", (10,", "(12,12), Prefix, [ '-' ] ; # '-', (11,11), Infix(Left()),", "{ (lookup '+') with defn = Some Plus } #", "# | Neg -> lookup '~' # | Eq ->", "Quotient -> { (lookup '\\\\div') with defn = Some Quotient", "# '\\\\o', (13,13), Infix(Left()), [ '\\\\circ' ] ; # '\\\\bigcirc',", "( 5, 5), Infix(Non()), [], Eq ; # '#', (", "Infix(Left()), [ '\\\\union' ], Cup ; # ] ; #", "(13,13), Infix(Left()), [] ; # '\\\\o', (13,13), Infix(Left()), [ '\\\\circ'", "with defn = Some Cat } # | Head ->", "(\"@@\", (6, 6), Infix(Left()), list()), (\"!!\", (9, 13), Infix(Non()), list()),", "| Append -> nonfix 'Append' (Some Append) # | Cat", "# '>', ( 5, 5), Infix(Non()), [] ; # '>=',", "; # '\\\\asymp', ( 5, 5), Infix(Non()), [] ; #", "Infix(Non()), list()), (\"(+)\", (10, 10), Infix(Left()), [\"\\\\oplus\"]), (\"(-)\", (11, 11),", "| Cat -> { (lookup '\\\\o') with defn = Some", "9), Infix(Non()), [] ; # '..', ( 9, 9), Infix(Non()),", "als, defn) = ( # name, prec, fix, als, Some", "Infix(Non()), [] ; # '\\\\subset', ( 5, 5), Infix(Non()), []", "User, # List.map (fun (name, prec, fix, als) -> (name,", "(\"DOMAIN\", (9, 9), Prefix(), list(), nodes.DOMAIN()), (\"\\\\subseteq\", (5, 5), Infix(Non()),", "'&', (13,13), Infix(Left()), [] ; # '$$', ( 9,13), Infix(Left()),", "'\\\\circ' ] ; # '\\\\bigcirc', (13,13), Infix(Left()), [] ; #", "(-1, -1) ; # fix = Nonfix ; dom =", "; # ] ; # ] def _generate_tlaops(): tlaops =", "prec, fix, als, Some defn);; def withdef(tuple_): name, prec, fix,", "Infix(Non()), list()), (\"=|\", (5, 5), Infix(Non()), list()), (\"<:\", (7, 7),", "Infix(Left()), [] ; # '!!', ( 9,13), Infix(Non()), [] ;", "UNION ; # 'DOMAIN', ( 9, 9), Prefix, [], DOMAIN", "# | Setminus -> lookup '\\\\' # | Cap ->", "# | StrongPrime -> lookup ''' # | Leadsto ->", "\"User\"} # type prec = int * int class Prec:", "(Some BSeq) # | Append -> nonfix 'Append' (Some Append)", "(\"%\", (10, 11), Infix(Non()), [\"\\\\mod\"]), (\"##\", (9, 13), Infix(Left()), list()),", "nodes.Box(True)), (\"<>\", (4, 15), Prefix(), list(), nodes.Diamond()), ], ), (", "tlaops: for name, prec, fixity, alternatives, defn in ops: op", "; # '+', (10,10), Infix(Left()), [] ; # '^+', (15,15),", "\"Sets\", \"Modal\", \"User\"} # type prec = int * int", "] ; # '...', ( 9, 9), Infix(Non()), [] ;", "Infix(Non()), [] ; # '-|', ( 5, 5), Infix(Non()), []", "(\"$$\", (9, 13), Infix(Left()), list()), (\"$\", (9, 13), Infix(Left()), list()),", "(Some PrintT) # | Assert -> nonfix 'Assert' (Some Assert)", "list()) optable[s].append(op) return optable optable = _generate_optable() # pprint.pprint(optable) #", "( 9,13), Infix(Left()), [] ; # '\\\\sqcap', ( 9,13), Infix(Left()),", "[ '<=' ; '\\\\leq' ] ; # '>', ( 5,", "(\"\\\\sqsupseteq\", (5, 5), Infix(Non()), list()), (\"\\\\doteq\", (5, 5), Infix(Non()), list()),", "= # if Hashtbl.mem optable name then # Hashtbl.find optable", "dict() for dom, ops in tlaops: for name, prec, fixity,", "5, 5), Infix(Non()), [] ; # '\\\\doteq', ( 5, 5),", "5), Infix(Non()), list()), (\"\\\\succ\", (5, 5), Infix(Non()), list()), (\"\\\\preceq\", (5,", "[] ; # ':=', ( 5, 5), Infix(Non()), [] ;", "# '<=>', ( 2, 2), Infix(Non()), [ '\\\\equiv' ], Equiv", "(\"=<\", (5, 5), Infix(Non()), [\"<=\", \"\\\\leq\"]), (\">\", (5, 5), Infix(Non()),", "Infix(Non()), list()), (\"|=\", (5, 5), Infix(Non()), list()), (\"-|\", (5, 5),", "= Some OneArg } # | Extend -> { (lookup", "(\"\\\\propto\", (5, 5), Infix(Non()), list()), ] ], ), ] return", "nonfix 'Unprimable' None # | Irregular -> nonfix 'Irregular' None", "), ] return tlaops # type tlaop = { #", "# | Divides -> # { # name = '?|';", "(\"&&\", (13, 13), Infix(Left()), list()), (\"&\", (13, 13), Infix(Left()), list()),", "(13, 13), Infix(Left()), list()), (\"\\\\prec\", (5, 5), Infix(Non()), list()), (\"\\\\succ\",", "| Cup -> lookup '\\\\cup' # # | Prime ->", "Infix(Non()), [] ; # '\\\\sqsubset', ( 5, 5), Infix(Non()), []", "Infix(Non()), [] ; # '|=', ( 5, 5), Infix(Non()), []", "Infix(Left()), list()), (\"\\\\prec\", (5, 5), Infix(Non()), list()), (\"\\\\succ\", (5, 5),", "Disj ; # '~', ( 4, 4), Prefix, [ '\\\\neg'", "'\\\\subseteq', ( 5, 5), Infix(Non()), [], Subseteq ; # '\\\\in',", "(13,13), Infix(Left()), [ '\\\\otimes' ] ; # '\\\\uplus', ( 9,13),", "name ; # prec = prec ; # fix =", "Infix(Non()), [] ; # '@@', ( 6, 6), Infix(Left()), []", "(9, 13), Infix(Left()), list()), (\"\\\\sqcap\", (9, 13), Infix(Left()), list()), (\"\\\\sqcup\",", "Infix(Non()), list()), (\"\\\\sqsupset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupseteq\", (5, 5),", "# | Plus -> { (lookup '+') with defn =", "Range -> { (lookup '..') with defn = Some Range", "14), Infix(Non()), list()), (\"/\", (13, 13), Infix(Non()), list()), (\"*\", (13,", "nonfix 'Real' (Some Real) # | Infinity -> nonfix 'Infinity'", "-> nonfix 'Print' (Some Print) # | PrintT -> nonfix", "-> nonfix 'BOOLEAN' (Some BOOLEAN) # | SUBSET -> lookup", "nonfix 'PrintT' (Some PrintT) # | Assert -> nonfix 'Assert'", "# | SelectSeq -> nonfix 'SelectSeq' (Some SelectSeq) # #", "8), Prefix(), list(), nodes.SUBSET()), (\"UNION\", (8, 8), Prefix(), list(), nodes.UNION()),", "= (-1, -1) ; # fix = Nonfix ; dom", "(4, 15), Prefix(), list(), nodes.UNCHANGED()), (\"\\\\cdot\", (5, 14), Infix(Left()), list(),", "(\"--\", (11, 11), Infix(Left()), list()), (\"**\", (13, 13), Infix(Left()), list()),", "lookup '[]' # | Diamond -> lookup '<>' # #", "# Sets, # List.map withdef [ # 'SUBSET', ( 8,", "5), Infix(Non()), list()), (\"\\\\sqsupset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupseteq\", (5,", "# | Lteq -> { (lookup '=<') with defn =", "# | OneArg -> { (lookup ':>') with defn =", "'\\\\ominus' ] ; # '(.)', (13,13), Infix(Left()), [ '\\\\odot' ]", "[] ; # '\\\\cong', ( 5, 5), Infix(Non()), [] ;", "# '\\\\sim', ( 5, 5), Infix(Non()), [] ; # '\\\\simeq',", "Infix(Left()), list()), (\"+\", (10, 10), Infix(Left()), list()), (\"^+\", (15, 15),", "Infix(Left()), [\"\\\\otimes\"]), (\"\\\\uplus\", (9, 13), Infix(Left()), list()), (\"\\\\sqcap\", (9, 13),", "= fix ; dom = dom ; # defn =", "# | Nat -> nonfix 'Nat' (Some Nat) # |", "let lookup name = # if Hashtbl.mem optable name then", "Actplus ; # '[]', ( 4,15), Prefix, [], Box true", "[ '\\\\circ' ] ; # '\\\\bigcirc', (13,13), Infix(Left()), [] ;", "return optable optable = _generate_optable() # pprint.pprint(optable) # let nonfix", "[] ; # '??', ( 9,13), Infix(Left()), [] ; #", "Infinity -> nonfix 'Infinity' (Some Infinity) # # | Seq", "-> { (lookup '>') with defn = Some Gt }", "let tab = H.create 109 in # List.iter begin #", "( 8, 8), Infix(Left()), [ '\\\\union' ], Cup ; #", "name, prec, fix, als, Some defn);; def withdef(tuple_): name, prec,", "5), Infix(Non()), [\"<=\", \"\\\\leq\"]), (\">\", (5, 5), Infix(Non()), list()), (\">=\",", "def __init__(self, assoc): self.assoc = assoc # and assoc =", "let tlaops = [ # Logic, # List.map withdef [", "Infix(Non()), list()), (\"\\\\preceq\", (5, 5), Infix(Non()), list()), (\"\\\\succeq\", (5, 5),", "(Some RandomElement) # | Any -> nonfix 'Any' (Some Any)", "*) # | Logic | Sets | Modal # (*", "(5, 14), Infix(Left()), list(), nodes.Cdot()), (\"-+->\", (2, 2), Infix(Non()), list(),", "list()), (\"\\\\sqsupseteq\", (5, 5), Infix(Non()), list()), (\"\\\\doteq\", (5, 5), Infix(Non()),", "class Assoc: pass class Left(Assoc): pass class Right(Assoc): pass class", "; # prec : prec ; # fix : fixity", "Nodes as nodes # open Builtin # type fixity =", "(\"...\", (9, 9), Infix(Non()), list()), (\"..\", (9, 9), Infix(Non()), list()),", "Right(Assoc): pass class Non(Assoc): pass # and dom = #", "5), Infix(Non()), list()), (\"\\\\sqsubset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubseteq\", (5,", "nonfix name defn = # { name = name ;", "Notmem ; # '\\\\', ( 8, 8), Infix(Non()), [], Setminus", "| Sets | Modal # (* user-definable operators *) #", "# All rights reserved. Licensed under 3-clause BSD. # #", "'/\\\\', ( 3, 3), Infix(Left()), [ '\\\\land' ], Conj ;", "( 3, 3), Infix(Left()), [ '\\\\land' ], Conj ; #", "; # '\\\\star', (13,13), Infix(Left()), [] ; # '\\\\o', (13,13),", "(\"##\", (9, 13), Infix(Left()), list()), (\"++\", (10, 10), Infix(Left()), list()),", "def _generate_optable(): tlaops = _generate_tlaops() optable = dict() for dom,", "5), Infix(Non()), list(), nodes.Subseteq()), (\"\\\\in\", (5, 5), Infix(Non()), list(), nodes.Mem()),", "], ), ( \"Modal\", [ (\"'\", (15, 15), Postfix(), list(),", "op ; # List.iter (fun s -> H.add tab s", "| Nonfix # | Prefix | Postfix # | Infix", "nonfix 'TLCGet' (Some TLCGet) # | TLCSet -> nonfix 'TLCSet'", "Infix(Non()), [], Subseteq ; # '\\\\in', ( 5, 5), Infix(Non()),", "] ; # Modal, # List.map withdef [ # ''',", "'\\\\succeq', ( 5, 5), Infix(Non()), [] ; # '\\\\sim', (", "} # | Gt -> { (lookup '>') with defn", "[] ; # '=|', ( 5, 5), Infix(Non()), [] ;", "list()), (\"\\\\propto\", (5, 5), Infix(Non()), list()), ] ], ), ]", "8), Prefix, [], SUBSET ; # 'UNION', ( 8, 8),", "; # 'UNCHANGED', ( 4,15), Prefix, [], UNCHANGED ; #", "[\"\\\\ominus\"]), (\"(.)\", (13, 13), Infix(Left()), [\"\\\\odot\"]), (\"(/)\", (13, 13), Infix(Non()),", "Infix(Non()), list()), (\"\\\\subset\", (5, 5), Infix(Non()), list()), (\"\\\\supset\", (5, 5),", "; # List.iter (fun s -> H.add tab s op)", "} # | Minus -> { (lookup '-') with defn", "Microsoft Corporation # All rights reserved. Licensed under 3-clause BSD.", "ops: op = TLAOP(name, prec, fixity, dom, defn) optable.setdefault(name, list())", "list()), (\"&\", (13, 13), Infix(Left()), list()), (\"$$\", (9, 13), Infix(Left()),", "# | TLCGet -> nonfix 'TLCGet' (Some TLCGet) # |", "# '|', (10,11), Infix(Left()), [] ; # '||', (10,11), Infix(Left()),", "[] ; # '@@', ( 6, 6), Infix(Left()), [] ;", "-> nonfix 'ToString' (Some ToString) # # | Unprimable ->", "4,15), Prefix, [], Box true ; # '<>', ( 4,15),", "5), Infix(Non()), [] ; # '<:', ( 7, 7), Infix(Non()),", "FALSE) # | Implies -> lookup '=>' # | Equiv", "| SortSeq -> nonfix 'SortSeq' (Some SortSeq) # | RandomElement", "= name ; prec = (-1, -1) ; # fix", "Diamond ; # ] ; # User, # List.map (fun", "Infix(Non()), list()), (\"\\\\wr\", (9, 14), Infix(Non()), list()), (\"\\\\star\", (13, 13),", "'\\\\sqcup', ( 9,13), Infix(Left()), [] ; # '\\\\div', (13,13), Infix(Non()),", "5, 5), Infix(Non()), [ '<=' ; '\\\\leq' ] ; #", "fix = Nonfix ; dom = User ; defn =", "8, 8), Prefix, [], SUBSET ; # 'UNION', ( 8,", "'::=', ( 5, 5), Infix(Non()), [] ; # '(+)', (10,10),", "'-.') with defn = Some Uminus ; name = '-'", "= ( # name, prec, fix, als, Some defn);; def", "-> nonfix 'Infinity' (Some Infinity) # # | Seq ->", ": fixity ; # dom : dom ; # defn", "; # '(\\\\X)', (13,13), Infix(Left()), [ '\\\\otimes' ] ; #", "13), Infix(Left()), [\"\\\\times\"], None), ], ), ( \"Modal\", [ (\"'\",", "Infix(Non()), [] ; # '\\\\sqsupset', ( 5, 5), Infix(Non()), []", "[] ; # '\\\\bullet', (13,13), Infix(Left()), [] ; # '\\\\prec',", "'\\\\propto', ( 5, 5), Infix(Non()), [] ; # ] ;", "Infix(Non()), list()), (\"\\\\succeq\", (5, 5), Infix(Non()), list()), (\"\\\\sim\", (5, 5),", "-> nonfix 'RandomElement' (Some RandomElement) # | Any -> nonfix", "2), Infix(Non()), [ '\\\\leadsto' ], Leadsto ; # 'ENABLED', (", "(5, 5), Infix(Non()), list()), (\">=\", (5, 5), Infix(Non()), [\"\\\\geq\"]), (\"...\",", "Infix(Non()), [] ; # '\\\\approx', ( 5, 5), Infix(Non()), []", "'FALSE' (Some FALSE) # | Implies -> lookup '=>' #", "Infix(Left()), [] ; # '//', (13,13), Infix(Non()), [] ; #", "# '=<', ( 5, 5), Infix(Non()), [ '<=' ; '\\\\leq'", "list(), nodes.Eq()), (\"#\", (5, 5), Infix(Non()), [\"/=\"], nodes.Neq()), ], ),", "prec = prec ; # fix = fix ; dom", "(2, 2), Infix(Non()), [\"\\\\equiv\"], nodes.Equiv()), (\"/\\\\\", (3, 3), Infix(Left()), [\"\\\\land\"],", "def __init__(self, a, b): self.a = a self.b = b", "# type prec = int * int class Prec: def", "'\\\\in', ( 5, 5), Infix(Non()), [], Mem ; # '\\\\notin',", "Infix(Non()), [ '<=' ; '\\\\leq' ] ; # '>', (", "(4, 15), Prefix(), list(), nodes.Box(True)), (\"<>\", (4, 15), Prefix(), list(),", "(lookup '-.') with defn = Some Uminus ; name =", "FALSE -> nonfix 'FALSE' (Some FALSE) # | Implies ->", "# List.iter begin # fun (name, prec, fix, als, defn)", "Infix(Non()), list()), (\"\\\\asymp\", (5, 5), Infix(Non()), list()), (\"\\\\subset\", (5, 5),", "5, 5), Infix(Non()), [] ; # '\\\\succeq', ( 5, 5),", "15), Prefix(), list(), nodes.Box(True)), (\"<>\", (4, 15), Prefix(), list(), nodes.Diamond()),", "(\"\\\\sqcup\", (9, 13), Infix(Left()), list()), (\"\\\\div\", (13, 13), Infix(Non()), list()),", "dom ; # defn : Builtin.builtin option ; # }", "s -> H.add tab s op) als # end ops", "# | Neq -> lookup '#' # | Divides ->", "Infix(Non()), list()), (\"^^\", (14, 14), Infix(Non()), list()), (\"@@\", (6, 6),", "(Some TRUE) # | FALSE -> nonfix 'FALSE' (Some FALSE)", "5), Infix(Non()), list()), ] ], ), ] return tlaops #", "(5, 5), Infix(Non()), list()), (\"\\\\succ\", (5, 5), Infix(Non()), list()), (\"\\\\preceq\",", "in # List.iter begin # fun (dom, ops) -> #", "defn = Some Remainder } # | Exp -> {", "2), Infix(Non()), list(), nodes.WhilePlus()), (\"[]\", (4, 15), Prefix(), list(), nodes.Box(True)),", "# '|-', ( 5, 5), Infix(Non()), [] ; # '|=',", "# # let lookup name = # if Hashtbl.mem optable", "tlaops *) # let standard_form b = # match b", "; # '**', (13,13), Infix(Left()), [] ; # '//', (13,13),", "5), Infix(Non()), [] ; # '\\\\sqsupset', ( 5, 5), Infix(Non()),", "3), Infix(Left()), [ '\\\\land' ], Conj ; # '\\\\/', (", "8, 8), Infix(Non()), [], Setminus ; # '\\\\cap', ( 8,", "# '\\\\supseteq', ( 5, 5), Infix(Non()), [] ; # '\\\\approx',", "13), Infix(Left()), list()), (\"&\", (13, 13), Infix(Left()), list()), (\"$$\", (9,", "(\"^^\", (14, 14), Infix(Non()), list()), (\"@@\", (6, 6), Infix(Left()), list()),", "Infix(Non()), [\"<=\", \"\\\\leq\"]), (\">\", (5, 5), Infix(Non()), list()), (\">=\", (5,", "Hashtbl.find optable name # else # nonfix name None #", "dom = # (* primitive operators *) # | Logic", "4,15), Prefix, [], UNCHANGED ; # '\\\\cdot', ( 5,14), Infix(Left()),", "9,13), Infix(Left()), [] ; # '\\\\sqcap', ( 9,13), Infix(Left()), []", "(\"\\\\cdot\", (5, 14), Infix(Left()), list(), nodes.Cdot()), (\"-+->\", (2, 2), Infix(Non()),", "(Some SortSeq) # | RandomElement -> nonfix 'RandomElement' (Some RandomElement)", "user-definable operators *) # | User dom = {\"Logic\", \"Sets\",", "prec, fix, als, None) for name, prec, fix, als in", "'<=' ; '\\\\leq' ] ; # '>', ( 5, 5),", "as nodes # open Builtin # type fixity = #", "# '$$', ( 9,13), Infix(Left()), [] ; # '$', (", "; # '/', (13,13), Infix(Non()), [] ; # '*', (13,13),", "list()) optable[name].append(op) for s in alternatives: optable.setdefault(s, list()) optable[s].append(op) return", "option ; # } class TLAOP: def __init__(self, name, prec,", "(15,15), Postfix, [] ; # '^*', (15,15), Postfix, [] ;", "# (* primitive operators *) # | Logic | Sets", "(8, 8), Infix(Left()), [\"\\\\union\"], nodes.Cup()), (\"\\\\X\", (10, 13), Infix(Left()), [\"\\\\times\"],", "# | BSeq -> nonfix 'BSeq' (Some BSeq) # |", "assoc): self.assoc = assoc # and assoc = # |", "# ':=', ( 5, 5), Infix(Non()), [] ; # '::=',", "[], Mem ; # '\\\\notin', ( 5, 5), Infix(Non()), [],", "'\\\\cup' # # | Prime -> lookup ''' # |", "| Nat -> nonfix 'Nat' (Some Nat) # | Int", "# '<>', ( 4,15), Prefix, [], Diamond ; # ]", "lookup 'DOMAIN' # | Subseteq -> lookup '\\\\subseteq' # |", "class Right(Assoc): pass class Non(Assoc): pass # and dom =", "tab = H.create 109 in # List.iter begin # fun", "(13,13), Infix(Non()), [] ; # '\\\\wr', ( 9,14), Infix(Non()), []", "( 5, 5), Infix(Non()), [] ; # '=<', ( 5,", "-> lookup '\\\\cup' # # | Prime -> lookup '''", "lookup '#' # | Divides -> # { # name", "5,14), Infix(Left()), [], Cdot ; # '-+->', ( 2, 2),", "(5, 5), Infix(Non()), list()), (\"=|\", (5, 5), Infix(Non()), list()), (\"<:\",", "Any) # | ToString -> nonfix 'ToString' (Some ToString) #", "Some Lteq } # | Lt -> { (lookup '<')", "INRIA and Microsoft Corporation # All rights reserved. Licensed under", "(5, 5), Infix(Non()), [\"/=\"], nodes.Neq()), ], ), ( \"Sets\", [", "= a self.b = b # let withdef (name, prec,", "optable = dict() for dom, ops in tlaops: for name,", "( 5, 5), Infix(Non()), [] ; # '\\\\simeq', ( 5,", "TLAOP(name, prec, fixity, dom, defn) optable.setdefault(name, list()) optable[name].append(op) for s", "(\"-.\", (12, 12), Prefix(), [\"-\"]), (\"-\", (11, 11), Infix(Left()), list()),", "'\\\\odot' ] ; # '(/)', (13,13), Infix(Non()), [ '\\\\oslash' ]", "UNION -> lookup 'UNION' # | DOMAIN -> lookup 'DOMAIN'", "# fix : fixity ; # dom : dom ;", "Nonfix ; dom = User ; defn = defn }", "(\"%%\", (10, 11), Infix(Left()), list()), (\"%\", (10, 11), Infix(Non()), [\"\\\\mod\"]),", "[ (name, prec, fix, als, None) for name, prec, fix,", "H.add tab name op ; # List.iter (fun s ->", "defn = Some Minus } # | Uminus -> {", "| Remainder -> { (lookup '%') with defn = Some", "# name = '?|'; # prec = (10, 11); #", "(15, 15), Postfix(), list()), (\"^#\", (15, 15), Postfix(), list()), (\"<\",", "[ ( \"Logic\", [ (\"=>\", (1, 1), Infix(Non()), list(), nodes.Implies()),", "nodes.Notmem()), (\"\\\\\", (8, 8), Infix(Non()), [\"\\\\setminus\"], nodes.Setminus()), (\"\\\\cap\", (8, 8),", "# Prec self.fix = fixity # Fixity self.dom = dom", "5, 5), Infix(Non()), [] ; # '\\\\subset', ( 5, 5),", "Gt } # | Range -> { (lookup '..') with", "= # (* primitive operators *) # | Logic |", "# '\\\\sqcup', ( 9,13), Infix(Left()), [] ; # '\\\\div', (13,13),", "(\"&\", (13, 13), Infix(Left()), list()), (\"$$\", (9, 13), Infix(Left()), list()),", "; # '\\\\cap', ( 8, 8), Infix(Left()), [ '\\\\intersect' ],", "defn) = ( # name, prec, fix, als, Some defn);;", "-> { (lookup '\\\\div') with defn = Some Quotient }", "[ '\\\\intersect' ], Cap ; # '\\\\cup', ( 8, 8),", "(fun (name, prec, fix, als) -> (name, prec, fix, als,", "# '/\\\\', ( 3, 3), Infix(Left()), [ '\\\\land' ], Conj", "( 5, 5), Infix(Non()), [] ; # '>=', ( 5,", "| FALSE -> nonfix 'FALSE' (Some FALSE) # | Implies", "(11,11), Infix(Left()), [] ; # '**', (13,13), Infix(Left()), [] ;", "class Prec: def __init__(self, a, b): self.a = a self.b", "California Institute of Technology # Copyright (c) 2008-2013 INRIA and", "[], Actplus ; # '[]', ( 4,15), Prefix, [], Box", "TLCSet -> nonfix 'TLCSet' (Some TLCSet) # | Permutations ->", "Infix(Left()), [ '\\\\oplus' ] ; # '(-)', (11,11), Infix(Left()), [", "# '=|', ( 5, 5), Infix(Non()), [] ; # '<:',", "list()), (\"<:\", (7, 7), Infix(Non()), list()), (\":>\", (7, 7), Infix(Non()),", "; # '\\\\preceq', ( 5, 5), Infix(Non()), [] ; #", "'\\\\gg', ( 5, 5), Infix(Non()), [] ; # '\\\\asymp', (", "), ( \"Modal\", [ (\"'\", (15, 15), Postfix(), list(), nodes.Prime()),", "-> lookup '/\\\\' # | Disj -> lookup '\\\\/' #", "Exp -> { (lookup '^') with defn = Some Exp", "self.b = b # let withdef (name, prec, fix, als,", "name = '?|'; # prec = (10, 11); # fix", "lookup name = # if Hashtbl.mem optable name then #", "| Extend -> { (lookup '@@') with defn = Some", "4,15), Prefix, [], ENABLED ; # 'UNCHANGED', ( 4,15), Prefix,", "defn = Some Quotient } # | Remainder -> {", "(\"-\", (11, 11), Infix(Left()), list()), (\"+\", (10, 10), Infix(Left()), list()),", "| User dom = {\"Logic\", \"Sets\", \"Modal\", \"User\"} # type", "Divides -> # { # name = '?|'; # prec", "Infix(Left()), [] ; # '??', ( 9,13), Infix(Left()), [] ;", "-> lookup '\\\\cdot' # | Actplus -> lookup '-+->' #", "2008-2013 INRIA and Microsoft Corporation # All rights reserved. Licensed", "= '-' } # | Times -> { (lookup '*')", "Modal # (* user-definable operators *) # | User dom", "; name = '-' } # | Times -> {", "# defn = defn } # in # H.add tab", "'\\\\div') with defn = Some Quotient } # | Remainder", "# '\\\\supset', ( 5, 5), Infix(Non()), [] ; # '\\\\supseteq',", "'\\\\leadsto' ], Leadsto ; # 'ENABLED', ( 4,15), Prefix, [],", "Infix(Non()), list()), (\"/\", (13, 13), Infix(Non()), list()), (\"*\", (13, 13),", "( 9,13), Infix(Left()), [] ; # '++', (10,10), Infix(Left()), []", "{ (lookup '..') with defn = Some Range } #", "# | ToString -> nonfix 'ToString' (Some ToString) # #", "# fun (name, prec, fix, als, defn) -> # let", "[\"\\\\lor\"], nodes.Disj()), (\"~\", (4, 4), Prefix(), [\"\\\\neg\", \"\\\\lnot\"], nodes.Neg()), (\"=\",", "Equiv -> lookup '<=>' # | Conj -> lookup '/\\\\'", "# let nonfix name defn = # { name =", "Exp } # | Lteq -> { (lookup '=<') with", "list()), (\"\\\\preceq\", (5, 5), Infix(Non()), list()), (\"\\\\succeq\", (5, 5), Infix(Non()),", "# end tlaops ; # tab def _generate_optable(): tlaops =", "| Subseteq -> lookup '\\\\subseteq' # | Mem -> lookup", "b = # match b with # | TRUE ->", "15), Postfix(), list()), (\"<\", (5, 5), Infix(Non()), list()), (\"=<\", (5,", "Infix(Non()), list()), (\"\\\\ll\", (5, 5), Infix(Non()), list()), (\"\\\\gg\", (5, 5),", "; # dom : dom ; # defn : Builtin.builtin", "[], ENABLED ; # 'UNCHANGED', ( 4,15), Prefix, [], UNCHANGED", "Cap -> lookup '\\\\cap' # | Cup -> lookup '\\\\cup'", "Infix(Left()), [ '\\\\odot' ] ; # '(/)', (13,13), Infix(Non()), [", "List.iter begin # fun (name, prec, fix, als, defn) ->", "list()), (\"^#\", (15, 15), Postfix(), list()), (\"<\", (5, 5), Infix(Non()),", "(\"<>\", (4, 15), Prefix(), list(), nodes.Diamond()), ], ), ( \"User\",", "-> lookup '\\\\/' # | Neg -> lookup '~' #", "defn = Some Exp } # | Lteq -> {", "(1, 1), Infix(Non()), list(), nodes.Implies()), (\"<=>\", (2, 2), Infix(Non()), [\"\\\\equiv\"],", "als # end ops # end tlaops ; # tab", "| Unprimable -> nonfix 'Unprimable' None # | Irregular ->", "5), Infix(Non()), [] ; # '\\\\subset', ( 5, 5), Infix(Non()),", "| Notmem -> lookup '\\\\notin' # | Setminus -> lookup", "; # '++', (10,10), Infix(Left()), [] ; # '--', (11,11),", "( 5, 5), Infix(Non()), [] ; # '\\\\sqsubseteq', ( 5,", "nonfix 'BSeq' (Some BSeq) # | Append -> nonfix 'Append'", "# '<', ( 5, 5), Infix(Non()), [] ; # '=<',", "(\"\\\\simeq\", (5, 5), Infix(Non()), list()), (\"\\\\ll\", (5, 5), Infix(Non()), list()),", "# | Box _ -> lookup '[]' # | Diamond", "Prefix, [], Diamond ; # ] ; # User, #", "# '+', (10,10), Infix(Left()), [] ; # '^+', (15,15), Postfix,", "; # prec = prec ; # fix = fix", "let standard_form b = # match b with # |", "defn = Some Times } # | Ratio -> {", "Prefix(), [\"-\"]), (\"-\", (11, 11), Infix(Left()), list()), (\"+\", (10, 10),", "| Lteq -> { (lookup '=<') with defn = Some", "defn = Some Lteq } # | Lt -> {", "# User, # List.map (fun (name, prec, fix, als) ->", "'\\\\sqsubseteq', ( 5, 5), Infix(Non()), [] ; # '\\\\sqsupset', (", "-> { (lookup '-.') with defn = Some Uminus ;", "# let tab = H.create 109 in # List.iter begin", "class Infix(Fixity): def __init__(self, assoc): self.assoc = assoc # and", "} # # let lookup name = # if Hashtbl.mem", "5), Infix(Non()), [] ; # '-|', ( 5, 5), Infix(Non()),", "5), Infix(Non()), list()), (\"\\\\propto\", (5, 5), Infix(Non()), list()), ] ],", "[ '\\\\lor' ], Disj ; # '~', ( 4, 4),", "7), Infix(Non()), [] ; # ':>', ( 7, 7), Infix(Non()),", "] ; # '>', ( 5, 5), Infix(Non()), [] ;", "13), Infix(Left()), list()), (\"\\\\sqcap\", (9, 13), Infix(Left()), list()), (\"\\\\sqcup\", (9,", "'$', ( 9,13), Infix(Left()), [] ; # '??', ( 9,13),", "(5, 5), Infix(Non()), list()), ] ], ), ] return tlaops", "# '**', (13,13), Infix(Left()), [] ; # '//', (13,13), Infix(Non()),", "defn = Some Ratio } # | Quotient -> {", "'\\\\uplus', ( 9,13), Infix(Left()), [] ; # '\\\\sqcap', ( 9,13),", "'|', (10,11), Infix(Left()), [] ; # '||', (10,11), Infix(Left()), []", "in # H.add tab name op ; # List.iter (fun", "| UNION -> lookup 'UNION' # | DOMAIN -> lookup", "Infix(Non()), [] ; # '\\\\supset', ( 5, 5), Infix(Non()), []", "[] ; # '\\\\supset', ( 5, 5), Infix(Non()), [] ;", "(\"\\\\uplus\", (9, 13), Infix(Left()), list()), (\"\\\\sqcap\", (9, 13), Infix(Left()), list()),", "nodes.Mem()), (\"\\\\notin\", (5, 5), Infix(Non()), [], nodes.Notmem()), (\"\\\\\", (8, 8),", "(dom, ops) -> # List.iter begin # fun (name, prec,", "(10, 11), Infix(Non()), [\"\\\\mod\"]), (\"##\", (9, 13), Infix(Left()), list()), (\"++\",", "(\"\\\\gg\", (5, 5), Infix(Non()), list()), (\"\\\\asymp\", (5, 5), Infix(Non()), list()),", "Infix(Left()), list()), (\"//\", (13, 13), Infix(Non()), list()), (\"^^\", (14, 14),", "Infix(Left()), [] ; # '\\\\sqcup', ( 9,13), Infix(Left()), [] ;", "# '-.', (12,12), Prefix, [ '-' ] ; # '-',", "| Cdot -> lookup '\\\\cdot' # | Actplus -> lookup", "Infix(Left()), list()), (\"%\", (10, 11), Infix(Non()), [\"\\\\mod\"]), (\"##\", (9, 13),", "defn : Builtin.builtin option ; # } class TLAOP: def", "# ] ; # Sets, # [ '\\\\X', (10,13), Prefix,", "'\\\\preceq', ( 5, 5), Infix(Non()), [] ; # '\\\\succeq', (", "name # else # nonfix name None # # (**", "'~>', ( 2, 2), Infix(Non()), [ '\\\\leadsto' ], Leadsto ;", "optable[name].append(op) for s in alternatives: optable.setdefault(s, list()) optable[s].append(op) return optable", "prec, fix, als, None)) [ # '^', (14,14), Infix(Non()), []", "| Seq -> nonfix 'Seq' (Some Seq) # | Len", "optable.setdefault(s, list()) optable[s].append(op) return optable optable = _generate_optable() # pprint.pprint(optable)", "Infix(Non()), list()), (\":>\", (7, 7), Infix(Non()), list()), (\":=\", (5, 5),", "[ '\\\\ominus' ] ; # '(.)', (13,13), Infix(Left()), [ '\\\\odot'", "fix, als, None) for name, prec, fix, als in [", "2), Infix(Non()), [\"\\\\equiv\"], nodes.Equiv()), (\"/\\\\\", (3, 3), Infix(Left()), [\"\\\\land\"], nodes.Conj()),", "(5, 5), Infix(Non()), list()), (\"\\\\subset\", (5, 5), Infix(Non()), list()), (\"\\\\supset\",", "Some Times } # | Ratio -> { (lookup '/')", "} class TLAOP: def __init__(self, name, prec, fixity, dom, defn):", "9,13), Infix(Left()), [] ; # '%%', (10,11), Infix(Left()), [] ;", "| Equiv -> lookup '<=>' # | Conj -> lookup", "(10, 11), Infix(Left()), list()), (\"%\", (10, 11), Infix(Non()), [\"\\\\mod\"]), (\"##\",", "'|=', ( 5, 5), Infix(Non()), [] ; # '-|', (", "list()), (\"|-\", (5, 5), Infix(Non()), list()), (\"|=\", (5, 5), Infix(Non()),", "(\"::=\", (5, 5), Infix(Non()), list()), (\"(+)\", (10, 10), Infix(Left()), [\"\\\\oplus\"]),", "Uminus -> { (lookup '-.') with defn = Some Uminus", "9,13), Infix(Non()), [] ; # '|-', ( 5, 5), Infix(Non()),", "[] ; # '|=', ( 5, 5), Infix(Non()), [] ;", "# '\\\\prec', ( 5, 5), Infix(Non()), [] ; # '\\\\succ',", "[\"\\\\oplus\"]), (\"(-)\", (11, 11), Infix(Left()), [\"\\\\ominus\"]), (\"(.)\", (13, 13), Infix(Left()),", "Prefix(), list(), nodes.UNION()), (\"DOMAIN\", (9, 9), Prefix(), list(), nodes.DOMAIN()), (\"\\\\subseteq\",", "(\"++\", (10, 10), Infix(Left()), list()), (\"--\", (11, 11), Infix(Left()), list()),", "Divides; # } # # | STRING -> nonfix 'STRING'", "Cdot ; # '-+->', ( 2, 2), Infix(Non()), [], Actplus", "-> lookup 'ENABLED' # | UNCHANGED -> lookup 'UNCHANGED' #", "fix, als) -> (name, prec, fix, als, None)) [ #", "Infix(Non()), [] ; # '<:', ( 7, 7), Infix(Non()), []", "; # '\\\\approx', ( 5, 5), Infix(Non()), [] ; #", "(11,11), Infix(Left()), [ '\\\\ominus' ] ; # '(.)', (13,13), Infix(Left()),", "Infix(Left()), [\"\\\\ominus\"]), (\"(.)\", (13, 13), Infix(Left()), [\"\\\\odot\"]), (\"(/)\", (13, 13),", "Int) # | Real -> nonfix 'Real' (Some Real) #", "(\"ENABLED\", (4, 15), Prefix(), list(), nodes.ENABLED()), (\"UNCHANGED\", (4, 15), Prefix(),", "} # | Range -> { (lookup '..') with defn", "s in alternatives: optable.setdefault(s, list()) optable[s].append(op) return optable optable =", "[] ; # '\\\\star', (13,13), Infix(Left()), [] ; # '\\\\o',", "9,13), Infix(Left()), [] ; # '\\\\div', (13,13), Infix(Non()), [] ;", "'DOMAIN' # | Subseteq -> lookup '\\\\subseteq' # | Mem", "Lt } # | Gteq -> { (lookup '>=') with", "; # '--', (11,11), Infix(Left()), [] ; # '**', (13,13),", "(13, 13), Infix(Left()), list()), (\"\\\\o\", (13, 13), Infix(Left()), [\"\\\\circ\"]), (\"\\\\bigcirc\",", "self.dom = dom self.defn = defn def __repr__(self): return (", "Infix(Non()), list()), (\">=\", (5, 5), Infix(Non()), [\"\\\\geq\"]), (\"...\", (9, 9),", "6, 6), Infix(Left()), [] ; # '!!', ( 9,13), Infix(Non()),", "list()), (\"$\", (9, 13), Infix(Left()), list()), (\"??\", (9, 13), Infix(Left()),", "5), Infix(Non()), [] ; # '\\\\simeq', ( 5, 5), Infix(Non()),", "5, 5), Infix(Non()), [] ; # '\\\\preceq', ( 5, 5),", "[\"\\\\union\"], nodes.Cup()), (\"\\\\X\", (10, 13), Infix(Left()), [\"\\\\times\"], None), ], ),", "nodes.Conj()), (\"\\\\/\", (3, 3), Infix(Left()), [\"\\\\lor\"], nodes.Disj()), (\"~\", (4, 4),", "= Infix(Non()); # dom = Logic; # defn = Some", "( 5, 5), Infix(Non()), [] ; # '\\\\approx', ( 5,", "# | User dom = {\"Logic\", \"Sets\", \"Modal\", \"User\"} #", "(9, 13), Infix(Left()), list()), (\"??\", (9, 13), Infix(Left()), list()), (\"%%\",", "13), Infix(Non()), list()), (\"^^\", (14, 14), Infix(Non()), list()), (\"@@\", (6,", "List.map (fun (name, prec, fix, als) -> (name, prec, fix,", "; # '\\\\subset', ( 5, 5), Infix(Non()), [] ; #", "Infix(Non()), [] ; # '|-', ( 5, 5), Infix(Non()), []", "ToString) # # | Unprimable -> nonfix 'Unprimable' None #", "Head) # | Tail -> nonfix 'Tail' (Some Tail) #", "# ] ; # ] def _generate_tlaops(): tlaops = [", "Prefix, [ '\\\\neg' ; '\\\\lnot' ], Neg ; # '=',", "# | Real -> nonfix 'Real' (Some Real) # |", "= # | Left | Non | Right class Assoc:", "5), Infix(Non()), [] ; # '\\\\doteq', ( 5, 5), Infix(Non()),", "# '^^', (14,14), Infix(Non()), [] ; # '@@', ( 6,", "Gteq } # | Gt -> { (lookup '>') with", "'$$', ( 9,13), Infix(Left()), [] ; # '$', ( 9,13),", "nonfix 'Infinity' (Some Infinity) # # | Seq -> nonfix", "pass class Left(Assoc): pass class Right(Assoc): pass class Non(Assoc): pass", "5, 5), Infix(Non()), [ '/=' ], Neq ; # ]", "defn = tuple_ return (name, prec, fix, als, defn) #", "(10, 11); # fix = Infix(Non()); # dom = Logic;", "(5, 5), Infix(Non()), list(), nodes.Subseteq()), (\"\\\\in\", (5, 5), Infix(Non()), list(),", "-> lookup '\\\\' # | Cap -> lookup '\\\\cap' #", "'PrintT' (Some PrintT) # | Assert -> nonfix 'Assert' (Some", "[] ; # '\\\\succeq', ( 5, 5), Infix(Non()), [] ;", "[\"\\\\geq\"]), (\"...\", (9, 9), Infix(Non()), list()), (\"..\", (9, 9), Infix(Non()),", "; # '^^', (14,14), Infix(Non()), [] ; # '@@', (", "nodes.Cup()), (\"\\\\X\", (10, 13), Infix(Left()), [\"\\\\times\"], None), ], ), (", "tlaops # type tlaop = { # name : string", "} # | Nat -> nonfix 'Nat' (Some Nat) #", "defn = defn } # in # H.add tab name", "Infix(Left()), [\"\\\\oplus\"]), (\"(-)\", (11, 11), Infix(Left()), [\"\\\\ominus\"]), (\"(.)\", (13, 13),", "= name # str self.prec = prec # Prec self.fix", "Sets | Modal # (* user-definable operators *) # |", "list()), (\"//\", (13, 13), Infix(Non()), list()), (\"^^\", (14, 14), Infix(Non()),", "(\"\\\\sim\", (5, 5), Infix(Non()), list()), (\"\\\\simeq\", (5, 5), Infix(Non()), list()),", "(\"\\\\sqcap\", (9, 13), Infix(Left()), list()), (\"\\\\sqcup\", (9, 13), Infix(Left()), list()),", "[] ; # '>=', ( 5, 5), Infix(Non()), [ '\\\\geq'", "= defn } # in # H.add tab name op", "# | Seq -> nonfix 'Seq' (Some Seq) # |", "prec, fix, als) -> (name, prec, fix, als, None)) [", "'||', (10,11), Infix(Left()), [] ; # '&&', (13,13), Infix(Left()), []", "'-|', ( 5, 5), Infix(Non()), [] ; # '=|', (", "] return tlaops # type tlaop = { # name", "5, 5), Infix(Non()), [] ; # '\\\\propto', ( 5, 5),", "{ (lookup '-') with defn = Some Minus } #", "# '/', (13,13), Infix(Non()), [] ; # '*', (13,13), Infix(Left()),", "# prec = (10, 11); # fix = Infix(Non()); #", "rights reserved. Licensed under 3-clause BSD. # # This module", "(10, 11), Infix(Left()), list()), (\"||\", (10, 11), Infix(Left()), list()), (\"&&\",", "(\"//\", (13, 13), Infix(Non()), list()), (\"^^\", (14, 14), Infix(Non()), list()),", "'[]' # | Diamond -> lookup '<>' # # |", "; # 'DOMAIN', ( 9, 9), Prefix, [], DOMAIN ;", "with defn = Some Plus } # | Minus ->", "# '\\\\star', (13,13), Infix(Left()), [] ; # '\\\\o', (13,13), Infix(Left()),", "(3, 3), Infix(Left()), [\"\\\\land\"], nodes.Conj()), (\"\\\\/\", (3, 3), Infix(Left()), [\"\\\\lor\"],", "| Divides -> # { # name = '?|'; #", "(5, 5), Infix(Non()), list(), nodes.Eq()), (\"#\", (5, 5), Infix(Non()), [\"/=\"],", "'\\\\wr', ( 9,14), Infix(Non()), [] ; # '\\\\star', (13,13), Infix(Left()),", "standard_form b = # match b with # | TRUE", "'JavaTime' (Some JavaTime) # | TLCGet -> nonfix 'TLCGet' (Some", "{ (lookup '>=') with defn = Some Gteq } #", "-> nonfix 'SelectSeq' (Some SelectSeq) # # | OneArg ->", "11), Infix(Left()), list()), (\"%\", (10, 11), Infix(Non()), [\"\\\\mod\"]), (\"##\", (9,", "Permutations -> nonfix 'Permutations' (Some Permutations) # | SortSeq ->", "(\"\\\\preceq\", (5, 5), Infix(Non()), list()), (\"\\\\succeq\", (5, 5), Infix(Non()), list()),", "= H.create 109 in # List.iter begin # fun (dom,", "Seq -> nonfix 'Seq' (Some Seq) # | Len ->", "Infix(Non()), [] ; # '\\\\wr', ( 9,14), Infix(Non()), [] ;", "s op) als # end ops # end tlaops ;", "; # '\\\\/', ( 3, 3), Infix(Left()), [ '\\\\lor' ],", "; '\\\\leq' ] ; # '>', ( 5, 5), Infix(Non()),", "# | Len -> nonfix 'Len' (Some Len) # |", "Postfix(), list()), (\"<\", (5, 5), Infix(Non()), list()), (\"=<\", (5, 5),", ") # let optable = # let module H =", "'...', ( 9, 9), Infix(Non()), [] ; # '..', (", "10), Infix(Left()), [\"\\\\oplus\"]), (\"(-)\", (11, 11), Infix(Left()), [\"\\\\ominus\"]), (\"(.)\", (13,", "prec, fixity, alternatives, defn in ops: op = TLAOP(name, prec,", "Print) # | PrintT -> nonfix 'PrintT' (Some PrintT) #", "[] ; # '\\\\supseteq', ( 5, 5), Infix(Non()), [] ;", "; # '\\\\sqsubset', ( 5, 5), Infix(Non()), [] ; #", "11), Infix(Left()), list()), (\"+\", (10, 10), Infix(Left()), list()), (\"^+\", (15,", "= Some Lteq } # | Lt -> { (lookup", "5), Infix(Non()), list()), (\"-|\", (5, 5), Infix(Non()), list()), (\"=|\", (5,", "match b with # | TRUE -> nonfix 'TRUE' (Some", "5), Infix(Non()), list()), (\"\\\\sqsubseteq\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupset\", (5,", "; # '-+->', ( 2, 2), Infix(Non()), [], Actplus ;", "(13,13), Infix(Left()), [ '\\\\circ' ] ; # '\\\\bigcirc', (13,13), Infix(Left()),", "'STRING' (Some STRING) # | BOOLEAN -> nonfix 'BOOLEAN' (Some", "# '\\\\subset', ( 5, 5), Infix(Non()), [] ; # '\\\\supset',", "Quotient } # | Remainder -> { (lookup '%') with", "tab def _generate_optable(): tlaops = _generate_tlaops() optable = dict() for", "(13, 13), Infix(Left()), list()), (\"$$\", (9, 13), Infix(Left()), list()), (\"$\",", "Infix(Non()), list()), (\"\\\\simeq\", (5, 5), Infix(Non()), list()), (\"\\\\ll\", (5, 5),", "# let withdef (name, prec, fix, als, defn) = (", "fix = fix ; dom = dom ; # defn", "Permutations) # | SortSeq -> nonfix 'SortSeq' (Some SortSeq) #", "Infix(Left()), [] ; # '-.', (12,12), Prefix, [ '-' ]", "# } class TLAOP: def __init__(self, name, prec, fixity, dom,", "2, 2), Infix(Non()), [], Actplus ; # '[]', ( 4,15),", "(\"~>\", (2, 2), Infix(Non()), [\"\\\\leadsto\"], nodes.LeadsTo()), (\"ENABLED\", (4, 15), Prefix(),", "prec, fixity, dom, defn): self.name = name # str self.prec", "__init__(self, assoc): self.assoc = assoc # and assoc = #", "], None ] ; # Modal, # List.map withdef [", "9,14), Infix(Non()), [] ; # '\\\\star', (13,13), Infix(Left()), [] ;", "# List.map (fun (name, prec, fix, als) -> (name, prec,", "(8, 8), Prefix(), list(), nodes.SUBSET()), (\"UNION\", (8, 8), Prefix(), list(),", "; # '^*', (15,15), Postfix, [] ; # '^#', (15,15),", "14), Infix(Left()), list(), nodes.Cdot()), (\"-+->\", (2, 2), Infix(Non()), list(), nodes.WhilePlus()),", "Infix(Non()), [], Implies ; # '<=>', ( 2, 2), Infix(Non()),", "= b # let withdef (name, prec, fix, als, defn)", "f\"{self.fix}, {self.dom}, {self.defn})\" ) # let optable = # let", "fix, als, Some defn);; def withdef(tuple_): name, prec, fix, als,", "import Nodes as nodes # open Builtin # type fixity", "; # ] def _generate_tlaops(): tlaops = [ ( \"Logic\",", "lookup '\\\\notin' # | Setminus -> lookup '\\\\' # |", "(5, 5), Infix(Non()), list()), (\"\\\\ll\", (5, 5), Infix(Non()), list()), (\"\\\\gg\",", "Infix(Non()), list()), (\"..\", (9, 9), Infix(Non()), list()), (\"|\", (10, 11),", "7), Infix(Non()), [] ; # ':=', ( 5, 5), Infix(Non()),", "13), Infix(Non()), list()), (\"*\", (13, 13), Infix(Left()), list()), (\"-.\", (12,", "(\"\\\\asymp\", (5, 5), Infix(Non()), list()), (\"\\\\subset\", (5, 5), Infix(Non()), list()),", "(5, 5), Infix(Non()), list()), (\"-|\", (5, 5), Infix(Non()), list()), (\"=|\",", "name # str self.prec = prec # Prec self.fix =", "Infix(Non()), list()), (\"\\\\supseteq\", (5, 5), Infix(Non()), list()), (\"\\\\approx\", (5, 5),", "; # '<>', ( 4,15), Prefix, [], Diamond ; #", "; dom = User ; defn = defn } #", "type tlaop = { # name : string ; #", "Remainder } # | Exp -> { (lookup '^') with", "5), Infix(Non()), [] ; # '\\\\gg', ( 5, 5), Infix(Non()),", "\"\"\"Table of operators.\"\"\" # Copyright 2020 by California Institute of", "[ '\\\\equiv' ], Equiv ; # '/\\\\', ( 3, 3),", "Infix(Non()), [] ; # '\\\\preceq', ( 5, 5), Infix(Non()), []", "(9, 13), Infix(Non()), list()), (\"|-\", (5, 5), Infix(Non()), list()), (\"|=\",", "(5, 5), Infix(Non()), list(), nodes.Mem()), (\"\\\\notin\", (5, 5), Infix(Non()), [],", "name = name ; prec = (-1, -1) ; #", "# '^#', (15,15), Postfix, [] ; # '<', ( 5,", "[ '\\\\oslash' ] ; # '(\\\\X)', (13,13), Infix(Left()), [ '\\\\otimes'", "(\"\\\\o\", (13, 13), Infix(Left()), [\"\\\\circ\"]), (\"\\\\bigcirc\", (13, 13), Infix(Left()), list()),", "(* primitive operators *) # | Logic | Sets |", "], ), ( \"Sets\", [ (\"SUBSET\", (8, 8), Prefix(), list(),", "-1) ; # fix = Nonfix ; dom = User", "(6, 6), Infix(Left()), list()), (\"!!\", (9, 13), Infix(Non()), list()), (\"|-\",", "withdef(tuple_): name, prec, fix, als, defn = tuple_ return (name,", "for name, prec, fixity, alternatives, defn in ops: op =", "Infix(Non()), [\"\\\\geq\"]), (\"...\", (9, 9), Infix(Non()), list()), (\"..\", (9, 9),", "# '\\\\sqcap', ( 9,13), Infix(Left()), [] ; # '\\\\sqcup', (", "5, 5), Infix(Non()), [] ; # '<:', ( 7, 7),", "list()), (\"%\", (10, 11), Infix(Non()), [\"\\\\mod\"]), (\"##\", (9, 13), Infix(Left()),", "Infix(Non()), [] ; # '=<', ( 5, 5), Infix(Non()), [", "class Postfix(Fixity): pass class Infix(Fixity): def __init__(self, assoc): self.assoc =", "(Some BOOLEAN) # | SUBSET -> lookup 'SUBSET' # |", "(5, 5), Infix(Non()), [\"<=\", \"\\\\leq\"]), (\">\", (5, 5), Infix(Non()), list()),", "= tuple_ return (name, prec, fix, als, defn) # let", "{ (lookup '<') with defn = Some Lt } #", "5), Infix(Non()), [] ; # '\\\\sqsubset', ( 5, 5), Infix(Non()),", "; # '\\\\sqcap', ( 9,13), Infix(Left()), [] ; # '\\\\sqcup',", "'%') with defn = Some Remainder } # | Exp", "# | TLCSet -> nonfix 'TLCSet' (Some TLCSet) # |", "# let lookup name = # if Hashtbl.mem optable name", "als, defn = tuple_ return (name, prec, fix, als, defn)", "[] ; # '=<', ( 5, 5), Infix(Non()), [ '<='", "8, 8), Prefix, [], UNION ; # 'DOMAIN', ( 9,", "11); # fix = Infix(Non()); # dom = Logic; #", "PrintT -> nonfix 'PrintT' (Some PrintT) # | Assert ->", "'\\\\/' # | Neg -> lookup '~' # | Eq", "(9, 13), Infix(Left()), list()), (\"\\\\sqcup\", (9, 13), Infix(Left()), list()), (\"\\\\div\",", "# ] ; # User, # List.map (fun (name, prec,", "nonfix 'TRUE' (Some TRUE) # | FALSE -> nonfix 'FALSE'", "fixity = # | Nonfix # | Prefix | Postfix", "'+') with defn = Some Plus } # | Minus", "[] ; # '<:', ( 7, 7), Infix(Non()), [] ;", "( 5, 5), Infix(Non()), [] ; # '\\\\sqsubset', ( 5,", "Non(Assoc): pass # and dom = # (* primitive operators", "# '\\\\sqsubseteq', ( 5, 5), Infix(Non()), [] ; # '\\\\sqsupset',", "fix = Infix(Non()); # dom = Logic; # defn =", "| SelectSeq -> nonfix 'SelectSeq' (Some SelectSeq) # # |", "( 5, 5), Infix(Non()), [] ; # '\\\\supseteq', ( 5,", "14), Infix(Non()), list()), (\"\\\\star\", (13, 13), Infix(Left()), list()), (\"\\\\o\", (13,", "tlaops = [ # Logic, # List.map withdef [ #", "(\"/\\\\\", (3, 3), Infix(Left()), [\"\\\\land\"], nodes.Conj()), (\"\\\\/\", (3, 3), Infix(Left()),", "with defn = Some Exp } # | Lteq ->", "module is based on the file: # # <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> #", "# import pprint from .ast import Nodes as nodes #", "Gt -> { (lookup '>') with defn = Some Gt", "8, 8), Infix(Left()), [ '\\\\union' ], Cup ; # ]", "( 8, 8), Prefix, [], UNION ; # 'DOMAIN', (", "[] ; # '$$', ( 9,13), Infix(Left()), [] ; #", "[ # 'SUBSET', ( 8, 8), Prefix, [], SUBSET ;", "':=', ( 5, 5), Infix(Non()), [] ; # '::=', (", "; # defn = defn } # in # H.add", "( \"Modal\", [ (\"'\", (15, 15), Postfix(), list(), nodes.Prime()), (\"~>\",", "; # '(+)', (10,10), Infix(Left()), [ '\\\\oplus' ] ; #", "operators.\"\"\" # Copyright 2020 by California Institute of Technology #", "prec # Prec self.fix = fixity # Fixity self.dom =", "[] ; # '%%', (10,11), Infix(Left()), [] ; # '%',", "( 5, 5), Infix(Non()), [ '<=' ; '\\\\leq' ] ;", "[\"\\\\leadsto\"], nodes.LeadsTo()), (\"ENABLED\", (4, 15), Prefix(), list(), nodes.ENABLED()), (\"UNCHANGED\", (4,", "Infix(Non()), list()), (\"\\\\sim\", (5, 5), Infix(Non()), list()), (\"\\\\simeq\", (5, 5),", "defn = Some Extend } # | Print -> nonfix", "User ; defn = defn } # # let lookup", "reserved. Licensed under 3-clause BSD. # # This module is", "Infix(Non()), list()), ] ], ), ] return tlaops # type", "; # '<=>', ( 2, 2), Infix(Non()), [ '\\\\equiv' ],", "-> lookup 'SUBSET' # | UNION -> lookup 'UNION' #", "(\"\\\\bullet\", (13, 13), Infix(Left()), list()), (\"\\\\prec\", (5, 5), Infix(Non()), list()),", "'\\\\cdot', ( 5,14), Infix(Left()), [], Cdot ; # '-+->', (", "'<:', ( 7, 7), Infix(Non()), [] ; # ':>', (", "[] ; # '//', (13,13), Infix(Non()), [] ; # '^^',", "5, 5), Infix(Non()), [] ; # '\\\\gg', ( 5, 5),", "(10,10), Infix(Left()), [] ; # '--', (11,11), Infix(Left()), [] ;", "; # '$', ( 9,13), Infix(Left()), [] ; # '??',", "'..') with defn = Some Range } # | Nat", "and dom = # (* primitive operators *) # |", "# | Cat -> { (lookup '\\\\o') with defn =", "TLCSet) # | Permutations -> nonfix 'Permutations' (Some Permutations) #", "( 9, 9), Infix(Non()), [] ; # '..', ( 9,", "; # '\\\\cdot', ( 5,14), Infix(Left()), [], Cdot ; #", "5), Infix(Non()), list()), (\"=<\", (5, 5), Infix(Non()), [\"<=\", \"\\\\leq\"]), (\">\",", "(Some JavaTime) # | TLCGet -> nonfix 'TLCGet' (Some TLCGet)", "nonfix name None # # (** Mapping from builtins to", "Infix(Left()), [\"\\\\odot\"]), (\"(/)\", (13, 13), Infix(Non()), [\"\\\\oslash\"]), (\"(\\\\X)\", (13, 13),", "nonfix 'Seq' (Some Seq) # | Len -> nonfix 'Len'", "list()), (\"\\\\sqsubset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubseteq\", (5, 5), Infix(Non()),", "'=<') with defn = Some Lteq } # | Lt", "; # '|', (10,11), Infix(Left()), [] ; # '||', (10,11),", "return ( f\"TLAOP({self.name}, {self.prec}, \" f\"{self.fix}, {self.dom}, {self.defn})\" ) #", "for s in alternatives: optable.setdefault(s, list()) optable[s].append(op) return optable optable", "} # | Remainder -> { (lookup '%') with defn", "| Setminus -> lookup '\\\\' # | Cap -> lookup", "5), Infix(Non()), list()), (\"\\\\gg\", (5, 5), Infix(Non()), list()), (\"\\\\asymp\", (5,", "'<=>', ( 2, 2), Infix(Non()), [ '\\\\equiv' ], Equiv ;", "ENABLED ; # 'UNCHANGED', ( 4,15), Prefix, [], UNCHANGED ;", "SubSeq -> nonfix 'SubSeq' (Some SubSeq) # | SelectSeq ->", "None)) [ # '^', (14,14), Infix(Non()), [] ; # '/',", "= prec ; # fix = fix ; dom =", "if Hashtbl.mem optable name then # Hashtbl.find optable name #", "# '++', (10,10), Infix(Left()), [] ; # '--', (11,11), Infix(Left()),", "(10,11), Infix(Left()), [] ; # '&&', (13,13), Infix(Left()), [] ;", "(5, 5), Infix(Non()), list()), (\"\\\\supset\", (5, 5), Infix(Non()), list()), (\"\\\\supseteq\",", "optable = _generate_optable() # pprint.pprint(optable) # let nonfix name defn", "-> nonfix 'Append' (Some Append) # | Cat -> {", "| Minus -> { (lookup '-') with defn = Some", "( 5, 5), Infix(Non()), [] ; # '(+)', (10,10), Infix(Left()),", "None # # (** Mapping from builtins to standard tlaops", "5, 5), Infix(Non()), [] ; # '\\\\sqsubset', ( 5, 5),", "'\\\\neg' ; '\\\\lnot' ], Neg ; # '=', ( 5,", "= # { name = name ; prec = (-1,", "(5, 5), Infix(Non()), list()), (\"=<\", (5, 5), Infix(Non()), [\"<=\", \"\\\\leq\"]),", "dom = dom ; # defn = defn } #", "5), Infix(Non()), [] ; # '(+)', (10,10), Infix(Left()), [ '\\\\oplus'", "Minus } # | Uminus -> { (lookup '-.') with", "3), Infix(Left()), [\"\\\\lor\"], nodes.Disj()), (\"~\", (4, 4), Prefix(), [\"\\\\neg\", \"\\\\lnot\"],", "] ; # '\\\\bigcirc', (13,13), Infix(Left()), [] ; # '\\\\bullet',", "lookup '\\\\cap' # | Cup -> lookup '\\\\cup' # #", "Infix(Left()), list()), (\"\\\\sqcap\", (9, 13), Infix(Left()), list()), (\"\\\\sqcup\", (9, 13),", "Tail) # | SubSeq -> nonfix 'SubSeq' (Some SubSeq) #", "Infix(Left()), list()), (\"%%\", (10, 11), Infix(Left()), list()), (\"%\", (10, 11),", "# let tlaops = [ # Logic, # List.map withdef", "list()), (\"\\\\asymp\", (5, 5), Infix(Non()), list()), (\"\\\\subset\", (5, 5), Infix(Non()),", "-> lookup '~>' # | ENABLED -> lookup 'ENABLED' #", "list()), (\"^+\", (15, 15), Postfix(), list()), (\"^*\", (15, 15), Postfix(),", "Infix(Left()), [] ; # '++', (10,10), Infix(Left()), [] ; #", "is based on the file: # # <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> # import", "# | Left | Non | Right class Assoc: pass", "Infix(Non()), [] ; # '\\\\simeq', ( 5, 5), Infix(Non()), []", "(5, 5), Infix(Non()), list()), (\"\\\\simeq\", (5, 5), Infix(Non()), list()), (\"\\\\ll\",", "; # fix = fix ; dom = dom ;", "[] ; # '\\\\simeq', ( 5, 5), Infix(Non()), [] ;", "5, 5), Infix(Non()), [] ; # '\\\\cong', ( 5, 5),", "(\"??\", (9, 13), Infix(Left()), list()), (\"%%\", (10, 11), Infix(Left()), list()),", "lookup '~' # | Eq -> lookup '=' # |", "Infix(Non()), [] ; # '|', (10,11), Infix(Left()), [] ; #", "(5, 5), Infix(Non()), list()), (\"\\\\sim\", (5, 5), Infix(Non()), list()), (\"\\\\simeq\",", "fun (name, prec, fix, als, defn) -> # let op", "nodes.LeadsTo()), (\"ENABLED\", (4, 15), Prefix(), list(), nodes.ENABLED()), (\"UNCHANGED\", (4, 15),", "'Any' (Some Any) # | ToString -> nonfix 'ToString' (Some", "\"Modal\", [ (\"'\", (15, 15), Postfix(), list(), nodes.Prime()), (\"~>\", (2,", "(4, 15), Prefix(), list(), nodes.ENABLED()), (\"UNCHANGED\", (4, 15), Prefix(), list(),", "'Int' (Some Int) # | Real -> nonfix 'Real' (Some", "; # '...', ( 9, 9), Infix(Non()), [] ; #", "# '\\\\/', ( 3, 3), Infix(Left()), [ '\\\\lor' ], Disj", "(\"|=\", (5, 5), Infix(Non()), list()), (\"-|\", (5, 5), Infix(Non()), list()),", "= defn def __repr__(self): return ( f\"TLAOP({self.name}, {self.prec}, \" f\"{self.fix},", "Infix(Non()), [\"\\\\mod\"]), (\"##\", (9, 13), Infix(Left()), list()), (\"++\", (10, 10),", "'~>' # | ENABLED -> lookup 'ENABLED' # | UNCHANGED", "-> { (lookup '..') with defn = Some Range }", "Infix(Non()), list()), (\"<:\", (7, 7), Infix(Non()), list()), (\":>\", (7, 7),", "Infix(Non()), [] ; # '/', (13,13), Infix(Non()), [] ; #", "(14,14), Infix(Non()), [] ; # '/', (13,13), Infix(Non()), [] ;", "5), Infix(Non()), list(), nodes.Eq()), (\"#\", (5, 5), Infix(Non()), [\"/=\"], nodes.Neq()),", "(Some FALSE) # | Implies -> lookup '=>' # |", "| TLCGet -> nonfix 'TLCGet' (Some TLCGet) # | TLCSet", "# List.iter (fun s -> H.add tab s op) als", "; # '\\\\sqsupset', ( 5, 5), Infix(Non()), [] ; #", "# | Logic | Sets | Modal # (* user-definable", "(\"(.)\", (13, 13), Infix(Left()), [\"\\\\odot\"]), (\"(/)\", (13, 13), Infix(Non()), [\"\\\\oslash\"]),", "TLAOP: def __init__(self, name, prec, fixity, dom, defn): self.name =", "dom = User ; defn = defn } # #", "name = # if Hashtbl.mem optable name then # Hashtbl.find", "nonfix 'Len' (Some Len) # | BSeq -> nonfix 'BSeq'", "Infix(Non()), [] ; # '\\\\asymp', ( 5, 5), Infix(Non()), []", "5), Infix(Non()), [] ; # '\\\\sim', ( 5, 5), Infix(Non()),", "# '!!', ( 9,13), Infix(Non()), [] ; # '|-', (", "'\\\\ll', ( 5, 5), Infix(Non()), [] ; # '\\\\gg', (", "5), Infix(Non()), list()), (\"(+)\", (10, 10), Infix(Left()), [\"\\\\oplus\"]), (\"(-)\", (11,", "'@@') with defn = Some Extend } # | Print", "prec, fix, als, defn = tuple_ return (name, prec, fix,", "(3, 3), Infix(Left()), [\"\\\\lor\"], nodes.Disj()), (\"~\", (4, 4), Prefix(), [\"\\\\neg\",", "nonfix 'SubSeq' (Some SubSeq) # | SelectSeq -> nonfix 'SelectSeq'", "name ; prec = (-1, -1) ; # fix =", "= Hashtbl in # let tab = H.create 109 in", "list()), (\"*\", (13, 13), Infix(Left()), list()), (\"-.\", (12, 12), Prefix(),", "'\\\\asymp', ( 5, 5), Infix(Non()), [] ; # '\\\\subset', (", "''' # | StrongPrime -> lookup ''' # | Leadsto", "(14,14), Infix(Non()), [] ; # '@@', ( 6, 6), Infix(Left()),", "'\\\\oslash' ] ; # '(\\\\X)', (13,13), Infix(Left()), [ '\\\\otimes' ]", "'\\\\notin', ( 5, 5), Infix(Non()), [], Notmem ; # '\\\\',", "'ENABLED' # | UNCHANGED -> lookup 'UNCHANGED' # | Cdot", "Cat -> { (lookup '\\\\o') with defn = Some Cat", "lookup 'SUBSET' # | UNION -> lookup 'UNION' # |", "'\\\\geq' ] ; # '...', ( 9, 9), Infix(Non()), []", "Infix(Non()), [\"\\\\oslash\"]), (\"(\\\\X)\", (13, 13), Infix(Left()), [\"\\\\otimes\"]), (\"\\\\uplus\", (9, 13),", "(lookup '+') with defn = Some Plus } # |", "{ (lookup ':>') with defn = Some OneArg } #", "b with # | TRUE -> nonfix 'TRUE' (Some TRUE)", "lookup '\\\\/' # | Neg -> lookup '~' # |", "; # Sets, # [ '\\\\X', (10,13), Prefix, [ '\\\\times'", "13), Infix(Non()), list()), (\"\\\\wr\", (9, 14), Infix(Non()), list()), (\"\\\\star\", (13,", "b # let withdef (name, prec, fix, als, defn) =", "'[]', ( 4,15), Prefix, [], Box true ; # '<>',", "-> nonfix 'Assert' (Some Assert) # | JavaTime -> nonfix", "name = name ; # prec = prec ; #", "list()), (\"++\", (10, 10), Infix(Left()), list()), (\"--\", (11, 11), Infix(Left()),", "'\\\\cap' # | Cup -> lookup '\\\\cup' # # |", "| Quotient -> { (lookup '\\\\div') with defn = Some", "# | Any -> nonfix 'Any' (Some Any) # |", "(12, 12), Prefix(), [\"-\"]), (\"-\", (11, 11), Infix(Left()), list()), (\"+\",", "13), Infix(Left()), list()), (\"\\\\div\", (13, 13), Infix(Non()), list()), (\"\\\\wr\", (9,", "nodes.Equiv()), (\"/\\\\\", (3, 3), Infix(Left()), [\"\\\\land\"], nodes.Conj()), (\"\\\\/\", (3, 3),", "pass class Non(Assoc): pass # and dom = # (*", "3), Infix(Left()), [ '\\\\lor' ], Disj ; # '~', (", "[] ; # '\\\\ll', ( 5, 5), Infix(Non()), [] ;", "defn } # in # H.add tab name op ;", "lookup '\\\\cup' # # | Prime -> lookup ''' #", "(\"\\\\\", (8, 8), Infix(Non()), [\"\\\\setminus\"], nodes.Setminus()), (\"\\\\cap\", (8, 8), Infix(Left()),", "; # '%%', (10,11), Infix(Left()), [] ; # '%', (10,11),", "(\"-+->\", (2, 2), Infix(Non()), list(), nodes.WhilePlus()), (\"[]\", (4, 15), Prefix(),", "| Mem -> lookup '\\\\in' # | Notmem -> lookup", "# | Equiv -> lookup '<=>' # | Conj ->", "# | Infinity -> nonfix 'Infinity' (Some Infinity) # #", "; # '\\\\ll', ( 5, 5), Infix(Non()), [] ; #", "(10,10), Infix(Left()), [ '\\\\oplus' ] ; # '(-)', (11,11), Infix(Left()),", "Logic, # List.map withdef [ # '=>', ( 1, 1),", "nodes.Neq()), ], ), ( \"Sets\", [ (\"SUBSET\", (8, 8), Prefix(),", "; # '//', (13,13), Infix(Non()), [] ; # '^^', (14,14),", "withdef [ # 'SUBSET', ( 8, 8), Prefix, [], SUBSET", "= { name = name ; # prec = prec", "end tlaops ; # tab def _generate_optable(): tlaops = _generate_tlaops()", "{self.defn})\" ) # let optable = # let module H", "als, None)) [ # '^', (14,14), Infix(Non()), [] ; #", "# '\\\\cong', ( 5, 5), Infix(Non()), [] ; # '\\\\sqsubset',", "'??', ( 9,13), Infix(Left()), [] ; # '%%', (10,11), Infix(Left()),", "op = { name = name ; # prec =", "prec, fix, als, defn) -> # let op = {", "5), Infix(Non()), [] ; # '>=', ( 5, 5), Infix(Non()),", "(\"\\\\X\", (10, 13), Infix(Left()), [\"\\\\times\"], None), ], ), ( \"Modal\",", "'\\\\cdot' # | Actplus -> lookup '-+->' # | Box", "(\"SUBSET\", (8, 8), Prefix(), list(), nodes.SUBSET()), (\"UNION\", (8, 8), Prefix(),", "list(), nodes.DOMAIN()), (\"\\\\subseteq\", (5, 5), Infix(Non()), list(), nodes.Subseteq()), (\"\\\\in\", (5,", "fix ; dom = dom ; # defn = defn", "optable[s].append(op) return optable optable = _generate_optable() # pprint.pprint(optable) # let", "Times } # | Ratio -> { (lookup '/') with", "Int -> nonfix 'Int' (Some Int) # | Real ->", "; # '(/)', (13,13), Infix(Non()), [ '\\\\oslash' ] ; #", "[] ; # '..', ( 9, 9), Infix(Non()), [] ;", "Infix(Left()), list()), (\"\\\\o\", (13, 13), Infix(Left()), [\"\\\\circ\"]), (\"\\\\bigcirc\", (13, 13),", "(\"=|\", (5, 5), Infix(Non()), list()), (\"<:\", (7, 7), Infix(Non()), list()),", "'\\\\subseteq' # | Mem -> lookup '\\\\in' # | Notmem", "-> # List.iter begin # fun (name, prec, fix, als,", "begin # fun (dom, ops) -> # List.iter begin #", "to standard tlaops *) # let standard_form b = #", "'Append' (Some Append) # | Cat -> { (lookup '\\\\o')", "in ops: op = TLAOP(name, prec, fixity, dom, defn) optable.setdefault(name,", "(lookup '<') with defn = Some Lt } # |", "# fun (dom, ops) -> # List.iter begin # fun", "[ # ''', (15,15), Postfix, [], Prime ; # '~>',", "'\\\\otimes' ] ; # '\\\\uplus', ( 9,13), Infix(Left()), [] ;", "nodes.Diamond()), ], ), ( \"User\", [ (name, prec, fix, als,", "(15, 15), Postfix(), list()), (\"<\", (5, 5), Infix(Non()), list()), (\"=<\",", "Hashtbl in # let tab = H.create 109 in #", "\"Logic\", [ (\"=>\", (1, 1), Infix(Non()), list(), nodes.Implies()), (\"<=>\", (2,", "(\"\\\\notin\", (5, 5), Infix(Non()), [], nodes.Notmem()), (\"\\\\\", (8, 8), Infix(Non()),", "# | SubSeq -> nonfix 'SubSeq' (Some SubSeq) # |", "5), Infix(Non()), [] ; # '\\\\approx', ( 5, 5), Infix(Non()),", "on the file: # # <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> # import pprint from", "Modal, # List.map withdef [ # ''', (15,15), Postfix, [],", "(5, 5), Infix(Non()), list()), (\"\\\\sqsubset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubseteq\",", "; # ] ; # Sets, # [ '\\\\X', (10,13),", "(5, 5), Infix(Non()), list()), (\"::=\", (5, 5), Infix(Non()), list()), (\"(+)\",", "Some Lt } # | Gteq -> { (lookup '>=')", "-> nonfix 'Any' (Some Any) # | ToString -> nonfix", "a self.b = b # let withdef (name, prec, fix,", "with defn = Some Lt } # | Gteq ->", "Infix(Non()), [] ; # '\\\\propto', ( 5, 5), Infix(Non()), []", "'Real' (Some Real) # | Infinity -> nonfix 'Infinity' (Some", "# defn = Some Divides; # } # # |", "(\"\\\\div\", (13, 13), Infix(Non()), list()), (\"\\\\wr\", (9, 14), Infix(Non()), list()),", "2, 2), Infix(Non()), [ '\\\\leadsto' ], Leadsto ; # 'ENABLED',", "(\"\\\\supset\", (5, 5), Infix(Non()), list()), (\"\\\\supseteq\", (5, 5), Infix(Non()), list()),", "lookup ''' # | Leadsto -> lookup '~>' # |", "# | Gteq -> { (lookup '>=') with defn =", "# '(\\\\X)', (13,13), Infix(Left()), [ '\\\\otimes' ] ; # '\\\\uplus',", "string ; # prec : prec ; # fix :", "# str self.prec = prec # Prec self.fix = fixity", "else # nonfix name None # # (** Mapping from", "# '%%', (10,11), Infix(Left()), [] ; # '%', (10,11), Infix(Non()),", "assoc # and assoc = # | Left | Non", "], Neg ; # '=', ( 5, 5), Infix(Non()), [],", "int * int class Prec: def __init__(self, a, b): self.a", "; # '\\\\div', (13,13), Infix(Non()), [] ; # '\\\\wr', (", "dom self.defn = defn def __repr__(self): return ( f\"TLAOP({self.name}, {self.prec},", "(\"/\", (13, 13), Infix(Non()), list()), (\"*\", (13, 13), Infix(Left()), list()),", "[] ; # '\\\\preceq', ( 5, 5), Infix(Non()), [] ;", "'UNION' # | DOMAIN -> lookup 'DOMAIN' # | Subseteq", "nonfix 'SortSeq' (Some SortSeq) # | RandomElement -> nonfix 'RandomElement'", "pass class Nonfix(Fixity): pass class Prefix(Fixity): pass class Postfix(Fixity): pass", "None # | Irregular -> nonfix 'Irregular' None # ;;", "(Some Permutations) # | SortSeq -> nonfix 'SortSeq' (Some SortSeq)", "= Some Extend } # | Print -> nonfix 'Print'", "Infix(Non()), [] ; # '\\\\succ', ( 5, 5), Infix(Non()), []", "Neq -> lookup '#' # | Divides -> # {", "pprint from .ast import Nodes as nodes # open Builtin", "Infix(Left()), [\"\\\\land\"], nodes.Conj()), (\"\\\\/\", (3, 3), Infix(Left()), [\"\\\\lor\"], nodes.Disj()), (\"~\",", "# | SortSeq -> nonfix 'SortSeq' (Some SortSeq) # |", "= Some Remainder } # | Exp -> { (lookup", "5), Infix(Non()), [] ; # '\\\\ll', ( 5, 5), Infix(Non()),", "SUBSET -> lookup 'SUBSET' # | UNION -> lookup 'UNION'", "(10,11), Infix(Non()), [ '\\\\mod' ] ; # '##', ( 9,13),", "\"Modal\", \"User\"} # type prec = int * int class", "# | Remainder -> { (lookup '%') with defn =", "'-+->' # | Box _ -> lookup '[]' # |", "'*') with defn = Some Times } # | Ratio", "Real -> nonfix 'Real' (Some Real) # | Infinity ->", "5, 5), Infix(Non()), [] ; # '\\\\sim', ( 5, 5),", "Postfix(), list()), (\"^#\", (15, 15), Postfix(), list()), (\"<\", (5, 5),", "Range } # | Nat -> nonfix 'Nat' (Some Nat)", "def __repr__(self): return ( f\"TLAOP({self.name}, {self.prec}, \" f\"{self.fix}, {self.dom}, {self.defn})\"", "nodes.Subseteq()), (\"\\\\in\", (5, 5), Infix(Non()), list(), nodes.Mem()), (\"\\\\notin\", (5, 5),", "'SortSeq' (Some SortSeq) # | RandomElement -> nonfix 'RandomElement' (Some", "RandomElement) # | Any -> nonfix 'Any' (Some Any) #", "1, 1), Infix(Non()), [], Implies ; # '<=>', ( 2,", "Some Quotient } # | Remainder -> { (lookup '%')", "Some Exp } # | Lteq -> { (lookup '=<')", "Box true ; # '<>', ( 4,15), Prefix, [], Diamond", "with defn = Some Remainder } # | Exp ->", "| Head -> nonfix 'Head' (Some Head) # | Tail", "; # fix : fixity ; # dom : dom", "Builtin # type fixity = # | Nonfix # |", "and assoc = # | Left | Non | Right", "# '\\\\uplus', ( 9,13), Infix(Left()), [] ; # '\\\\sqcap', (", "Print -> nonfix 'Print' (Some Print) # | PrintT ->", "[], SUBSET ; # 'UNION', ( 8, 8), Prefix, [],", "| DOMAIN -> lookup 'DOMAIN' # | Subseteq -> lookup", "(4, 4), Prefix(), [\"\\\\neg\", \"\\\\lnot\"], nodes.Neg()), (\"=\", (5, 5), Infix(Non()),", "; # '\\\\simeq', ( 5, 5), Infix(Non()), [] ; #", "{ (lookup '%') with defn = Some Remainder } #", "Prec: def __init__(self, a, b): self.a = a self.b =", "[\"\\\\land\"], nodes.Conj()), (\"\\\\/\", (3, 3), Infix(Left()), [\"\\\\lor\"], nodes.Disj()), (\"~\", (4,", "# | Infix of assoc class Fixity: pass class Nonfix(Fixity):", "from .ast import Nodes as nodes # open Builtin #", "; # '|-', ( 5, 5), Infix(Non()), [] ; #", "Implies -> lookup '=>' # | Equiv -> lookup '<=>'", "# '(.)', (13,13), Infix(Left()), [ '\\\\odot' ] ; # '(/)',", "'>', ( 5, 5), Infix(Non()), [] ; # '>=', (", "13), Infix(Non()), list()), (\"|-\", (5, 5), Infix(Non()), list()), (\"|=\", (5,", "Mem ; # '\\\\notin', ( 5, 5), Infix(Non()), [], Notmem", "H.create 109 in # List.iter begin # fun (dom, ops)", "# else # nonfix name None # # (** Mapping", "; # } class TLAOP: def __init__(self, name, prec, fixity,", "Some Minus } # | Uminus -> { (lookup '-.')", "[] ; # '-|', ( 5, 5), Infix(Non()), [] ;", "Infix(Non()), [] ; # '=|', ( 5, 5), Infix(Non()), []", "list(), nodes.Subseteq()), (\"\\\\in\", (5, 5), Infix(Non()), list(), nodes.Mem()), (\"\\\\notin\", (5,", "withdef [ # ''', (15,15), Postfix, [], Prime ; #", "| BSeq -> nonfix 'BSeq' (Some BSeq) # | Append", "# | Assert -> nonfix 'Assert' (Some Assert) # |", "Infix of assoc class Fixity: pass class Nonfix(Fixity): pass class", "Conj ; # '\\\\/', ( 3, 3), Infix(Left()), [ '\\\\lor'", "Some Uminus ; name = '-' } # | Times", "], Equiv ; # '/\\\\', ( 3, 3), Infix(Left()), [", "list()), (\"\\\\simeq\", (5, 5), Infix(Non()), list()), (\"\\\\ll\", (5, 5), Infix(Non()),", "(10,13), Prefix, [ '\\\\times' ], None ] ; # Modal,", "(lookup '>=') with defn = Some Gteq } # |", "None) for name, prec, fix, als in [ (\"^\", (14,", "'-', (11,11), Infix(Left()), [] ; # '+', (10,10), Infix(Left()), []", "# | ENABLED -> lookup 'ENABLED' # | UNCHANGED ->", "-> # { # name = '?|'; # prec =", "( 5, 5), Infix(Non()), [ '/=' ], Neq ; #", "8), Infix(Non()), [\"\\\\setminus\"], nodes.Setminus()), (\"\\\\cap\", (8, 8), Infix(Left()), [\"\\\\intersect\"], nodes.Cap()),", "(\"\\\\approx\", (5, 5), Infix(Non()), list()), (\"\\\\cong\", (5, 5), Infix(Non()), list()),", "Prec self.fix = fixity # Fixity self.dom = dom self.defn", "with # | TRUE -> nonfix 'TRUE' (Some TRUE) #", "5), Infix(Non()), [ '/=' ], Neq ; # ] ;", "Assert) # | JavaTime -> nonfix 'JavaTime' (Some JavaTime) #", "Infinity) # # | Seq -> nonfix 'Seq' (Some Seq)", "; # '>', ( 5, 5), Infix(Non()), [] ; #", "( 1, 1), Infix(Non()), [], Implies ; # '<=>', (", "SelectSeq) # # | OneArg -> { (lookup ':>') with", "[ '\\\\land' ], Conj ; # '\\\\/', ( 3, 3),", "lookup '\\\\subseteq' # | Mem -> lookup '\\\\in' # |", "Prefix(Fixity): pass class Postfix(Fixity): pass class Infix(Fixity): def __init__(self, assoc):", "= Some Gteq } # | Gt -> { (lookup", "als, defn) -> # let op = { name =", "pass class Postfix(Fixity): pass class Infix(Fixity): def __init__(self, assoc): self.assoc", "Eq ; # '#', ( 5, 5), Infix(Non()), [ '/='", "'+', (10,10), Infix(Left()), [] ; # '^+', (15,15), Postfix, []", "-> { (lookup '>=') with defn = Some Gteq }", "| Cap -> lookup '\\\\cap' # | Cup -> lookup", "Unprimable -> nonfix 'Unprimable' None # | Irregular -> nonfix", "(5, 5), Infix(Non()), list()), (\"\\\\sqsupset\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupseteq\",", "6), Infix(Left()), [] ; # '!!', ( 9,13), Infix(Non()), []", "fixity, alternatives, defn in ops: op = TLAOP(name, prec, fixity,", "lookup '\\\\in' # | Notmem -> lookup '\\\\notin' # |", "'--', (11,11), Infix(Left()), [] ; # '**', (13,13), Infix(Left()), []", "( 5, 5), Infix(Non()), [] ; # '\\\\preceq', ( 5,", "(13, 13), Infix(Non()), list()), (\"^^\", (14, 14), Infix(Non()), list()), (\"@@\",", "(\"\\\\star\", (13, 13), Infix(Left()), list()), (\"\\\\o\", (13, 13), Infix(Left()), [\"\\\\circ\"]),", "# | Conj -> lookup '/\\\\' # | Disj ->", "':>') with defn = Some OneArg } # | Extend", "-> { (lookup '-') with defn = Some Minus }", "# if Hashtbl.mem optable name then # Hashtbl.find optable name", "5), Infix(Non()), [] ; # '|=', ( 5, 5), Infix(Non()),", "list()), (\"=|\", (5, 5), Infix(Non()), list()), (\"<:\", (7, 7), Infix(Non()),", "| Neq -> lookup '#' # | Divides -> #", "(lookup '=<') with defn = Some Lteq } # |", "= dom self.defn = defn def __repr__(self): return ( f\"TLAOP({self.name},", "Infix(Non()), list()), (\"\\\\doteq\", (5, 5), Infix(Non()), list()), (\"\\\\propto\", (5, 5),", "'\\\\land' ], Conj ; # '\\\\/', ( 3, 3), Infix(Left()),", "tlaops = [ ( \"Logic\", [ (\"=>\", (1, 1), Infix(Non()),", "] def _generate_tlaops(): tlaops = [ ( \"Logic\", [ (\"=>\",", "# '-+->', ( 2, 2), Infix(Non()), [], Actplus ; #", "; # '!!', ( 9,13), Infix(Non()), [] ; # '|-',", "(5, 5), Infix(Non()), list()), (\"|=\", (5, 5), Infix(Non()), list()), (\"-|\",", "(9, 13), Infix(Left()), list()), (\"\\\\div\", (13, 13), Infix(Non()), list()), (\"\\\\wr\",", "5, 5), Infix(Non()), [] ; # ] ; # ]", "( 5, 5), Infix(Non()), [] ; # '\\\\asymp', ( 5,", "Infix(Non()), [] ; # '\\\\succeq', ( 5, 5), Infix(Non()), []", "list()), (\"&&\", (13, 13), Infix(Left()), list()), (\"&\", (13, 13), Infix(Left()),", "# defn : Builtin.builtin option ; # } class TLAOP:", "= assoc # and assoc = # | Left |", "(\"~\", (4, 4), Prefix(), [\"\\\\neg\", \"\\\\lnot\"], nodes.Neg()), (\"=\", (5, 5),", "Ratio -> { (lookup '/') with defn = Some Ratio", "[] ; # '\\\\wr', ( 9,14), Infix(Non()), [] ; #", "then # Hashtbl.find optable name # else # nonfix name", "Infix(Left()), list()), (\"^+\", (15, 15), Postfix(), list()), (\"^*\", (15, 15),", "Infix(Non()), [] ; # ] ; # ] def _generate_tlaops():", "'\\\\sim', ( 5, 5), Infix(Non()), [] ; # '\\\\simeq', (", "# | Nonfix # | Prefix | Postfix # |", "'UNCHANGED', ( 4,15), Prefix, [], UNCHANGED ; # '\\\\cdot', (", "| Non | Right class Assoc: pass class Left(Assoc): pass", "| Infinity -> nonfix 'Infinity' (Some Infinity) # # |", "], ), ( \"User\", [ (name, prec, fix, als, None)", "= Logic; # defn = Some Divides; # } #", "9,13), Infix(Left()), [] ; # '++', (10,10), Infix(Left()), [] ;", "; # '*', (13,13), Infix(Left()), [] ; # '-.', (12,12),", "list()), (\"\\\\doteq\", (5, 5), Infix(Non()), list()), (\"\\\\propto\", (5, 5), Infix(Non()),", "defn = Some OneArg } # | Extend -> {", "nonfix 'Append' (Some Append) # | Cat -> { (lookup", "for dom, ops in tlaops: for name, prec, fixity, alternatives,", "# # | Prime -> lookup ''' # | StrongPrime", "[] ; # '|', (10,11), Infix(Left()), [] ; # '||',", "''' # | Leadsto -> lookup '~>' # | ENABLED", "-> nonfix 'JavaTime' (Some JavaTime) # | TLCGet -> nonfix", "[] ; # '!!', ( 9,13), Infix(Non()), [] ; #", "[ (\"'\", (15, 15), Postfix(), list(), nodes.Prime()), (\"~>\", (2, 2),", "'Tail' (Some Tail) # | SubSeq -> nonfix 'SubSeq' (Some", "'\\\\equiv' ], Equiv ; # '/\\\\', ( 3, 3), Infix(Left()),", "# Copyright (c) 2008-2013 INRIA and Microsoft Corporation # All", "] ; # '-', (11,11), Infix(Left()), [] ; # '+',", "# | Minus -> { (lookup '-') with defn =", "UNCHANGED -> lookup 'UNCHANGED' # | Cdot -> lookup '\\\\cdot'", "Infix(Left()), [] ; # '||', (10,11), Infix(Left()), [] ; #", "= (10, 11); # fix = Infix(Non()); # dom =", "fixity ; # dom : dom ; # defn :", "# '\\\\ll', ( 5, 5), Infix(Non()), [] ; # '\\\\gg',", "Infix(Left()), list()), (\"!!\", (9, 13), Infix(Non()), list()), (\"|-\", (5, 5),", "13), Infix(Left()), list()), (\"\\\\prec\", (5, 5), Infix(Non()), list()), (\"\\\\succ\", (5,", "1), Infix(Non()), [], Implies ; # '<=>', ( 2, 2),", "(13, 13), Infix(Left()), [\"\\\\otimes\"]), (\"\\\\uplus\", (9, 13), Infix(Left()), list()), (\"\\\\sqcap\",", "5), Infix(Non()), [ '<=' ; '\\\\leq' ] ; # '>',", "= _generate_optable() # pprint.pprint(optable) # let nonfix name defn =", "'\\\\bullet', (13,13), Infix(Left()), [] ; # '\\\\prec', ( 5, 5),", "list()), (\"\\\\sqsubseteq\", (5, 5), Infix(Non()), list()), (\"\\\\sqsupset\", (5, 5), Infix(Non()),", "'/=' ], Neq ; # ] ; # Sets, #", "# | Subseteq -> lookup '\\\\subseteq' # | Mem ->", "Infix(Non()), [\"/=\"], nodes.Neq()), ], ), ( \"Sets\", [ (\"SUBSET\", (8,", "7), Infix(Non()), list()), (\":>\", (7, 7), Infix(Non()), list()), (\":=\", (5,", "nonfix 'TLCSet' (Some TLCSet) # | Permutations -> nonfix 'Permutations'", "'\\\\approx', ( 5, 5), Infix(Non()), [] ; # '\\\\cong', (", "[] ; # '++', (10,10), Infix(Left()), [] ; # '--',", "defn = defn } # # let lookup name =", "5, 5), Infix(Non()), [] ; # '\\\\simeq', ( 5, 5),", "name, prec, fixity, alternatives, defn in ops: op = TLAOP(name,", "'**', (13,13), Infix(Left()), [] ; # '//', (13,13), Infix(Non()), []", "[ (\"^\", (14, 14), Infix(Non()), list()), (\"/\", (13, 13), Infix(Non()),", "nonfix 'JavaTime' (Some JavaTime) # | TLCGet -> nonfix 'TLCGet'", "} # | Gteq -> { (lookup '>=') with defn", "# | JavaTime -> nonfix 'JavaTime' (Some JavaTime) # |", "2, 2), Infix(Non()), [ '\\\\equiv' ], Equiv ; # '/\\\\',", "(\"[]\", (4, 15), Prefix(), list(), nodes.Box(True)), (\"<>\", (4, 15), Prefix(),", "Infix(Non()), list(), nodes.Implies()), (\"<=>\", (2, 2), Infix(Non()), [\"\\\\equiv\"], nodes.Equiv()), (\"/\\\\\",", "nonfix 'ToString' (Some ToString) # # | Unprimable -> nonfix", "list()), (\"$$\", (9, 13), Infix(Left()), list()), (\"$\", (9, 13), Infix(Left()),", "5, 5), Infix(Non()), [] ; # '::=', ( 5, 5),", "dom = Logic; # defn = Some Divides; # }", "; # '&', (13,13), Infix(Left()), [] ; # '$$', (", "| STRING -> nonfix 'STRING' (Some STRING) # | BOOLEAN", "'\\\\succ', ( 5, 5), Infix(Non()), [] ; # '\\\\preceq', (", "5, 5), Infix(Non()), [] ; # '(+)', (10,10), Infix(Left()), [", "self.name = name # str self.prec = prec # Prec", "; # '$$', ( 9,13), Infix(Left()), [] ; # '$',", "-> nonfix 'Len' (Some Len) # | BSeq -> nonfix", "\"\\\\lnot\"], nodes.Neg()), (\"=\", (5, 5), Infix(Non()), list(), nodes.Eq()), (\"#\", (5,", "'\\\\sqsupseteq', ( 5, 5), Infix(Non()), [] ; # '\\\\doteq', (", "-> lookup '=' # | Neq -> lookup '#' #", "5), Infix(Non()), [] ; # ] ; # ] def", "; # '-', (11,11), Infix(Left()), [] ; # '+', (10,10),", "5, 5), Infix(Non()), [] ; # '\\\\sqsupseteq', ( 5, 5),", "tlaops = _generate_tlaops() optable = dict() for dom, ops in", "-> { (lookup '@@') with defn = Some Extend }", "'TLCGet' (Some TLCGet) # | TLCSet -> nonfix 'TLCSet' (Some", "[], Diamond ; # ] ; # User, # List.map", "Prefix(), list(), nodes.ENABLED()), (\"UNCHANGED\", (4, 15), Prefix(), list(), nodes.UNCHANGED()), (\"\\\\cdot\",", "nonfix 'Assert' (Some Assert) # | JavaTime -> nonfix 'JavaTime'", "(lookup '\\\\div') with defn = Some Quotient } # |", "-> lookup '<=>' # | Conj -> lookup '/\\\\' #", "# | Permutations -> nonfix 'Permutations' (Some Permutations) # |", "{self.dom}, {self.defn})\" ) # let optable = # let module", "Infix(Left()), [ '\\\\circ' ] ; # '\\\\bigcirc', (13,13), Infix(Left()), []", "5), Infix(Non()), list()), (\"\\\\supseteq\", (5, 5), Infix(Non()), list()), (\"\\\\approx\", (5,", "# fix = Nonfix ; dom = User ; defn", "<https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> # import pprint from .ast import Nodes as nodes", "| Prefix | Postfix # | Infix of assoc class", "10), Infix(Left()), list()), (\"--\", (11, 11), Infix(Left()), list()), (\"**\", (13,", "# '^+', (15,15), Postfix, [] ; # '^*', (15,15), Postfix,", "(15,15), Postfix, [], Prime ; # '~>', ( 2, 2),", "list(), nodes.Cdot()), (\"-+->\", (2, 2), Infix(Non()), list(), nodes.WhilePlus()), (\"[]\", (4,", "5), Infix(Non()), list()), (\"\\\\cong\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubset\", (5,", "; # '<:', ( 7, 7), Infix(Non()), [] ; #", "type prec = int * int class Prec: def __init__(self,", "Infix(Non()), list()), (\"\\\\cong\", (5, 5), Infix(Non()), list()), (\"\\\\sqsubset\", (5, 5),", "5), Infix(Non()), list()), (\"\\\\asymp\", (5, 5), Infix(Non()), list()), (\"\\\\subset\", (5,", "Left | Non | Right class Assoc: pass class Left(Assoc):", "# '...', ( 9, 9), Infix(Non()), [] ; # '..',", "optable optable = _generate_optable() # pprint.pprint(optable) # let nonfix name", "| SubSeq -> nonfix 'SubSeq' (Some SubSeq) # | SelectSeq", "-> nonfix 'Permutations' (Some Permutations) # | SortSeq -> nonfix", "Postfix # | Infix of assoc class Fixity: pass class", "# '\\\\approx', ( 5, 5), Infix(Non()), [] ; # '\\\\cong',", "( # name, prec, fix, als, Some defn);; def withdef(tuple_):", "= Some Lt } # | Gteq -> { (lookup", "withdef (name, prec, fix, als, defn) = ( # name,", "Infix(Left()), [\"\\\\union\"], nodes.Cup()), (\"\\\\X\", (10, 13), Infix(Left()), [\"\\\\times\"], None), ],", "list(), nodes.Prime()), (\"~>\", (2, 2), Infix(Non()), [\"\\\\leadsto\"], nodes.LeadsTo()), (\"ENABLED\", (4,", "list()), (\">=\", (5, 5), Infix(Non()), [\"\\\\geq\"]), (\"...\", (9, 9), Infix(Non()),", "nonfix 'Any' (Some Any) # | ToString -> nonfix 'ToString'", "list()), (\"!!\", (9, 13), Infix(Non()), list()), (\"|-\", (5, 5), Infix(Non()),", "'\\\\supseteq', ( 5, 5), Infix(Non()), [] ; # '\\\\approx', (", "Infix(Left()), [] ; # '--', (11,11), Infix(Left()), [] ; #", "'=', ( 5, 5), Infix(Non()), [], Eq ; # '#',", "; # '\\\\bullet', (13,13), Infix(Left()), [] ; # '\\\\prec', (", "'TRUE' (Some TRUE) # | FALSE -> nonfix 'FALSE' (Some", "= [ ( \"Logic\", [ (\"=>\", (1, 1), Infix(Non()), list(),", "; # '\\\\', ( 8, 8), Infix(Non()), [], Setminus ;", "# | Leadsto -> lookup '~>' # | ENABLED ->", "= _generate_tlaops() optable = dict() for dom, ops in tlaops:", "Infix(Left()), [] ; # '$$', ( 9,13), Infix(Left()), [] ;", "} # | Lteq -> { (lookup '=<') with defn", "begin # fun (name, prec, fix, als, defn) -> #", "Infix(Left()), list()), (\"||\", (10, 11), Infix(Left()), list()), (\"&&\", (13, 13),", "defn);; def withdef(tuple_): name, prec, fix, als, defn = tuple_", "_generate_tlaops() optable = dict() for dom, ops in tlaops: for", "| Eq -> lookup '=' # | Neq -> lookup", "# Hashtbl.find optable name # else # nonfix name None", "User dom = {\"Logic\", \"Sets\", \"Modal\", \"User\"} # type prec", "(8, 8), Prefix(), list(), nodes.UNION()), (\"DOMAIN\", (9, 9), Prefix(), list(),", "(Some Append) # | Cat -> { (lookup '\\\\o') with", "[] ; # '&&', (13,13), Infix(Left()), [] ; # '&',", ": Builtin.builtin option ; # } class TLAOP: def __init__(self,", "# 'UNION', ( 8, 8), Prefix, [], UNION ; #", "in [ (\"^\", (14, 14), Infix(Non()), list()), (\"/\", (13, 13),", "Some Gteq } # | Gt -> { (lookup '>')", "9,13), Infix(Left()), [] ; # '$', ( 9,13), Infix(Left()), []", "OneArg -> { (lookup ':>') with defn = Some OneArg", "( 5, 5), Infix(Non()), [] ; # '\\\\succeq', ( 5,", "fix, als, defn) # let tlaops = [ # Logic,", "'=|', ( 5, 5), Infix(Non()), [] ; # '<:', (", "= User ; defn = defn } # # let", "; # '~', ( 4, 4), Prefix, [ '\\\\neg' ;", "| Right class Assoc: pass class Left(Assoc): pass class Right(Assoc):", "5, 5), Infix(Non()), [ '\\\\geq' ] ; # '...', (", "(5, 5), Infix(Non()), list()), (\"\\\\asymp\", (5, 5), Infix(Non()), list()), (\"\\\\subset\",", "# List.map withdef [ # ''', (15,15), Postfix, [], Prime", "Infix(Non()), [] ; # '\\\\ll', ( 5, 5), Infix(Non()), []", "name, prec, fix, als in [ (\"^\", (14, 14), Infix(Non()),", "; # ] ; # Sets, # List.map withdef [", "5), Infix(Non()), [] ; # '\\\\succeq', ( 5, 5), Infix(Non()),", "[ # '=>', ( 1, 1), Infix(Non()), [], Implies ;", "(13,13), Infix(Left()), [ '\\\\odot' ] ; # '(/)', (13,13), Infix(Non()),", "3, 3), Infix(Left()), [ '\\\\land' ], Conj ; # '\\\\/',", "[] ; # '\\\\prec', ( 5, 5), Infix(Non()), [] ;", "(\"\\\\subset\", (5, 5), Infix(Non()), list()), (\"\\\\supset\", (5, 5), Infix(Non()), list()),", "# '$', ( 9,13), Infix(Left()), [] ; # '??', (", "[] ; # '(+)', (10,10), Infix(Left()), [ '\\\\oplus' ] ;", "(9, 13), Infix(Left()), list()), (\"$\", (9, 13), Infix(Left()), list()), (\"??\",", "Len -> nonfix 'Len' (Some Len) # | BSeq ->", "nodes.Setminus()), (\"\\\\cap\", (8, 8), Infix(Left()), [\"\\\\intersect\"], nodes.Cap()), (\"\\\\cup\", (8, 8),", "Remainder -> { (lookup '%') with defn = Some Remainder", "[ '\\\\leadsto' ], Leadsto ; # 'ENABLED', ( 4,15), Prefix,", "4), Prefix(), [\"\\\\neg\", \"\\\\lnot\"], nodes.Neg()), (\"=\", (5, 5), Infix(Non()), list(),", "Lt -> { (lookup '<') with defn = Some Lt", "-> { (lookup '+') with defn = Some Plus }", "BOOLEAN -> nonfix 'BOOLEAN' (Some BOOLEAN) # | SUBSET ->", "BSD. # # This module is based on the file:", "[\"<=\", \"\\\\leq\"]), (\">\", (5, 5), Infix(Non()), list()), (\">=\", (5, 5),", "(7, 7), Infix(Non()), list()), (\":>\", (7, 7), Infix(Non()), list()), (\":=\",", "let withdef (name, prec, fix, als, defn) = ( #", "= # let module H = Hashtbl in # let", "# # (** Mapping from builtins to standard tlaops *)", "; # '-|', ( 5, 5), Infix(Non()), [] ; #", "] ; # '\\\\uplus', ( 9,13), Infix(Left()), [] ; #", "'~', ( 4, 4), Prefix, [ '\\\\neg' ; '\\\\lnot' ],", "Mapping from builtins to standard tlaops *) # let standard_form", "Infix(Left()), [ '\\\\lor' ], Disj ; # '~', ( 4,", "Some Extend } # | Print -> nonfix 'Print' (Some", "(\"^#\", (15, 15), Postfix(), list()), (\"<\", (5, 5), Infix(Non()), list()),", "1), Infix(Non()), list(), nodes.Implies()), (\"<=>\", (2, 2), Infix(Non()), [\"\\\\equiv\"], nodes.Equiv()),", "JavaTime -> nonfix 'JavaTime' (Some JavaTime) # | TLCGet ->", "# dom : dom ; # defn : Builtin.builtin option", "op) als # end ops # end tlaops ; #", "[] ; # '**', (13,13), Infix(Left()), [] ; # '//',", "lookup '-+->' # | Box _ -> lookup '[]' #", "__init__(self, a, b): self.a = a self.b = b #", "| Int -> nonfix 'Int' (Some Int) # | Real", "Prefix(), [\"\\\\neg\", \"\\\\lnot\"], nodes.Neg()), (\"=\", (5, 5), Infix(Non()), list(), nodes.Eq()),", "; # 'UNION', ( 8, 8), Prefix, [], UNION ;", "Prefix, [ '\\\\times' ], None ] ; # Modal, #", "(\"\\\\prec\", (5, 5), Infix(Non()), list()), (\"\\\\succ\", (5, 5), Infix(Non()), list()),", "self.prec = prec # Prec self.fix = fixity # Fixity", "standard tlaops *) # let standard_form b = # match", "| PrintT -> nonfix 'PrintT' (Some PrintT) # | Assert", "class Non(Assoc): pass # and dom = # (* primitive", "# '\\\\cup', ( 8, 8), Infix(Left()), [ '\\\\union' ], Cup", "[] ; # '-.', (12,12), Prefix, [ '-' ] ;", "| Disj -> lookup '\\\\/' # | Neg -> lookup", "Postfix, [] ; # '<', ( 5, 5), Infix(Non()), []", "3), Infix(Left()), [\"\\\\land\"], nodes.Conj()), (\"\\\\/\", (3, 3), Infix(Left()), [\"\\\\lor\"], nodes.Disj()),", "5), Infix(Non()), list()), (\"\\\\preceq\", (5, 5), Infix(Non()), list()), (\"\\\\succeq\", (5,", "dom = {\"Logic\", \"Sets\", \"Modal\", \"User\"} # type prec =", "'..', ( 9, 9), Infix(Non()), [] ; # '|', (10,11),", "Some Plus } # | Minus -> { (lookup '-')", "# '@@', ( 6, 6), Infix(Left()), [] ; # '!!',", "# List.map withdef [ # '=>', ( 1, 1), Infix(Non()),", "dom ; # defn = defn } # in #", "], ), ] return tlaops # type tlaop = {", "| Times -> { (lookup '*') with defn = Some", "with defn = Some Extend } # | Print ->", "-> { (lookup ':>') with defn = Some OneArg }", "# prec = prec ; # fix = fix ;", "[] ; # '$', ( 9,13), Infix(Left()), [] ; #", "5, 5), Infix(Non()), [] ; # '\\\\asymp', ( 5, 5),", "(\"\\\\/\", (3, 3), Infix(Left()), [\"\\\\lor\"], nodes.Disj()), (\"~\", (4, 4), Prefix(),", "(10,11), Infix(Left()), [] ; # '||', (10,11), Infix(Left()), [] ;", "[] ; # '*', (13,13), Infix(Left()), [] ; # '-.',", "(5, 5), Infix(Non()), list()), (\"<:\", (7, 7), Infix(Non()), list()), (\":>\",", "(9, 14), Infix(Non()), list()), (\"\\\\star\", (13, 13), Infix(Left()), list()), (\"\\\\o\",", "DOMAIN ; # '\\\\subseteq', ( 5, 5), Infix(Non()), [], Subseteq", "Infix(Non()), list()), (\"\\\\propto\", (5, 5), Infix(Non()), list()), ] ], ),", "list()), (\"\\\\gg\", (5, 5), Infix(Non()), list()), (\"\\\\asymp\", (5, 5), Infix(Non()),", "9,13), Infix(Left()), [] ; # '??', ( 9,13), Infix(Left()), []", "Cup -> lookup '\\\\cup' # # | Prime -> lookup", "9), Prefix(), list(), nodes.DOMAIN()), (\"\\\\subseteq\", (5, 5), Infix(Non()), list(), nodes.Subseteq()),", "2), Infix(Non()), [\"\\\\leadsto\"], nodes.LeadsTo()), (\"ENABLED\", (4, 15), Prefix(), list(), nodes.ENABLED()),", "list()), (\"\\\\subset\", (5, 5), Infix(Non()), list()), (\"\\\\supset\", (5, 5), Infix(Non()),", "(name, prec, fix, als, defn) = ( # name, prec,", "-> nonfix 'Unprimable' None # | Irregular -> nonfix 'Irregular'", "# and assoc = # | Left | Non |", "(13, 13), Infix(Left()), list()), (\"-.\", (12, 12), Prefix(), [\"-\"]), (\"-\",", "Infix(Left()), [] ; # '\\\\bullet', (13,13), Infix(Left()), [] ; #", "primitive operators *) # | Logic | Sets | Modal", "(c) 2008-2013 INRIA and Microsoft Corporation # All rights reserved.", "[], UNCHANGED ; # '\\\\cdot', ( 5,14), Infix(Left()), [], Cdot", "[] ; # '\\\\div', (13,13), Infix(Non()), [] ; # '\\\\wr',", "[] ; # '\\\\sqcap', ( 9,13), Infix(Left()), [] ; #", "SortSeq -> nonfix 'SortSeq' (Some SortSeq) # | RandomElement ->", "'\\\\sqsubset', ( 5, 5), Infix(Non()), [] ; # '\\\\sqsubseteq', (", "( 5, 5), Infix(Non()), [] ; # '::=', ( 5,", "-> nonfix 'Tail' (Some Tail) # | SubSeq -> nonfix", "( 9,13), Infix(Left()), [] ; # '??', ( 9,13), Infix(Left()),", "(Some Nat) # | Int -> nonfix 'Int' (Some Int)", "5), Infix(Non()), list(), nodes.Mem()), (\"\\\\notin\", (5, 5), Infix(Non()), [], nodes.Notmem()),", "__repr__(self): return ( f\"TLAOP({self.name}, {self.prec}, \" f\"{self.fix}, {self.dom}, {self.defn})\" )", "(13, 13), Infix(Left()), [\"\\\\circ\"]), (\"\\\\bigcirc\", (13, 13), Infix(Left()), list()), (\"\\\\bullet\",", "let op = { name = name ; # prec", "name op ; # List.iter (fun s -> H.add tab", "109 in # List.iter begin # fun (dom, ops) ->", "(11, 11), Infix(Left()), list()), (\"+\", (10, 10), Infix(Left()), list()), (\"^+\",", "# fix = Infix(Non()); # dom = Logic; # defn", "Infix(Non()), list(), nodes.WhilePlus()), (\"[]\", (4, 15), Prefix(), list(), nodes.Box(True)), (\"<>\",", "(\"+\", (10, 10), Infix(Left()), list()), (\"^+\", (15, 15), Postfix(), list()),", "(\"\\\\supseteq\", (5, 5), Infix(Non()), list()), (\"\\\\approx\", (5, 5), Infix(Non()), list()),", "# # | Plus -> { (lookup '+') with defn", "; # ':>', ( 7, 7), Infix(Non()), [] ; #", "# '\\\\preceq', ( 5, 5), Infix(Non()), [] ; # '\\\\succeq',", "list(), nodes.Diamond()), ], ), ( \"User\", [ (name, prec, fix,", "], Leadsto ; # 'ENABLED', ( 4,15), Prefix, [], ENABLED", "Nat) # | Int -> nonfix 'Int' (Some Int) #", "Append) # | Cat -> { (lookup '\\\\o') with defn", "| Actplus -> lookup '-+->' # | Box _ ->", "} # | Lt -> { (lookup '<') with defn", "prec : prec ; # fix : fixity ; #", "# | Prime -> lookup ''' # | StrongPrime ->", "# '*', (13,13), Infix(Left()), [] ; # '-.', (12,12), Prefix,", "of Technology # Copyright (c) 2008-2013 INRIA and Microsoft Corporation", "# end ops # end tlaops ; # tab def", "(Some ToString) # # | Unprimable -> nonfix 'Unprimable' None", "(\"<=>\", (2, 2), Infix(Non()), [\"\\\\equiv\"], nodes.Equiv()), (\"/\\\\\", (3, 3), Infix(Left()),", "(\"**\", (13, 13), Infix(Left()), list()), (\"//\", (13, 13), Infix(Non()), list()),", "| StrongPrime -> lookup ''' # | Leadsto -> lookup", "# '..', ( 9, 9), Infix(Non()), [] ; # '|',", "Equiv ; # '/\\\\', ( 3, 3), Infix(Left()), [ '\\\\land'", "= Some Cat } # | Head -> nonfix 'Head'", "; # ] ; # User, # List.map (fun (name,", "Left(Assoc): pass class Right(Assoc): pass class Non(Assoc): pass # and", "( 5, 5), Infix(Non()), [ '\\\\geq' ] ; # '...',", "Prefix(), list(), nodes.Box(True)), (\"<>\", (4, 15), Prefix(), list(), nodes.Diamond()), ],", "# 'DOMAIN', ( 9, 9), Prefix, [], DOMAIN ; #", "Infix(Non()), [ '\\\\oslash' ] ; # '(\\\\X)', (13,13), Infix(Left()), [", "Infix(Left()), [] ; # '&&', (13,13), Infix(Left()), [] ; #", "# | Diamond -> lookup '<>' # # | Plus", "Infix(Non()), [] ; # '\\\\doteq', ( 5, 5), Infix(Non()), []", "= fixity # Fixity self.dom = dom self.defn = defn", "List.iter (fun s -> H.add tab s op) als #", "] ], ), ] return tlaops # type tlaop =", "= Nonfix ; dom = User ; defn = defn", "prec = (10, 11); # fix = Infix(Non()); # dom", "assoc = # | Left | Non | Right class", "# ':>', ( 7, 7), Infix(Non()), [] ; # ':=',", "( 5, 5), Infix(Non()), [] ; # '\\\\ll', ( 5,", "(13, 13), Infix(Left()), list()), (\"&\", (13, 13), Infix(Left()), list()), (\"$$\",", "] ; # Sets, # [ '\\\\X', (10,13), Prefix, [", "Ratio } # | Quotient -> { (lookup '\\\\div') with", "Infix(Left()), list()), (\"\\\\sqcup\", (9, 13), Infix(Left()), list()), (\"\\\\div\", (13, 13),", "-> nonfix 'TRUE' (Some TRUE) # | FALSE -> nonfix", "{self.prec}, \" f\"{self.fix}, {self.dom}, {self.defn})\" ) # let optable =", "5, 5), Infix(Non()), [] ; # '\\\\supseteq', ( 5, 5),", "'|-', ( 5, 5), Infix(Non()), [] ; # '|=', (", "(\"<\", (5, 5), Infix(Non()), list()), (\"=<\", (5, 5), Infix(Non()), [\"<=\",", "Infix(Left()), [ '\\\\ominus' ] ; # '(.)', (13,13), Infix(Left()), [", "# <https://github.com/tlaplus/tlapm/blob/main/src/optable.ml> # import pprint from .ast import Nodes as", "Infix(Non()), list()), (\"=<\", (5, 5), Infix(Non()), [\"<=\", \"\\\\leq\"]), (\">\", (5,", "= Some Plus } # | Minus -> { (lookup", "'(-)', (11,11), Infix(Left()), [ '\\\\ominus' ] ; # '(.)', (13,13),", "; # '##', ( 9,13), Infix(Left()), [] ; # '++',", "(\"UNCHANGED\", (4, 15), Prefix(), list(), nodes.UNCHANGED()), (\"\\\\cdot\", (5, 14), Infix(Left()),", "Prefix, [ '-' ] ; # '-', (11,11), Infix(Left()), []", "# '<:', ( 7, 7), Infix(Non()), [] ; # ':>',", "-> { (lookup '^') with defn = Some Exp }", "nonfix 'Tail' (Some Tail) # | SubSeq -> nonfix 'SubSeq'", "# '||', (10,11), Infix(Left()), [] ; # '&&', (13,13), Infix(Left()),", "'SelectSeq' (Some SelectSeq) # # | OneArg -> { (lookup", "List.iter begin # fun (dom, ops) -> # List.iter begin", "with defn = Some Uminus ; name = '-' }", "[], nodes.Notmem()), (\"\\\\\", (8, 8), Infix(Non()), [\"\\\\setminus\"], nodes.Setminus()), (\"\\\\cap\", (8,", "[] ; # '^#', (15,15), Postfix, [] ; # '<',", "# | Ratio -> { (lookup '/') with defn =", "Right class Assoc: pass class Left(Assoc): pass class Right(Assoc): pass", "] ; # '(\\\\X)', (13,13), Infix(Left()), [ '\\\\otimes' ] ;", "ENABLED -> lookup 'ENABLED' # | UNCHANGED -> lookup 'UNCHANGED'", "[], UNION ; # 'DOMAIN', ( 9, 9), Prefix, [],", "# '\\\\', ( 8, 8), Infix(Non()), [], Setminus ; #", "} # in # H.add tab name op ; #", "(\"\\\\succeq\", (5, 5), Infix(Non()), list()), (\"\\\\sim\", (5, 5), Infix(Non()), list()),", "# (** Mapping from builtins to standard tlaops *) #", "Infix(Non()), [] ; # '*', (13,13), Infix(Left()), [] ; #", "( 2, 2), Infix(Non()), [ '\\\\leadsto' ], Leadsto ; #", "( 8, 8), Prefix, [], SUBSET ; # 'UNION', (", "-> lookup 'UNION' # | DOMAIN -> lookup 'DOMAIN' #", "Cdot -> lookup '\\\\cdot' # | Actplus -> lookup '-+->'", "Postfix, [] ; # '^#', (15,15), Postfix, [] ; #", "# | Gt -> { (lookup '>') with defn =", "] ; # Sets, # List.map withdef [ # 'SUBSET',", "# 'UNCHANGED', ( 4,15), Prefix, [], UNCHANGED ; # '\\\\cdot',", "'\\\\leq' ] ; # '>', ( 5, 5), Infix(Non()), []", "(5, 5), Infix(Non()), list()), (\"\\\\preceq\", (5, 5), Infix(Non()), list()), (\"\\\\succeq\",", "Infix(Non()), [] ; # '\\\\star', (13,13), Infix(Left()), [] ; #", "'\\\\subset', ( 5, 5), Infix(Non()), [] ; # '\\\\supset', (", "# | Head -> nonfix 'Head' (Some Head) # |", "# '\\\\notin', ( 5, 5), Infix(Non()), [], Notmem ; #", "TRUE) # | FALSE -> nonfix 'FALSE' (Some FALSE) #", "; dom = dom ; # defn = defn }", "| RandomElement -> nonfix 'RandomElement' (Some RandomElement) # | Any", "(Some Print) # | PrintT -> nonfix 'PrintT' (Some PrintT)", "Postfix(Fixity): pass class Infix(Fixity): def __init__(self, assoc): self.assoc = assoc", "Cap ; # '\\\\cup', ( 8, 8), Infix(Left()), [ '\\\\union'", "pass # and dom = # (* primitive operators *)", "Prefix(), list(), nodes.SUBSET()), (\"UNION\", (8, 8), Prefix(), list(), nodes.UNION()), (\"DOMAIN\",", "prec ; # fix : fixity ; # dom :", "( 9,13), Infix(Non()), [] ; # '|-', ( 5, 5)," ]
[ "tree index item. @return: \"\"\" function = index.data(role=DIE.UI.Function_Role) if function", "= item_func_context_list[0] item_function.appendRow(item_func_context_list) occurrence_num = 0 for function_context in function_context_list:", "call\") model.setHorizontalHeaderItem(7, item_header) ### Return Value Icon Header item_header =", "use_qt5: _QSortFilterProxyModel = QtCore.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchRecursive _MatchExactly = QtCore.Qt.MatchExactly", "is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_value_item is not None: self.context_menu_param = is_value_item", "root_item = self.functionModel.item(0, 0) rows = root_item.rowCount() thread_id = self.thread_id_combo.currentText()", "% (function_context.calling_func_name, hex(call_offset)) else: func_ea_txt = \"[%s]:%s\" % (function_context.calling_func_name, hex(function_context.calling_ea))", "function context in FunctionView: %s\\n\" % ex) return False ###############################################################################################", "a single item @param item: module item \"\"\" try: item.setBackground(QtGui.QColor('yellow'))", "its members to the module self._add_model_container_members(this_row_item, call_value, ret_value, nest_depth) def", "= item if not parent.hasChildren(): self.highlight_item(parent) return row = item.row()", "find_function(self, function_name): \"\"\" Find and highlight a function in current", "and function.lib_name is not None: self.bp_handler.add_module_exception(function.lib_name) return # @QtCore.Slot(str) def", "= self.die_db.get_function_context_list(function) for func_context in func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return # @QtCore.Slot(str)", "data value can be \"a123aa5672aa11112a\") for threads 123, 5672 and", "%s\\n\" % ex) return False ############################################################################################### # Slots. # @QtCore.Slot(QtCore.QModelIndex)", "self.functionModel.hasIndex(row, column, parent.index()): cur_index = self.functionModel.index(row, column, parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index", "= QtGui.QStandardItem(\"Return Value\") item_header.setToolTip(\"Argument`s value on function return\") model.setHorizontalHeaderItem(9, item_header)", "parent, option, index): parsed_val_list = index.data(role=DIE.UI.ParsedValuesRole) # Show combobox only", "tree item for a function name (level-0) @param function: dbFunction", "100) self.functionTreeView.setColumnWidth(6, 20) self.functionTreeView.setColumnWidth(7, 450) self.functionTreeView.setColumnWidth(8, 20) self.functionTreeView.setColumnWidth(9, 450) #", "items, only occurrences of it. if not index.data().startswith(\"Occur\"): continue item", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def", "self.die_db.count_function_occurs(function, int(thread_id)) func_count_item = root_item.child(row, 1) func_count_item.setText(str(count)) ############################################################################################### # Highlight", "idaapi.msg(\"Error while highlighting item row: %s\\n\" % ex) def clear_highlights(self):", "current_ret_values = self.die_db.get_return_values(function_context) curret_ret_arg_value = self.die_db.get_return_arg_value(function_context) for arg_index in xrange(0,", "item_header = QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New Function\") model.setHorizontalHeaderItem(3, item_header) ### Indirect Header", "@param thread_id: thread id to normalize @return: a normalized string", "# Color library function # for tmp_item in item_list_func: #", "widget self.parent = form_to_widget(form) self.functionModel = QtGui.QStandardItemModel() self.functionTreeView = QtWidgets.QTreeView()", "call_graph: (from_address, to_address) = ctxt_node graph.add_edge(from_address, to_address) function_name = self.die_db.get_function_name(function_context.function)", "self.value_view = None self.bp_handler = None self.die_icons = None self.die_db", "selected thread_id \"\"\" root_item = self.functionModel.item(0, 0) rows = root_item.rowCount()", "_make_function_ea_item(self, function_context): \"\"\" Build a tree item for a function_ea", "DIE.Lib.DIEDb.dbFunction_Context): if function_context is not None: raise ValueError(\"Wrong value sent", "Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6, item_header) ### Call Value", "self.die_db.get_return_arg_value(function_context) for arg_index in xrange(0, function.arg_num): try: current_arg = self.die_db.get_function_arg(function,", "self.functionTreeView.setColumnWidth(7, 450) self.functionTreeView.setColumnWidth(8, 20) self.functionTreeView.setColumnWidth(9, 450) # Context menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)", "if not parent.hasChildren(): self.highlight_item(parent) return row = item.row() column_num =", "horizontal header data @param model: the QStandardItemModel which headers should", "= \" \" * nest_depth arg_ident_type = arg_ident + arg_type", "highlights: %s\\n\" % ex) ############################################################################################### # Find Items. def find_function(self,", "a reference if call_value is not None: if call_value.reference_flink is", "# If call value is a container type (struct\\union\\etc) if", "else: count = self.die_db.count_function_occurs(function, int(thread_id)) func_count_item = root_item.child(row, 1) func_count_item.setText(str(count))", "value found in thread_id argument will be delimited by the", "= TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0, 200) self.functionTreeView.setColumnWidth(1, 20)", "else: item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if ret_value.derref_depth ==", "None and ret_value.type == call_value.type: if ret_value.nested_values is not None:", "a list of function contexts @param context_list: list of function", "if calling_function_start is not None: call_offset = function_context.calling_ea - calling_function_start", "self).__init__() self.value_view = None self.bp_handler = None self.die_icons = None", "role=DIE.UI.ThreadId_Role) elif not current_thread_id in thread_data: item.setData(thread_data + current_thread_id, role=DIE.UI.ThreadId_Role)", "is not None: parsed_val_data = \"\" item_parsed_val_ret = QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count,", "# If return value is a container type (and call", "and set the count according to currently selected thread_id @param", "= QtWidgets.QAction(\"Show Call-Graph\", self.functionTreeView, triggered=lambda: self.on_show_callgraph(self.context_menu_param)) # Function ContextMenu self.function_context_menu", "import networkx as nx from awesome.context import ignored import sark", "layout.addWidget(self.functionTreeView) self.parent.setLayout(layout) def OnClose(self, form): idaapi.msg(\"Closed\\n\") def isVisible(self): \"\"\" Is", "nest_depth: @return: \"\"\" # If call debug value is a", "parent, call_value, ret_value, arg_name, arg_type, nest_depth=0): \"\"\" Add a debug", "import DIE.UI.ValueViewEx import DIE.UI.ParserView import DIE.UI.BPView import DIE.Lib.IDAConnector import DIE.Lib.DIEDb", "is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: # If more the", "Call number header item_header = QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number of calls preformed", "self.ea_context_menu = QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph) # Argument value ContextMenu self.value_context_menu", "name (for a non-executed function) @type: String @param function_name: Function", "(function_context.calling_func_name, hex(call_offset)) else: func_ea_txt = \"[%s]:%s\" % (function_context.calling_func_name, hex(function_context.calling_ea)) item_func_context_ea", "self.die_db.get_functions(): item_list_func = self._make_function_item(function) if function.is_lib_func: # Color library function", "len(parsed_vals) > 1: # If more the 1 item, show", "self.function_toolbar.addWidget(self.thread_id_combo) # Grid layout = QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView) self.parent.setLayout(layout) def", "self.functionTreeView.setModel(threadProxyModel) def on_valueview_button(self): value_view = DIE.UI.ValueViewEx.get_view() value_view.Show() def on_pluginsview_button(self): plugins_view", "None: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs': %s. excpected dbFunction_Context\"", "> 0: continue item_func_context_list = self._make_function_ea_item(function_context_list[0]) item_func_context_ea = item_func_context_list[0] item_function.appendRow(item_func_context_list)", "ctxt_node graph.add_edge(from_address, to_address) function_name = self.die_db.get_function_name(function_context.function) viewer = sark.ui.NXGraph(graph, \"Callgraph", "if not call_graph: idaapi.msg(\"No Execution Graph\") return for ctxt_node in", "occurrence \"\"\" func_occur_txt = \"Occur %s\" % str(occur_num) item_func_context =", "matched_items: if not index.isValid(): continue # Do not highlight \"ea", "= item.data(role=DIE.UI.ThreadId_Role) if thread_data is None: item.setData(current_thread_id, role=DIE.UI.ThreadId_Role) elif not", "for func_ea in idautils.Functions(): # func_name = DIE.Lib.IDAConnector.get_function_name(func_ea) # #", "find_context_list(self, context_list): \"\"\" Find and highlight a list of function", "from the return debug value. if ret_value is not None", "item_header.setToolTip(\"Argument Name\") model.setHorizontalHeaderItem(5, item_header) ### Call Value Icon Header item_header", "occurrence_num += 1 # Add non-executed function to the model", "delimited by the _make_thread_id_data function (e.g: thread_id 123 will become", "item_func_is_new.setEditable(False) if function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v) item_list = [item_func_context_ea, QtGui.QStandardItem(), item_func_is_indirect, item_func_is_new,", "item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count] return item_list def _make_function_ea_item(self,", "item if not parent.hasChildren(): self.highlight_item(parent) return row = item.row() column_num", "function contexts (of type dbFunction_Context) \"\"\" try: self.clear_highlights() root_index =", "item_header = QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function Name\") model.setHorizontalHeaderItem(0, item_header) ### Call number", "Clear all highlighted items @return: \"\"\" try: self.functionTreeView.collapseAll() for persistent_index", "and ea is not idc.BADADDR: idc.Jump(ea) return True func_context =", "line_txt = \"%d, %s, %s\" % (parsed_val.score, parsed_val.data, parsed_val.description) lines.append(line_txt)", "root\" items, only occurrences of it. if not index.data().startswith(\"Occur\"): continue", "self.context_menu_param = is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) # @QtCore.Slot(str) def on_exclude_func(self, function): if", "is not None: raise ValueError(\"Wrong value sent to 'on_exclude_ea': %s.", "is None: parent = item if not parent.hasChildren(): self.highlight_item(parent) return", "item_parsed_val_call = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1:", "0, this_row_item) parent.setChild(arg_count, 1, QtGui.QStandardItem()) parent.setChild(arg_count, 2, QtGui.QStandardItem()) parent.setChild(arg_count, 3,", "@param occur_num: occurrence number @return: QStandradItemModel item for the function", "# @QtCore.Slot(str) def on_show_callgraph(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if", "thread_id): \"\"\" Delimit thread_id data in order to support filtering\\sorting", "occurrence_num = 0 for function_context in function_context_list: item_func_context_list = self._make_func_occur_item(function_context,", "to 'on_exclude_func_adrs'\") if function.is_lib_func and function.lib_name is not None: self.bp_handler.add_module_exception(function.lib_name)", "function_context): \"\"\" Build a tree item for a function_ea node", "If return debug value is a reference (and call value", "1, QtGui.QStandardItem()) parent.setChild(arg_count, 2, QtGui.QStandardItem()) parent.setChild(arg_count, 3, QtGui.QStandardItem()) parent.setChild(arg_count, 4,", "model horizontal header data @param model: the QStandardItemModel which headers", "triggered=lambda: self.on_value_detail(self.context_menu_param)) action_show_callgraph = QtWidgets.QAction(\"Show Call-Graph\", self.functionTreeView, triggered=lambda: self.on_show_callgraph(self.context_menu_param)) #", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_func_occur_item(self, function_context, occur_num): \"\"\"", "except IndexError: break ret_arg = self.die_db.get_function_arg(function, -1) if ret_arg is", "if ret_value.reference_flink is not None and not ret_value.is_definitely_parsed: ref_val =", "or ret_value.reference_flink is not None: parsed_val_data = \"\" item_parsed_val_ret =", "QtWidgets.QStyledItemDelegate.__init__(self, parent) self.parent = parent def createEditor(self, parent, option, index):", "not None: self.context_menu_param = is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_value_item is not", "this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role) # Inherit thread data from parent # Set", "Call Value if call_value is not None: parsed_vals = self.die_db.get_parsed_values(call_value)", "sent to 'on_exclude_ea': %s. excpected dbFunction_Context\" % function_context.__class__) else: raise", "threads 123, 5672 and 111112 @param item: the model item", "module self._add_model_container_members(this_row_item, call_value, ret_value, nest_depth) def _add_model_arg_ref(self, parent, call_value, ret_value,", "Exception as ex: idaapi.msg(\"Error while looking up function context in", "ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name) return # @QtCore.Slot(str) def", "def on_thread_combobox_change(self, thread_id): self.reset_function_count(thread_id) # reset function count according to", "# if function.is_lib_func: # Color library function # for tmp_item", "None self.die_icons = None self.die_db = None self.highligthed_items = []", "reference values, add them to the module self._add_model_arg_ref(this_row_item, call_value, ret_value,", "in function_context_list: item_func_context_list = self._make_func_occur_item(function_context, occurrence_num) item_func_context = item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list)", "dbFunction_Context) \"\"\" try: self.clear_highlights() root_index = self.functionModel.index(0, 0) if not", "Value Header item_header = QtGui.QStandardItem(\"Return Value\") item_header.setToolTip(\"Argument`s value on function", "item_header = QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument Type\") model.setHorizontalHeaderItem(4, item_header) ### New Function", "data from parent # Set indentation for argument types (for", "= arg_ident + arg_type item_parsed_val_flag_call = QtGui.QStandardItem() item_parsed_val_call = QtGui.QStandardItem()", "Exception as ex: idaapi.msg(\"Error while highlighting item row: %s\\n\" %", "import DIE.Lib.BpHandler import sark.ui class FunctionView(PluginForm): \"\"\" DIE Function View", "parent = item if not parent.hasChildren(): self.highlight_item(parent) return row =", "% function_context.__class__) else: raise ValueError(\"Wrong value sent to 'on_show_callgraph'\") graph", "self.functionTreeView, triggered=lambda: self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs = QtWidgets.QAction(\"Exclude All Function Calls\", self.functionTreeView,", "self.reset_function_count(thread_id) # reset function count according to currently selected thread", "not None and len(parsed_val_list) > 1: lines = [] for", "is not None and len(parsed_val_list) > 1: lines = []", "%ex) def highlight_item_row(self, item): \"\"\" highlight the entire row containing", "len(parsed_vals) > 0: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call = QtGui.QStandardItem(best_val.data)", "item_func_is_new.setIcon(self.die_icons.icon_v) item_list = [item_func_context_ea, QtGui.QStandardItem(), item_func_is_indirect, item_func_is_new, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "ref_val.name, ref_val.type, nest_depth+1) def _add_model_container_members(self, parent, call_value, ret_value, nest_depth=0): \"\"\"", "None: if ret_value.reference_flink is not None and not ret_value.is_definitely_parsed: ref_val", "occurrence counter occurrence_num += 1 # Add non-executed function to", "not None: self.context_menu_param = is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_func_context_item is not", "for arg_index in xrange(0, function.arg_num): try: current_arg = self.die_db.get_function_arg(function, arg_index)", "a reference value to module @param parent: @param call_value: @param", "nested_val_ret, nested_val_ret.name, nested_val_ret.type, nest_depth+1) def reset_function_count(self, thread_id=None): \"\"\" Reset the", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_func_occur_item(self, function_context,", "editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False) # Singelton function_view = None def initialize():", "as ex: idaapi.msg(\"Error while highlighting item row: %s\\n\" % ex)", "def on_exclude_library(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is", "return combo_box def setEditorData(self, editor, index): editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False) #", "= QtGui.QStandardItem() item_parsed_val_call = QtGui.QStandardItem() item_parsed_val_flag_ret = QtGui.QStandardItem() item_parsed_val_ret =", "item_func_is_new = QtGui.QStandardItem() item_func_is_new.setEditable(False) if function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v) item_list = [item_func_context_ea,", "Call-Graph\", self.functionTreeView, triggered=lambda: self.on_show_callgraph(self.context_menu_param)) # Function ContextMenu self.function_context_menu = QtWidgets.QMenu(self.functionTreeView)", "not ret_value.is_definitely_parsed: ref_val = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, None, ref_val, ref_val.name, ref_val.type,", "None self.highligthed_items = [] def Show(self): # Reset highlighted items", "QtWidgets.QAction(\"Exclude Library\", self.functionTreeView, triggered=lambda: self.on_exclude_library(self.context_menu_param)) action_value_detail = QtWidgets.QAction(\"Inspect Value Details\",", "the model item to add the data to @param thread_id:", "role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if call_value.derref_depth == 0: parsed_val_data", "highlighted items self.highligthed_items = [] return PluginForm.Show(self, \"Function View\", options=PluginForm.FORM_PERSIST)", "function return\") model.setHorizontalHeaderItem(9, item_header) def _make_thread_id_data(self, thread_id): \"\"\" Delimit thread_id", "0) rows = root_item.rowCount() thread_id = self.thread_id_combo.currentText() for row in", "@param context_list: list of function contexts (of type dbFunction_Context) \"\"\"", "multi-thread data items @param thread_id: thread id to normalize @return:", "item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role) item_list", "in xrange(0, function.arg_num): try: current_arg = self.die_db.get_function_arg(function, arg_index) self._add_model_arg_value(item_func_context, current_call_values[arg_index],", "object \"\"\" model.clear() # Clear the model root_node = model.invisibleRootItem()", "= DIE.Lib.DIEDb.get_db() # Get parent widget self.parent = form_to_widget(form) self.functionModel", "self.bp_handler = DIE.Lib.BpHandler.get_bp_handler() self.die_icons = DIE.UI.Die_Icons.get_die_icons() self.die_db = DIE.Lib.DIEDb.get_db() #", "add the data to @param thread_id: thread_id number @return: True", "value to module @param parent: @param call_value: @param ret_value: @param", "parent.setChild(arg_count, 5, QtGui.QStandardItem(arg_name)) parent.setChild(arg_count, 6, item_parsed_val_flag_call) parent.setChild(arg_count, 7, item_parsed_val_call) parent.setChild(arg_count,", "is not None: if ret_value.reference_flink is not None and not", "item \"\"\" try: item.setBackground(QtGui.QColor('yellow')) cur_font = item.font() cur_font.setBold(True) item.setFont(cur_font) except", "clear_highlights(self): \"\"\" Clear all highlighted items @return: \"\"\" try: self.functionTreeView.collapseAll()", "= is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_func_context_item is not None: self.context_menu_param =", "not self.value_view.isVisible(): self.value_view.Show() self.value_view.find_value(value) return def on_thread_combobox_change(self, thread_id): self.reset_function_count(thread_id) #", "= QtGui.QStandardItem(\"0\") item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count] return item_list", "reference if call_value is not None: if call_value.reference_flink is not", "\"%d, %s, %s\" % (parsed_val.score, parsed_val.data, parsed_val.description) lines.append(line_txt) combo_box =", "call_value, ret_value, nest_depth=0): \"\"\" Add container members to module @param", "debug value is a reference (and call value is not)", "ThreadId_Role \"\"\" return \"t%st\" % str(thread_id) def _insert_thread_data(self, item, thread_id):", "function is not None: ea = function.function_start if function.is_lib_func: ea", "OnCreate(self, form): \"\"\" Called when the plugin form is created", "occur_num: occurrence number @return: QStandradItemModel item for the function occurrence", "# @QtCore.Slot(str) def on_exclude_func(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if", "debug value. if ret_value is not None and ret_value.type ==", "def OnClose(self, form): idaapi.msg(\"Closed\\n\") def isVisible(self): \"\"\" Is functionview visible", "for tmp_item in item_list_func: # tmp_item.setBackground(QtGui.QColor(255, 0, 0, 127)) #", "was successfully added to item, otherwise False \"\"\" try: current_thread_id", "in xrange(0, rows): cur_item = root_item.child(row, 0) function = cur_item.data(role=DIE.UI.Function_Role)", "a normalized string of the thread_id to be used sa", "\"All Threads\": if not self.functionTreeView.model() is self.functionModel: self.functionTreeView.setModel(self.functionModel) return hidden_threads", "DIE.Lib.DIEDb import DIE.Lib.BpHandler import sark.ui class FunctionView(PluginForm): \"\"\" DIE Function", "self.die_db is None: return # Add db functions to the", "DIE.UI.ValueViewEx.get_view() value_view.Show() def on_pluginsview_button(self): plugins_view = DIE.UI.ParserView.get_view() plugins_view.Show() def on_bpview_button(self):", "None # Parameter to be passed to context menu slots", "self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent, nested_val_call, nested_val_ret, nested_val_call.name, nested_val_call.type, nest_depth+1) # If return", "tmp_item in item_list_func: # tmp_item.setBackground(QtGui.QColor(255, 0, 0, 127)) # #", "# @QtCore.Slot(QtCore.QPoint) def onCustomContextMenu(self, point): index = self.functionTreeView.indexAt(point) is_function_item =", "is a container object, Add its members to the module", "model.invisibleRootItem() self._make_model_headers(model) if self.die_db is None: return # Add db", "def createEditor(self, parent, option, index): parsed_val_list = index.data(role=DIE.UI.ParsedValuesRole) # Show", "return debug value is a reference (and call value is", "is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: # If more the", "ex) return False ############################################################################################### # Slots. # @QtCore.Slot(QtCore.QModelIndex) def itemDoubleClickSlot(self,", "occurrence (level-2) @param function_context: a dbFunction_Context object @param occur_num: occurrence", "Execution Graph\") return for ctxt_node in call_graph: (from_address, to_address) =", "[item_function, item_function_count] return item_list def _make_function_ea_item(self, function_context): \"\"\" Build a", "\"ea root\" items, only occurrences of it. if not index.data().startswith(\"Occur\"):", "the model horizontal header data @param model: the QStandardItemModel which", "ComboBox threads = [] if self.die_db is not None: threads", "object @return: QStandradItemModel item for the function \"\"\" function_txt =", "two or more items. if parsed_val_list is not None and", "value is a container type (and call value is not)", "import DIE.Lib.IDAConnector import DIE.Lib.DIEDb import DIE.Lib.BpHandler import sark.ui class FunctionView(PluginForm):", "= DIE.UI.ValueViewEx.get_view() value_view.Show() def on_pluginsview_button(self): plugins_view = DIE.UI.ParserView.get_view() plugins_view.Show() def", "thread_id data into a model item. The value found in", "initialize(): global function_view function_view = FunctionView() def get_view(): return function_view", "this_row_item) parent.setChild(arg_count, 1, QtGui.QStandardItem()) parent.setChild(arg_count, 2, QtGui.QStandardItem()) parent.setChild(arg_count, 3, QtGui.QStandardItem())", "self.die_db.get_call_graph_to(function_context) if not call_graph: idaapi.msg(\"No Execution Graph\") return for ctxt_node", "0 for function_context in function_context_list: item_func_context_list = self._make_func_occur_item(function_context, occurrence_num) item_func_context", "= QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: #", "types (for nested values) arg_ident = \" \" * nest_depth", "thread if thread_id == \"All Threads\": if not self.functionTreeView.model() is", "to 'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name) return # @QtCore.Slot(str) def on_exclude_func_adrs(self, function): if", "\"\"\" Find and highlight a list of function contexts @param", "not None and call_value.nested_values is not None: if call_value.nested_values: for", "reference from the return debug value. if ret_value is not", "menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) # Actions self.context_menu_param = None # Parameter", "for index in matched_items: if not index.isValid(): continue # Do", "QtGui.QStandardItem()) parent.setChild(arg_count, 2, QtGui.QStandardItem()) parent.setChild(arg_count, 3, QtGui.QStandardItem()) parent.setChild(arg_count, 4, QtGui.QStandardItem(arg_ident_type))", "current_arg.type) except IndexError: break ret_arg = self.die_db.get_function_arg(function, -1) if ret_arg", "ret_value: @param arg_name: @param arg_type: @return: \"\"\" arg_count = parent.rowCount()", "value if ret_value is not None: parsed_vals = self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals,", "QtGui.QStandardItem(arg_name)) parent.setChild(arg_count, 6, item_parsed_val_flag_call) parent.setChild(arg_count, 7, item_parsed_val_call) parent.setChild(arg_count, 8, item_parsed_val_flag_ret)", "Add a reference value to module @param parent: @param call_value:", "function.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") func_context_list =", "Library\", self.functionTreeView, triggered=lambda: self.on_exclude_library(self.context_menu_param)) action_value_detail = QtWidgets.QAction(\"Inspect Value Details\", self.functionTreeView,", "# Set indentation for argument types (for nested values) arg_ident", "self._add_model_container_members(this_row_item, call_value, ret_value, nest_depth) def _add_model_arg_ref(self, parent, call_value, ret_value, nest_depth=0):", "self.value_view.isVisible(): self.value_view.Show() self.value_view.find_value(value) return def on_thread_combobox_change(self, thread_id): self.reset_function_count(thread_id) # reset", "is not None and not ret_value.is_definitely_parsed: ref_val = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent,", "for persistent_index in self.highligthed_items: if persistent_index.isValid(): item = self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white'))", "function_context_list: item_func_context_list = self._make_func_occur_item(function_context, occurrence_num) item_func_context = item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function,", "point): index = self.functionTreeView.indexAt(point) is_function_item = index.data(role=DIE.UI.Function_Role) is_func_context_item = index.data(role=DIE.UI.FunctionContext_Role)", "= self.die_db.get_return_values(function_context) curret_ret_arg_value = self.die_db.get_return_arg_value(function_context) for arg_index in xrange(0, function.arg_num):", "None and ea is not idc.BADADDR: idc.Jump(ea) return True #", "### Indirect Header item_header = QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument Type\") model.setHorizontalHeaderItem(4, item_header)", "self.function_context_menu.addAction(action_exclude_func_adrs) # Function ea ContextMenu self.ea_context_menu = QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph)", "name \"\"\" self.clear_highlights() matched_items = self.functionModel.findItems(function_name) for item in matched_items:", "Build a tree item for function occurrence (level-2) @param function_context:", "self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True) delegate = TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0,", "item_function.setData(function, role=DIE.UI.Function_Role) function_count = self.die_db.count_function_occurs(function) item_function_count = QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False) item_function.setEditable(False)", "self._make_thread_id_data(thread_id) thread_data = item.data(role=DIE.UI.ThreadId_Role) if thread_data is None: item.setData(current_thread_id, role=DIE.UI.ThreadId_Role)", "as two or more items. if parsed_val_list is not None", "is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_func_context_item is not None: self.context_menu_param = is_func_context_item", "= hex(call_value.raw_value) if len(call_value.nested_values) > 0 or call_value.reference_flink is not", "# @QtCore.Slot(str) def on_exclude_func_adrs(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if", "Indirect Header item_header = QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument Type\") model.setHorizontalHeaderItem(4, item_header) ###", "Indirect Header item_header = QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New Function\") model.setHorizontalHeaderItem(3, item_header) ###", "is not None and ret_value.type == call_value.type: if ret_value.nested_values is", "QtWidgets.QLabel(\"Thread: \") # Toolbar self.function_toolbar = QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo) #", "item_list = [item_func_context_ea, QtGui.QStandardItem(), item_func_is_indirect, item_func_is_new, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "current_arg.name, current_arg.type) except IndexError: break ret_arg = self.die_db.get_function_arg(function, -1) if", "as ex: idaapi.msg(\"Error while clearing highlights: %s\\n\" % ex) ###############################################################################################", "# @QtCore.Slot(str) def on_exclude_library(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if", "import DIE.UI.Die_Icons import DIE.UI.ValueViewEx import DIE.UI.ParserView import DIE.UI.BPView import DIE.Lib.IDAConnector", "None: ea = function.function_start if function.is_lib_func: ea = function.proto_ea if", "self.functionModel.findItems(function_name) for item in matched_items: self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(), _PositionAtTop) self.highlight_item_row(item) def", "_make_model_headers(self, model): \"\"\" Set the model horizontal header data @param", "\"!MAX_DEREF!\" if call_value.raw_value is not None: parsed_val_data = hex(call_value.raw_value) if", "item_header) ### New Function Header item_header = QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument Name\")", "self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) # @QtCore.Slot(str) def on_exclude_func(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction):", "the _make_thread_id_data function (e.g: thread_id 123 will become 't123t') the", "is not None and not ret_value.is_definitely_parsed: ref_val_ret = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent,", "to currently selected thread_id @param thread_id: currently selected thread_id \"\"\"", "role=DIE.UI.ThreadId_Role) item_list = [item_func_context, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "QtWidgets.QAction(\"Exclude All Function Calls\", self.functionTreeView, triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea = QtWidgets.QAction(\"Exclude", "count and set the count according to currently selected thread_id", "# Add non-executed function to the model # for func_ea", "# Therad ComboBox threads = [] if self.die_db is not", "them to the module self._add_model_arg_ref(this_row_item, call_value, ret_value, nest_depth) # If", "@QtCore.Slot(str) def on_exclude_func(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function", "value can be \"a123aa5672aa11112a\") for threads 123, 5672 and 111112", "matched_items = self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id, -1, _MatchRecursive | _MatchExactly) for", "or call_value.reference_flink is not None: parsed_val_data = \"\" item_parsed_val_call =", "the data to @param thread_id: thread_id number @return: True if", "index in xrange(0, len(call_value.nested_values)): nested_val_call = self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret = None", "ValueError(\"Wrong value sent to 'on_exclude_func_adrs': %s. excpected dbFunction_Context\" % function.__class__)", "is not None and ret_value.type == call_value.type: if ret_value.reference_flink is", "= QtCore.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchRecursive _MatchExactly = QtCore.Qt.MatchExactly _PositionAtTop =", "function in self.die_db.get_functions(): item_list_func = self._make_function_item(function) if function.is_lib_func: # Color", "-1, _MatchRecursive | _MatchExactly) for index in matched_items: if not", "item for the function occurrence \"\"\" func_occur_txt = \"Occur %s\"", "self._add_model_arg_value(parent, None, ref_val, ref_val.name, ref_val.type, nest_depth+1) def _add_model_container_members(self, parent, call_value,", "not item.index().isValid(): return parent = item.parent() if parent is None:", "= QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count, 0, this_row_item) parent.setChild(arg_count, 1, QtGui.QStandardItem()) parent.setChild(arg_count, 2,", "parsed_val_list = index.data(role=DIE.UI.ParsedValuesRole) # Show combobox only if parsed_value as", "role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module look-ups item_func_is_indirect =", "function_name): \"\"\" Build a tree item for a function name", "function_name = self.die_db.get_function_name(function_context.function) viewer = sark.ui.NXGraph(graph, \"Callgraph for {}\".format(function_name), handler=sark.ui.AddressNodeHandler())", "'on_show_callgraph': %s. excpected dbFunction_Context\" % function_context.__class__) else: raise ValueError(\"Wrong value", "action_value_detail = QtWidgets.QAction(\"Inspect Value Details\", self.functionTreeView, triggered=lambda: self.on_value_detail(self.context_menu_param)) action_show_callgraph =", "None: if ret_value.nested_values: for nested_value in ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(nested_value)", "item, show a combo-box item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else: item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole)", "DoubleClicked Slot. @param index: QModelIndex object of the clicked tree", "\"\"\" calling_function_start = None with ignored(sark.exceptions.SarkNoFunction): calling_function_start = sark.Function(function_context.calling_ea).startEA if", "= QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument Type\") model.setHorizontalHeaderItem(4, item_header) ### New Function Header", "model.setHorizontalHeaderItem(8, item_header) ### Return Value Header item_header = QtGui.QStandardItem(\"Return Value\")", "= QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role) #", "import sark import idaapi import idautils import idc from idaapi", "raise ValueError(\"Wrong value sent to 'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return # @QtCore.Slot(str)", "\"[%s]:%s\" % (function_context.calling_func_name, hex(function_context.calling_ea)) item_func_context_ea = QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole)", "= index.data(role=DIE.UI.FunctionContext_Role) is_value_item = index.data(role=DIE.UI.ParsedValueRole) if is_function_item is not None:", "item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6, item_header) ### Call Value Header item_header", "Increment occurrence counter occurrence_num += 1 # Add non-executed function", "parsed_value as two or more items. if parsed_val_list is not", "2, QtGui.QStandardItem()) parent.setChild(arg_count, 3, QtGui.QStandardItem()) parent.setChild(arg_count, 4, QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count, 5,", "self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label = QtWidgets.QLabel(\"Thread: \") # Toolbar self.function_toolbar = QtWidgets.QToolBar()", "func_context is not None: ea = func_context.calling_ea if ea is", "self.parent = parent def createEditor(self, parent, option, index): parsed_val_list =", "Show combobox only if parsed_value as two or more items.", "matched_items = self.functionModel.findItems(function_name) for item in matched_items: self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(), _PositionAtTop)", "func_context_dict[function_context_ea] if not len(function_context_list) > 0: continue item_func_context_list = self._make_function_ea_item(function_context_list[0])", "QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6, item_header) ### Call Value Header item_header = QtGui.QStandardItem(\"Call", "Header item_header = QtGui.QStandardItem(\"Return Value\") item_header.setToolTip(\"Argument`s value on function return\")", "cur_font.setBold(True) item.setFont(cur_font) except Exception as ex: idaapi.msg(\"Error while highlighting item:", "rows): cur_item = root_item.child(row, 0) function = cur_item.data(role=DIE.UI.Function_Role) if function", "Graph\") return for ctxt_node in call_graph: (from_address, to_address) = ctxt_node", "for nested_value in ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent, None, nested_val_ret,", "if is_value_item is not None: self.context_menu_param = is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) #", "model.clear() # Clear the model root_node = model.invisibleRootItem() self._make_model_headers(model) if", "self._make_thread_id_data(thread_id) + \".*\" threadProxyModel = _QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel)", "tmp_item.setBackground(QtGui.QColor(184, 223, 220)) item_function = item_list_func[0] root_node.appendRow(item_list_func) # Add function", "calling_function_start = sark.Function(function_context.calling_ea).startEA if calling_function_start is not None: call_offset =", "be set \"\"\" ### Function Header item_header = QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function", "self.functionTreeView.setColumnWidth(4, 250) self.functionTreeView.setColumnWidth(5, 100) self.functionTreeView.setColumnWidth(6, 20) self.functionTreeView.setColumnWidth(7, 450) self.functionTreeView.setColumnWidth(8, 20)", "call_value is not None and call_value.nested_values is not None: if", "item_function.appendRow(item_func_context_list) occurrence_num = 0 for function_context in function_context_list: item_func_context_list =", "= None self.bp_handler = None self.die_icons = None self.die_db =", "be appended to a string of concatenated (unique) child-item thread-ids", "= [item_function, item_function_count, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "is None: count = self.die_db.count_function_occurs(function) else: count = self.die_db.count_function_occurs(function, int(thread_id))", "in ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent, None, nested_val_ret, nested_val_ret.name, nested_val_ret.type,", "= \"VOID\" else: ret_arg_type = ret_arg.type # Add return argument", "excpected dbFunction_Context\" % function_context.__class__) else: raise ValueError(\"Wrong value sent to", "self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret = None # Try to get the same", "Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8, item_header) ### Return Value Header", "\"\"\" Is functionview visible @return: True if visible, otherwise False", "0) if not root_index.isValid(): return for func_context in context_list: context_id", "not idc.BADADDR: idc.Jump(ea) return True # @QtCore.Slot(QtCore.QPoint) def onCustomContextMenu(self, point):", "@param nest_depth: @return: \"\"\" # If call debug value is", "return item_list def _make_function_ea_item(self, function_context): \"\"\" Build a tree item", "ret_value.reference_flink is not None and not ret_value.is_definitely_parsed: ref_val_ret = self.die_db.get_dbg_value(ret_value.reference_flink)", "item: %s\\n\" %ex) def highlight_item_row(self, item): \"\"\" highlight the entire", "become 't123t') the delimited value will then be appended to", "function) @type: String @param function_name: Function name @return: \"\"\" item_function", "thread_id: currently selected thread_id \"\"\" root_item = self.functionModel.item(0, 0) rows", "def _insert_thread_data(self, item, thread_id): \"\"\" Insert thread_id data into a", "%s\\n\" %ex) def highlight_item_row(self, item): \"\"\" highlight the entire row", "in item_list_func: # tmp_item.setBackground(QtGui.QColor(255, 0, 0, 127)) # # root_node.appendRow(item_list_func)", "_QSortFilterProxyModel = QtCore.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchRecursive _MatchExactly = QtCore.Qt.MatchExactly _PositionAtTop", "20) self.functionTreeView.setColumnWidth(3, 20) self.functionTreeView.setColumnWidth(4, 250) self.functionTreeView.setColumnWidth(5, 100) self.functionTreeView.setColumnWidth(6, 20) self.functionTreeView.setColumnWidth(7,", "# Add function arguments to each context current_call_values = self.die_db.get_call_values(function_context)", "self.context_menu_param = is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_value_item is not None: self.context_menu_param", "if is_function_item is not None: self.context_menu_param = is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if", "self.bp_handler.add_bp_funcname_exception(function.function_name) return # @QtCore.Slot(str) def on_exclude_func_adrs(self, function): if not isinstance(function,", "concatenated (unique) child-item thread-ids (for example a item data value", "return False ############################################################################################### # Slots. # @QtCore.Slot(QtCore.QModelIndex) def itemDoubleClickSlot(self, index):", "= item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function, function_context.thread_id) self._insert_thread_data(item_func_context_ea, function_context.thread_id) # Add function", "Function\", self.functionTreeView, triggered=lambda: self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs = QtWidgets.QAction(\"Exclude All Function Calls\",", "None: raise ValueError(\"Wrong value sent to 'on_show_callgraph': %s. excpected dbFunction_Context\"", "self.parent = form_to_widget(form) self.functionModel = QtGui.QStandardItemModel() self.functionTreeView = QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False)", "@return: \"\"\" # If call value is a container type", "# If call debug value is a reference if call_value", "of function contexts (of type dbFunction_Context) \"\"\" try: self.clear_highlights() root_index", "a combo-box item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else: item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data", "= QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail) # Therad ComboBox threads = [] if", "ea = func_context.calling_ea if ea is not None and ea", "item_func_context_list = self._make_function_ea_item(function_context_list[0]) item_func_context_ea = item_func_context_list[0] item_function.appendRow(item_func_context_list) occurrence_num = 0", "% function_context.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea)", "function_txt = \"%s\" % function.function_name item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_txt) item_function.setData(function,", "def on_show_callgraph(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context is", "thread_id_list.append(\"All Threads\") for thread in threads: thread_id_list.append(str(thread.thread_num)) self.thread_id_combo = QtWidgets.QComboBox()", "= self.die_db.get_function_arg(function, -1) if ret_arg is None: ret_arg_type = \"VOID\"", "function_context.calling_ea - calling_function_start func_ea_txt = \"%s+%s\" % (function_context.calling_func_name, hex(call_offset)) else:", "if ret_value.nested_values: for nested_value in ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent,", "is not None: call_offset = function_context.calling_ea - calling_function_start func_ea_txt =", "\"\"\" ### Function Header item_header = QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function Name\") model.setHorizontalHeaderItem(0,", "127)) # # root_node.appendRow(item_list_func) def _make_model_headers(self, model): \"\"\" Set the", "QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True) delegate = TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel)", "item_list def _make_nonexec_function_time(self, function_name): \"\"\" Build a tree item for", "for argument types (for nested values) arg_ident = \" \"", "is_function_item is not None: self.context_menu_param = is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_func_context_item", "parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index = QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index) except Exception as ex:", "def _make_thread_id_data(self, thread_id): \"\"\" Delimit thread_id data in order to", "raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") if function.is_lib_func and function.lib_name", "a container type (and call value is not) elif ret_value", "= [item_function, item_function_count] return item_list def _make_function_ea_item(self, function_context): \"\"\" Build", "If return value is a container type (and call value", "_MatchExactly = QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import DIE.UI.Die_Icons import DIE.UI.ValueViewEx", "thread_id_list.append(str(thread.thread_num)) self.thread_id_combo = QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label = QtWidgets.QLabel(\"Thread: \")", "item.font() cur_font.setBold(False) item.setFont(cur_font) self.highligthed_items = [] except Exception as ex:", "self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return # @QtCore.Slot(str) def on_show_callgraph(self, function_context): if not isinstance(function_context,", "= QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New Function\") model.setHorizontalHeaderItem(3, item_header) ### Indirect Header item_header", "QtGui.QStandardItem(\"Return Value\") item_header.setToolTip(\"Argument`s value on function return\") model.setHorizontalHeaderItem(9, item_header) def", "QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo) # Grid layout = QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView)", "data items @param thread_id: thread id to normalize @return: a", "for the function \"\"\" function_txt = \"%s\" % function.function_name item_function", "= QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count, QtGui.QStandardItem(), QtGui.QStandardItem(),", "parent: @param call_value: @param ret_value: @param arg_name: @param arg_type: @return:", "3, QtGui.QStandardItem()) parent.setChild(arg_count, 4, QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count, 5, QtGui.QStandardItem(arg_name)) parent.setChild(arg_count, 6,", "set \"\"\" ### Function Header item_header = QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function Name\")", "= QtCore.Qt.MatchRecursive _MatchExactly = QtCore.Qt.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.PositionAtTop else: _QSortFilterProxyModel", "\"\"\" function = index.data(role=DIE.UI.Function_Role) if function is not None: ea", "can be \"a123aa5672aa11112a\") for threads 123, 5672 and 111112 @param", "= ctxt_node graph.add_edge(from_address, to_address) function_name = self.die_db.get_function_name(function_context.function) viewer = sark.ui.NXGraph(graph,", "7, item_parsed_val_call) parent.setChild(arg_count, 8, item_parsed_val_flag_ret) parent.setChild(arg_count, 9, item_parsed_val_ret) # If", "function occurrence \"\"\" func_occur_txt = \"Occur %s\" % str(occur_num) item_func_context", "if thread_data is None: item.setData(current_thread_id, role=DIE.UI.ThreadId_Role) elif not current_thread_id in", "is not None and len(parsed_vals) > 0: is_guessed, best_val =", "for index in xrange(0, len(call_value.nested_values)): nested_val_call = self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret =", "_make_nonexec_function_time(self, function_name): \"\"\" Build a tree item for a function", "triggered=lambda: self.on_show_callgraph(self.context_menu_param)) # Function ContextMenu self.function_context_menu = QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library)", "not root_index.isValid(): return for func_context in context_list: context_id = id(func_context)", "self.functionTreeView.setModel(self.functionModel) return hidden_threads = \".*\" + self._make_thread_id_data(thread_id) + \".*\" threadProxyModel", "if is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: # If more", "idaapi.msg(\"Error while inserting thread data: %s\\n\" %ex) return False def", "self._add_model_arg_value(parent, None, nested_val_ret, nested_val_ret.name, nested_val_ret.type, nest_depth+1) def reset_function_count(self, thread_id=None): \"\"\"", "sent to 'on_show_callgraph': %s. excpected dbFunction_Context\" % function_context.__class__) else: raise", "0: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call = QtGui.QStandardItem(best_val.data) if is_guessed:", "reference (and call value is not) elif ret_value is not", "TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\" Delegate for parsed value viewing in the tree", "QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect Call\") model.setHorizontalHeaderItem(2, item_header) ### Indirect Header item_header =", "to get the same member from the return debug value.", "self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_func_context_item is not None: self.context_menu_param = is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point))", "# Actions self.context_menu_param = None # Parameter to be passed", "\"\"\" DIE Function View \"\"\" def __init__(self): super(FunctionView, self).__init__() self.value_view", "item_parsed_val_call = QtGui.QStandardItem(parsed_val_data) # Get return value if ret_value is", "#self.functionTreeView.setSortingEnabled(True) delegate = TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0, 200)", "this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role) # If len(parsed_vals)>1 create a combobox delegate. if", "to this function\") model.setHorizontalHeaderItem(1, item_header) ### Indirect Header item_header =", "= function.proto_ea if ea is not None and ea is", "while highlighting item: %s\\n\" %ex) def highlight_item_row(self, item): \"\"\" highlight", "Type\") model.setHorizontalHeaderItem(4, item_header) ### New Function Header item_header = QtGui.QStandardItem(\"Name\")", "call_value, ret_value, nest_depth) def _add_model_arg_ref(self, parent, call_value, ret_value, nest_depth=0): \"\"\"", "self.value_view.Show() self.value_view.find_value(value) return def on_thread_combobox_change(self, thread_id): self.reset_function_count(thread_id) # reset function", "############################################################################################### # Highlight Items. def highlight_item(self, item): \"\"\" Highlight a", "= is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_value_item is not None: self.context_menu_param =", "# If len(parsed_vals)>1 create a combobox delegate. if parsed_vals: is_guessed,", "calling_function_start is not None: call_offset = function_context.calling_ea - calling_function_start func_ea_txt", "= self.thread_id_combo.currentText() for row in xrange(0, rows): cur_item = root_item.child(row,", "'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name) return # @QtCore.Slot(str) def on_exclude_func_adrs(self, function): if not", "is not None and call_value.nested_values is not None: if call_value.nested_values:", "View \"\"\" def __init__(self): super(FunctionView, self).__init__() self.value_view = None self.bp_handler", "__init__(self): super(FunctionView, self).__init__() self.value_view = None self.bp_handler = None self.die_icons", "looking up function context in FunctionView: %s\\n\" % ex) return", "= QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly = QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import DIE.UI.Die_Icons", "PluginForm from sark.qt import QtGui, QtCore, QtWidgets, form_to_widget, use_qt5 if", "ex: idaapi.msg(\"Error while highlighting item: %s\\n\" %ex) def highlight_item_row(self, item):", "(e.g: thread_id 123 will become 't123t') the delimited value will", "sent to 'on_exclude_func_adrs': %s. excpected dbFunction_Context\" % function.__class__) else: raise", "self.bp_handler = None self.die_icons = None self.die_db = None self.highligthed_items", "parsed_val_data = \"\" item_parsed_val_call = QtGui.QStandardItem(parsed_val_data) # Get return value", "\"\"\" try: self.clear_highlights() root_index = self.functionModel.index(0, 0) if not root_index.isValid():", "threads = self.die_db.get_thread_list() thread_id_list = [] thread_id_list.append(\"All Threads\") for thread", "= [] def Show(self): # Reset highlighted items self.highligthed_items =", "in func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return # @QtCore.Slot(str) def on_exclude_ea(self, function_context): if", "index.data(role=DIE.UI.Function_Role) if function is not None: ea = function.function_start if", "sent to 'on_exclude_func_adrs'\") func_context_list = self.die_db.get_function_context_list(function) for func_context in func_context_list:", "member from the return debug value. if ret_value is not", "self.highlight_item_row(item) def find_context_list(self, context_list): \"\"\" Find and highlight a list", "to @param thread_id: thread_id number @return: True if thread data", "Toolbar self.function_toolbar = QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo) # Grid layout =", "item_list def _make_function_ea_item(self, function_context): \"\"\" Build a tree item for", "QtCore, QtWidgets, form_to_widget, use_qt5 if use_qt5: _QSortFilterProxyModel = QtCore.QSortFilterProxyModel _MatchRecursive", "= root_item.rowCount() thread_id = self.thread_id_combo.currentText() for row in xrange(0, rows):", "\"\"\" try: return self.functionTreeView.isVisible() except: return False def _model_builder(self, model):", "nested_value in ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent, None, nested_val_ret, nested_val_ret.name,", "try: current_thread_id = self._make_thread_id_data(thread_id) thread_data = item.data(role=DIE.UI.ThreadId_Role) if thread_data is", "self.functionModel.index(0, 0) if not root_index.isValid(): return for func_context in context_list:", "item_list def _make_func_occur_item(self, function_context, occur_num): \"\"\" Build a tree item", "If more the 1 item, show a combo-box item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole)", "to module @param parent: @param call_value: @param ret_value: @param nest_depth:", "highlight_item_row(self, item): \"\"\" highlight the entire row containing a table", "members to module @param parent: @param call_value: @param ret_value: @param", "idaapi.msg(\"Closed\\n\") def isVisible(self): \"\"\" Is functionview visible @return: True if", "the function model. @param model: QStandardItemModel object \"\"\" model.clear() #", "item_function_count] return item_list def _make_function_ea_item(self, function_context): \"\"\" Build a tree", "QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_func_occur_item(self, function_context, occur_num): \"\"\" Build", "Function name @return: \"\"\" item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_name) item_function_count =", "= function_context.calling_ea - calling_function_start func_ea_txt = \"%s+%s\" % (function_context.calling_func_name, hex(call_offset))", "role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else: item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if", "container object, Add its members to the module self._add_model_container_members(this_row_item, call_value,", "QtGui.QStandardItem()) parent.setChild(arg_count, 3, QtGui.QStandardItem()) parent.setChild(arg_count, 4, QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count, 5, QtGui.QStandardItem(arg_name))", "number @return: QStandradItemModel item for the function occurrence \"\"\" func_occur_txt", "item_parsed_val_flag_call = QtGui.QStandardItem() item_parsed_val_call = QtGui.QStandardItem() item_parsed_val_flag_ret = QtGui.QStandardItem() item_parsed_val_ret", "Threads\") for thread in threads: thread_id_list.append(str(thread.thread_num)) self.thread_id_combo = QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list)", "parent.setChild(arg_count, 0, this_row_item) parent.setChild(arg_count, 1, QtGui.QStandardItem()) parent.setChild(arg_count, 2, QtGui.QStandardItem()) parent.setChild(arg_count,", "parsed_val_list is not None and len(parsed_val_list) > 1: lines =", "20) self.functionTreeView.setColumnWidth(9, 450) # Context menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) # Actions", "function_name: Function name \"\"\" self.clear_highlights() matched_items = self.functionModel.findItems(function_name) for item", "item_func_is_new, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def", "= QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph) # Argument value ContextMenu self.value_context_menu =", "to be used sa data for ThreadId_Role \"\"\" return \"t%st\"", "= QtWidgets.QAbstractItemView.PositionAtTop else: _QSortFilterProxyModel = QtGui.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly", "root_index = self.functionModel.index(0, 0) if not root_index.isValid(): return for func_context", "ea is not idc.BADADDR: idc.Jump(ea) return True # @QtCore.Slot(QtCore.QPoint) def", "# Context menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) # Actions self.context_menu_param = None", "current_thread_id in thread_data: item.setData(thread_data + current_thread_id, role=DIE.UI.ThreadId_Role) return True except", "parsed_val_data = \"!MAX_DEREF!\" if ret_value.raw_value is not None: parsed_val_data =", "index.data(role=DIE.UI.Function_Role) is_func_context_item = index.data(role=DIE.UI.FunctionContext_Role) is_value_item = index.data(role=DIE.UI.ParsedValueRole) if is_function_item is", "self.die_db.get_function_by_name(func_name) is None: # item_list_func = self._make_nonexec_function_time(func_name) # # if", "DIE.UI.ParserView import DIE.UI.BPView import DIE.Lib.IDAConnector import DIE.Lib.DIEDb import DIE.Lib.BpHandler import", "function.is_lib_func: # Color library function # for tmp_item in item_list_func:", "= None # Try to get the same reference from", "return # @QtCore.Slot(str) def on_show_callgraph(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context):", "try: current_arg = self.die_db.get_function_arg(function, arg_index) self._add_model_arg_value(item_func_context, current_call_values[arg_index], current_ret_values[arg_index], current_arg.name, current_arg.type)", "model.setHorizontalHeaderItem(0, item_header) ### Call number header item_header = QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number", "str(thread_id) def _insert_thread_data(self, item, thread_id): \"\"\" Insert thread_id data into", "# Try to get the same member from the return", "is not None: self.bp_handler.add_module_exception(function.lib_name) return # @QtCore.Slot(str) def on_value_detail(self, value):", "function (e.g: thread_id 123 will become 't123t') the delimited value", "except Exception as ex: idaapi.msg(\"Error while inserting thread data: %s\\n\"", "value is not) elif ret_value is not None: if ret_value.nested_values", "= QtGui.QStandardItem() item_func_is_indirect.setEditable(False) if function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new = QtGui.QStandardItem() item_func_is_new.setEditable(False)", "@param function: dbFunction object @return: QStandradItemModel item for the function", "item_parsed_val_ret = QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count, 0, this_row_item) parent.setChild(arg_count, 1, QtGui.QStandardItem()) parent.setChild(arg_count,", "nest_depth+1) def _add_model_container_members(self, parent, call_value, ret_value, nest_depth=0): \"\"\" Add container", "for row in xrange(0, rows): cur_item = root_item.child(row, 0) function", "be \"a123aa5672aa11112a\") for threads 123, 5672 and 111112 @param item:", "= QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import DIE.UI.Die_Icons import DIE.UI.ValueViewEx import DIE.UI.ParserView import DIE.UI.BPView", "is not None: self.context_menu_param = is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_value_item is", "value ContextMenu self.value_context_menu = QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail) # Therad ComboBox threads", "non-executed function to the model # for func_ea in idautils.Functions():", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _add_model_arg_value(self, parent, call_value,", "highlight_item(self, item): \"\"\" Highlight a single item @param item: module", "import idc from idaapi import PluginForm from sark.qt import QtGui,", "if use_qt5: _QSortFilterProxyModel = QtCore.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchRecursive _MatchExactly =", "and not ret_value.is_definitely_parsed: ref_val_ret = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, ref_val_call, ref_val_ret, ref_val_call.name,", "ret_value, nest_depth=0): \"\"\" Add a reference value to module @param", "and 111112 @param item: the model item to add the", "not None: if ret_value.reference_flink is not None and not ret_value.is_definitely_parsed:", "context_list: context_id = id(func_context) matched_items = self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id, -1,", "model. @param model: QStandardItemModel object \"\"\" model.clear() # Clear the", "function is not None: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs':", "self._make_func_occur_item(function_context, occurrence_num) item_func_context = item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function, function_context.thread_id) self._insert_thread_data(item_func_context_ea, function_context.thread_id)", "1: lines = [] for parsed_val in parsed_val_list: line_txt =", "name @return: \"\"\" item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_name) item_function_count = QtGui.QStandardItem(\"0\")", "1 item, show a combo-box item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else: item_parsed_val_call.setData(parsed_vals[0],", "New Function Header item_header = QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument Name\") model.setHorizontalHeaderItem(5, item_header)", "def on_exclude_func(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is", "show a combo-box item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else: item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else:", "nest_depth) def _add_model_arg_ref(self, parent, call_value, ret_value, nest_depth=0): \"\"\" Add a", "= self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white')) cur_font = item.font() cur_font.setBold(False) item.setFont(cur_font) self.highligthed_items =", "def on_exclude_func_adrs(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is", "_QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel) def on_valueview_button(self): value_view = DIE.UI.ValueViewEx.get_view()", "DIE.UI.BPView import DIE.Lib.IDAConnector import DIE.Lib.DIEDb import DIE.Lib.BpHandler import sark.ui class", "return True except Exception as ex: idaapi.msg(\"Error while looking up", "Add non-executed function to the model # for func_ea in", "= root_item.child(row, 1) func_count_item.setText(str(count)) ############################################################################################### # Highlight Items. def highlight_item(self,", "func_ea in idautils.Functions(): # func_name = DIE.Lib.IDAConnector.get_function_name(func_ea) # # if", "\"\"\" highlight the entire row containing a table item @param", "= [item_func_context_ea, QtGui.QStandardItem(), item_func_is_indirect, item_func_is_new, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "item.setBackground(QtGui.QColor('yellow')) cur_font = item.font() cur_font.setBold(True) item.setFont(cur_font) except Exception as ex:", "self._make_function_ea_item(function_context_list[0]) item_func_context_ea = item_func_context_list[0] item_function.appendRow(item_func_context_list) occurrence_num = 0 for function_context", "ContextMenu self.ea_context_menu = QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph) # Argument value ContextMenu", "occurrence_num) item_func_context = item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function, function_context.thread_id) self._insert_thread_data(item_func_context_ea, function_context.thread_id) #", "item, thread_id): \"\"\" Insert thread_id data into a model item.", "and ea is not idc.BADADDR: idc.Jump(ea) return True # @QtCore.Slot(QtCore.QPoint)", "\"%s\" % function.function_name item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_txt) item_function.setData(function, role=DIE.UI.Function_Role) function_count", "\"\"\" TreeView DoubleClicked Slot. @param index: QModelIndex object of the", "None self.bp_handler = None self.die_icons = None self.die_db = None", "the module self._add_model_arg_ref(this_row_item, call_value, ret_value, nest_depth) # If current object", "= QtGui.QStandardItem(parsed_val_data) # Get return value if ret_value is not", "# Get return value if ret_value is not None: parsed_vals", "\"\"\" Add a reference value to module @param parent: @param", "function_context: a dbFunction_Context object @param occur_num: occurrence number @return: QStandradItemModel", "= self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role) # If len(parsed_vals)>1 create a combobox", "str(occur_num) item_func_context = QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5) item_func_context.setEditable(False) item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role)", "QtGui.QStandardItem(self.die_icons.icon_function, function_name) item_function_count = QtGui.QStandardItem(\"0\") item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function,", "item.row() column_num = parent.columnCount() for column in xrange(0, column_num): if", "Slot. @param index: QModelIndex object of the clicked tree index", "delegate = TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0, 200) self.functionTreeView.setColumnWidth(1,", "'t123t') the delimited value will then be appended to a", "item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if call_value.derref_depth == 0:", "not self.functionTreeView.model() is self.functionModel: self.functionTreeView.setModel(self.functionModel) return hidden_threads = \".*\" +", "True # @QtCore.Slot(QtCore.QPoint) def onCustomContextMenu(self, point): index = self.functionTreeView.indexAt(point) is_function_item", "Find and highlight a function in current module @param function_name:", "_MatchExactly) for index in matched_items: if not index.isValid(): continue #", "self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role) if parsed_vals is not None and len(parsed_vals)", "Highlight a single item @param item: module item \"\"\" try:", "raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name) return # @QtCore.Slot(str)", "arg_ident = \" \" * nest_depth arg_ident_type = arg_ident +", "return # @QtCore.Slot(str) def on_value_detail(self, value): if not self.value_view.isVisible(): self.value_view.Show()", "not None: ea = function.function_start if function.is_lib_func: ea = function.proto_ea", "return False def _make_function_item(self, function): \"\"\" Build a tree item", "@QtCore.Slot(str) def on_exclude_library(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function", "= self.die_db.count_function_occurs(function) item_function_count = QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function,", "role=DIE.UI.Function_Role) function_count = self.die_db.count_function_occurs(function) item_function_count = QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False) item_function.setEditable(False) item_list", "column_num): if self.functionModel.hasIndex(row, column, parent.index()): cur_index = self.functionModel.index(row, column, parent.index())", "func_context.calling_ea if ea is not None and ea is not", "item_func_is_indirect = QtGui.QStandardItem() item_func_is_indirect.setEditable(False) if function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new = QtGui.QStandardItem()", "Exception as ex: idaapi.msg(\"Error while highlighting item: %s\\n\" %ex) def", "def clear_highlights(self): \"\"\" Clear all highlighted items @return: \"\"\" try:", "ret_value.raw_value is not None: parsed_val_data = hex(ret_value.raw_value) if ret_value.nested_values or", "model.setHorizontalHeaderItem(4, item_header) ### New Function Header item_header = QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument", "this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role) if parsed_vals is not None and len(parsed_vals) >", "@param item: module item \"\"\" try: item.setBackground(QtGui.QColor('yellow')) cur_font = item.font()", "Find and highlight a list of function contexts @param context_list:", "item_list_func[0] root_node.appendRow(item_list_func) # Add function contexts ea\\occurrences for the current", "= _QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel) def on_valueview_button(self): value_view =", "value is a reference if call_value is not None: if", "otherwise False \"\"\" try: return self.functionTreeView.isVisible() except: return False def", "= item.parent() if parent is None: parent = item if", "cur_index = self.functionModel.index(row, column, parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index = QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index)", "self.clear_highlights() root_index = self.functionModel.index(0, 0) if not root_index.isValid(): return for", "False \"\"\" try: current_thread_id = self._make_thread_id_data(thread_id) thread_data = item.data(role=DIE.UI.ThreadId_Role) if", "123 will become 't123t') the delimited value will then be", "_PositionAtTop) self.highlight_item_row(item) return True except Exception as ex: idaapi.msg(\"Error while", "None: # item_list_func = self._make_nonexec_function_time(func_name) # # if function.is_lib_func: #", "\"\"\" Delegate for parsed value viewing in the tree view", "nested_val_ret, nested_val_call.name, nested_val_call.type, nest_depth+1) # If return value is a", "db functions to the model for function in self.die_db.get_functions(): item_list_func", "- calling_function_start func_ea_txt = \"%s+%s\" % (function_context.calling_func_name, hex(call_offset)) else: func_ea_txt", "DIE.UI.BPView.get_view() bp_view.Show() ############################################################################################### # View Delegates. class TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\" Delegate", "arg_index in xrange(0, function.arg_num): try: current_arg = self.die_db.get_function_arg(function, arg_index) self._add_model_arg_value(item_func_context,", "= sark.Function(function_context.calling_ea).startEA if calling_function_start is not None: call_offset = function_context.calling_ea", "context_list): \"\"\" Find and highlight a list of function contexts", "self.die_db.get_function_name(function_context.function) viewer = sark.ui.NXGraph(graph, \"Callgraph for {}\".format(function_name), handler=sark.ui.AddressNodeHandler()) viewer.Show() return", "= self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret = None # Try to get the", "calling_function_start func_ea_txt = \"%s+%s\" % (function_context.calling_func_name, hex(call_offset)) else: func_ea_txt =", "role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module look-ups", "None: parsed_val_data = \"\" item_parsed_val_call = QtGui.QStandardItem(parsed_val_data) # Get return", "the count according to currently selected thread_id @param thread_id: currently", "return value if ret_value is not None: parsed_vals = self.die_db.get_parsed_values(ret_value)", "not None: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs': %s. excpected", "items self.highligthed_items = [] return PluginForm.Show(self, \"Function View\", options=PluginForm.FORM_PERSIST) def", "= self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id, -1, _MatchRecursive | _MatchExactly) for index", "is not None and ea is not idc.BADADDR: idc.Jump(ea) return", "ret_arg_type = ret_arg.type # Add return argument self._add_model_arg_value(item_func_context, None, curret_ret_arg_value,", "on_thread_combobox_change(self, thread_id): self.reset_function_count(thread_id) # reset function count according to currently", "= form_to_widget(form) self.functionModel = QtGui.QStandardItemModel() self.functionTreeView = QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True)", "clicked tree index item. @return: \"\"\" function = index.data(role=DIE.UI.Function_Role) if", "role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if ret_value.derref_depth == 0: parsed_val_data", "1: # If more the 1 item, show a combo-box", "not index.data().startswith(\"Occur\"): continue item = self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index, _PositionAtTop) self.highlight_item_row(item)", "ret_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\" if ret_value.raw_value is not", "= function.function_start if function.is_lib_func: ea = function.proto_ea if ea is", "id(func_context) matched_items = self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id, -1, _MatchRecursive | _MatchExactly)", "= self._make_function_item(function) if function.is_lib_func: # Color library function for tmp_item", "parent widget self.parent = form_to_widget(form) self.functionModel = QtGui.QStandardItemModel() self.functionTreeView =", "= self.die_db.count_function_occurs(function, int(thread_id)) func_count_item = root_item.child(row, 1) func_count_item.setText(str(count)) ############################################################################################### #", "% function.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") func_context_list", "= self.die_db.get_return_arg_value(function_context) for arg_index in xrange(0, function.arg_num): try: current_arg =", "to 'on_exclude_func_adrs'\") func_context_list = self.die_db.get_function_context_list(function) for func_context in func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea)", "of the thread_id to be used sa data for ThreadId_Role", "DIE.UI.ParserView.get_view() plugins_view.Show() def on_bpview_button(self): bp_view = DIE.UI.BPView.get_view() bp_view.Show() ############################################################################################### #", "this function\") model.setHorizontalHeaderItem(1, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"I\")", "= self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index, _PositionAtTop) self.highlight_item_row(item) return True except Exception", "= index.data(role=DIE.UI.Function_Role) if function is not None: ea = function.function_start", "idc.BADADDR: idc.Jump(ea) return True func_context = index.data(role=DIE.UI.FunctionContext_Role) if func_context is", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_func_occur_item(self,", "nested_val_call, nested_val_ret, nested_val_call.name, nested_val_call.type, nest_depth+1) # If return value is", "@QtCore.Slot(QtCore.QModelIndex) def itemDoubleClickSlot(self, index): \"\"\" TreeView DoubleClicked Slot. @param index:", "QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs) # Function ea ContextMenu self.ea_context_menu =", "call_value.nested_values: for index in xrange(0, len(call_value.nested_values)): nested_val_call = self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret", "function count and set the count according to currently selected", "QtGui.QStandardItem() item_parsed_val_flag_ret = QtGui.QStandardItem() item_parsed_val_ret = QtGui.QStandardItem() # Get Call", "if function is not None: ea = function.function_start if function.is_lib_func:", "= self.die_db.get_thread_list() thread_id_list = [] thread_id_list.append(\"All Threads\") for thread in", "on_value_detail(self, value): if not self.value_view.isVisible(): self.value_view.Show() self.value_view.find_value(value) return def on_thread_combobox_change(self,", "item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new = QtGui.QStandardItem() item_func_is_new.setEditable(False) if function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v) item_list =", "not call_graph: idaapi.msg(\"No Execution Graph\") return for ctxt_node in call_graph:", "to add the data to @param thread_id: thread_id number @return:", "self.functionTreeView.model() is self.functionModel: self.functionTreeView.setModel(self.functionModel) return hidden_threads = \".*\" + self._make_thread_id_data(thread_id)", "parsed_vals = self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role) if parsed_vals is not None", "form is created \"\"\" self.value_view = DIE.UI.ValueViewEx.get_view() self.bp_handler = DIE.Lib.BpHandler.get_bp_handler()", "parsed_val_data = hex(ret_value.raw_value) if ret_value.nested_values or ret_value.reference_flink is not None:", "\"\"\" Called when the plugin form is created \"\"\" self.value_view", "\"t%st\" % str(thread_id) def _insert_thread_data(self, item, thread_id): \"\"\" Insert thread_id", "action_exclude_func_adrs = QtWidgets.QAction(\"Exclude All Function Calls\", self.functionTreeView, triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea", "self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs) # Function ea ContextMenu self.ea_context_menu = QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea)", "# Show combobox only if parsed_value as two or more", "in parsed_val_list: line_txt = \"%d, %s, %s\" % (parsed_val.score, parsed_val.data,", "will become 't123t') the delimited value will then be appended", "in self.highligthed_items: if persistent_index.isValid(): item = self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white')) cur_font =", "call_value.nested_values is not None: if call_value.nested_values: for index in xrange(0,", "ret_value.nested_values is not None: if ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent,", "set the count according to currently selected thread_id @param thread_id:", "isVisible(self): \"\"\" Is functionview visible @return: True if visible, otherwise", "QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail) # Therad ComboBox threads = [] if self.die_db", "highlighting item row: %s\\n\" % ex) def clear_highlights(self): \"\"\" Clear", "if ea is not None and ea is not idc.BADADDR:", "QtWidgets.QAction(\"Show Call-Graph\", self.functionTreeView, triggered=lambda: self.on_show_callgraph(self.context_menu_param)) # Function ContextMenu self.function_context_menu =", "if call_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\" if call_value.raw_value is", "def highlight_item_row(self, item): \"\"\" highlight the entire row containing a", "sark.qt import QtGui, QtCore, QtWidgets, form_to_widget, use_qt5 if use_qt5: _QSortFilterProxyModel", "= 0 if thread_id is None: count = self.die_db.count_function_occurs(function) else:", "visible @return: True if visible, otherwise False \"\"\" try: return", "self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph) # Argument value ContextMenu self.value_context_menu = QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail)", "item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8, item_header) ### Return Value Header item_header", "of concatenated (unique) child-item thread-ids (for example a item data", "0 if thread_id is None: count = self.die_db.count_function_occurs(function) else: count", "if ret_value is not None and ret_value.type == call_value.type: if", "'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return # @QtCore.Slot(str) def on_show_callgraph(self, function_context): if not", "= nx.DiGraph() call_graph = self.die_db.get_call_graph_to(function_context) if not call_graph: idaapi.msg(\"No Execution", "function.lib_name is not None: self.bp_handler.add_module_exception(function.lib_name) return # @QtCore.Slot(str) def on_value_detail(self,", "item_parsed_val_ret) # If current object contains reference values, add them", "def _add_model_arg_value(self, parent, call_value, ret_value, arg_name, arg_type, nest_depth=0): \"\"\" Add", "else: parsed_val_data = \"NULL\" if call_value.derref_depth == 0: parsed_val_data =", "value @param parent: @param call_value: @param ret_value: @param arg_name: @param", "ret_value.nested_values: for nested_value in ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent, None,", "% str(occur_num) item_func_context = QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5) item_func_context.setEditable(False) item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context),", "Value Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8, item_header) ### Return", "if call_value is not None: parsed_vals = self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role)", "of it. if not index.data().startswith(\"Occur\"): continue item = self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index)", "function_context.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return", "item_header) ### Return Value Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8,", "is not None: if ret_value.nested_values is not None: if ret_value.nested_values:", "value on function return\") model.setHorizontalHeaderItem(9, item_header) def _make_thread_id_data(self, thread_id): \"\"\"", "thread_id @param thread_id: currently selected thread_id \"\"\" root_item = self.functionModel.item(0,", "item_func_context_ea = item_func_context_list[0] item_function.appendRow(item_func_context_list) occurrence_num = 0 for function_context in", "persistent_index.isValid(): item = self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white')) cur_font = item.font() cur_font.setBold(False) item.setFont(cur_font)", "self.functionTreeView.setColumnWidth(5, 100) self.functionTreeView.setColumnWidth(6, 20) self.functionTreeView.setColumnWidth(7, 450) self.functionTreeView.setColumnWidth(8, 20) self.functionTreeView.setColumnWidth(9, 450)", "if function is not None: raise ValueError(\"Wrong value sent to", "to_address) function_name = self.die_db.get_function_name(function_context.function) viewer = sark.ui.NXGraph(graph, \"Callgraph for {}\".format(function_name),", "import ignored import sark import idaapi import idautils import idc", "parent is None: parent = item if not parent.hasChildren(): self.highlight_item(parent)", "ret_value.type == call_value.type: if ret_value.nested_values is not None: if ret_value.nested_values:", "ValueError(\"Wrong value sent to 'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return # @QtCore.Slot(str) def", "@param function_name: Function name @return: \"\"\" item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_name)", "cur_font = item.font() cur_font.setBold(False) item.setFont(cur_font) self.highligthed_items = [] except Exception", "'on_exclude_func_adrs'\") func_context_list = self.die_db.get_function_context_list(function) for func_context in func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return", "item_list_func: tmp_item.setBackground(QtGui.QColor(184, 223, 220)) item_function = item_list_func[0] root_node.appendRow(item_list_func) # Add", "= QtGui.QStandardItem() item_func_is_new.setEditable(False) if function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v) item_list = [item_func_context_ea, QtGui.QStandardItem(),", "ret_value is not None and ret_value.type == call_value.type: if ret_value.nested_values", "\"\"\" Clear all highlighted items @return: \"\"\" try: self.functionTreeView.collapseAll() for", "ref_val, ref_val.name, ref_val.type, nest_depth+1) def _add_model_container_members(self, parent, call_value, ret_value, nest_depth=0):", "\"\"\" self.value_view = DIE.UI.ValueViewEx.get_view() self.bp_handler = DIE.Lib.BpHandler.get_bp_handler() self.die_icons = DIE.UI.Die_Icons.get_die_icons()", "object @param occur_num: occurrence number @return: QStandradItemModel item for the", "for item in matched_items: self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(), _PositionAtTop) self.highlight_item_row(item) def find_context_list(self,", "on function return\") model.setHorizontalHeaderItem(9, item_header) def _make_thread_id_data(self, thread_id): \"\"\" Delimit", "= None with ignored(sark.exceptions.SarkNoFunction): calling_function_start = sark.Function(function_context.calling_ea).startEA if calling_function_start is", "### Call Value Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6, item_header)", "is not None: ea = func_context.calling_ea if ea is not", "% (function_context.calling_func_name, hex(function_context.calling_ea)) item_func_context_ea = QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context,", "call_value.type: if ret_value.reference_flink is not None and not ret_value.is_definitely_parsed: ref_val_ret", "self._insert_thread_data(item_func_context_ea, function_context.thread_id) # Add function arguments to each context current_call_values", "\"\"\" Set the model horizontal header data @param model: the", "Header item_header = QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument Type\") model.setHorizontalHeaderItem(4, item_header) ### New", "the 1 item, show a combo-box item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else:", "parsed_val_list: line_txt = \"%d, %s, %s\" % (parsed_val.score, parsed_val.data, parsed_val.description)", "\".*\" threadProxyModel = _QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel) def on_valueview_button(self):", "import QtGui, QtCore, QtWidgets, form_to_widget, use_qt5 if use_qt5: _QSortFilterProxyModel =", "@return: \"\"\" try: self.functionTreeView.collapseAll() for persistent_index in self.highligthed_items: if persistent_index.isValid():", "len(parsed_val_list) > 1: lines = [] for parsed_val in parsed_val_list:", "in xrange(0, len(call_value.nested_values)): nested_val_call = self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret = None #", "to_address) = ctxt_node graph.add_edge(from_address, to_address) function_name = self.die_db.get_function_name(function_context.function) viewer =", "the function occurrence \"\"\" func_occur_txt = \"Occur %s\" % str(occur_num)", "def isVisible(self): \"\"\" Is functionview visible @return: True if visible,", "in order to support filtering\\sorting on multi-thread data items @param", "example a item data value can be \"a123aa5672aa11112a\") for threads", "not None and ea is not idc.BADADDR: idc.Jump(ea) return True", "ex: idaapi.msg(\"Error while clearing highlights: %s\\n\" % ex) ############################################################################################### #", "if thread_id == \"All Threads\": if not self.functionTreeView.model() is self.functionModel:", "else: raise ValueError(\"Wrong value sent to 'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return #", "tmp_item.setBackground(QtGui.QColor(255, 0, 0, 127)) # # root_node.appendRow(item_list_func) def _make_model_headers(self, model):", "from idaapi import PluginForm from sark.qt import QtGui, QtCore, QtWidgets,", "nest_depth) # If current object is a container object, Add", "= [] except Exception as ex: idaapi.msg(\"Error while clearing highlights:", "for a function name (level-0) @param function: dbFunction object @return:", "function arguments to each context current_call_values = self.die_db.get_call_values(function_context) current_ret_values =", "added to item, otherwise False \"\"\" try: current_thread_id = self._make_thread_id_data(thread_id)", "is a reference (and call value is not) elif ret_value", "= func_context.calling_ea if ea is not None and ea is", "= \"NULL\" if call_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\" if", "on_exclude_library(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is not", "item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function, function_context.thread_id) self._insert_thread_data(item_func_context_ea, function_context.thread_id) # Add function arguments", "_MatchRecursive = QtCore.Qt.MatchRecursive _MatchExactly = QtCore.Qt.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.PositionAtTop else:", "to support filtering\\sorting on multi-thread data items @param thread_id: thread", "item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: # If more the 1", "row = item.row() column_num = parent.columnCount() for column in xrange(0,", "nested values) arg_ident = \" \" * nest_depth arg_ident_type =", "type dbFunction_Context) \"\"\" try: self.clear_highlights() root_index = self.functionModel.index(0, 0) if", "item_function.setEditable(False) item_list = [item_function, item_function_count, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "\"\"\" arg_count = parent.rowCount() this_row_item = QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role) #", "current_thread_id = self._make_thread_id_data(thread_id) thread_data = item.data(role=DIE.UI.ThreadId_Role) if thread_data is None:", "############################################################################################### # View Delegates. class TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\" Delegate for parsed", "for a function_ea node (level-1) @param function_context: a dbFunction_Context object", "not None and len(parsed_vals) > 0: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals)", "self._make_nonexec_function_time(func_name) # # if function.is_lib_func: # Color library function #", "context \"\"\" calling_function_start = None with ignored(sark.exceptions.SarkNoFunction): calling_function_start = sark.Function(function_context.calling_ea).startEA", "self._add_model_arg_value(parent, ref_val_call, ref_val_ret, ref_val_call.name, ref_val_call.type, nest_depth+1) # If return debug", "in func_context_dict: function_context_list = func_context_dict[function_context_ea] if not len(function_context_list) > 0:", "for ctxt_node in call_graph: (from_address, to_address) = ctxt_node graph.add_edge(from_address, to_address)", "TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0, 200) self.functionTreeView.setColumnWidth(1, 20) self.functionTreeView.setColumnWidth(2,", "function \"\"\" function_txt = \"%s\" % function.function_name item_function = QtGui.QStandardItem(self.die_icons.icon_function,", "item_func_context.setColumnCount(5) item_func_context.setEditable(False) item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module", "contains reference values, add them to the module self._add_model_arg_ref(this_row_item, call_value,", "= QtWidgets.QAction(\"Inspect Value Details\", self.functionTreeView, triggered=lambda: self.on_value_detail(self.context_menu_param)) action_show_callgraph = QtWidgets.QAction(\"Show", "\"\"\" Build a tree item for a function name (for", "= \"%s\" % function.function_name item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_txt) item_function.setData(function, role=DIE.UI.Function_Role)", "Name\") model.setHorizontalHeaderItem(0, item_header) ### Call number header item_header = QtGui.QStandardItem(\"#\")", "ret_value, nest_depth) def _add_model_arg_ref(self, parent, call_value, ret_value, nest_depth=0): \"\"\" Add", "function_name: Function name @return: \"\"\" item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_name) item_function_count", "QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly = QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import DIE.UI.Die_Icons import", "function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v) item_list = [item_func_context_ea, QtGui.QStandardItem(), item_func_is_indirect, item_func_is_new, QtGui.QStandardItem(), QtGui.QStandardItem(),", "values, add them to the module self._add_model_arg_ref(this_row_item, call_value, ret_value, nest_depth)", "of the clicked tree index item. @return: \"\"\" function =", "item_function_count = QtGui.QStandardItem(\"0\") item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count] return", "try: return self.functionTreeView.isVisible() except: return False def _model_builder(self, model): \"\"\"", "QtGui.QStandardItem() item_func_is_new.setEditable(False) if function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v) item_list = [item_func_context_ea, QtGui.QStandardItem(), item_func_is_indirect,", "item = self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index, _PositionAtTop) self.highlight_item_row(item) return True except", "self.functionTreeView.scrollTo(item.index(), _PositionAtTop) self.highlight_item_row(item) def find_context_list(self, context_list): \"\"\" Find and highlight", "= QtGui.QStandardItem(self.die_icons.icon_function, function_name) item_function_count = QtGui.QStandardItem(\"0\") item_function_count.setEditable(False) item_function.setEditable(False) item_list =", "ret_value, arg_name, arg_type, nest_depth=0): \"\"\" Add a debug value @param", "= None self.die_db = None self.highligthed_items = [] def Show(self):", "% str(thread_id) def _insert_thread_data(self, item, thread_id): \"\"\" Insert thread_id data", "except Exception as ex: idaapi.msg(\"Error while highlighting item row: %s\\n\"", "> 0: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call = QtGui.QStandardItem(best_val.data) if", "module @param function_name: Function name \"\"\" self.clear_highlights() matched_items = self.functionModel.findItems(function_name)", "to a string of concatenated (unique) child-item thread-ids (for example", "parent.index()): cur_index = self.functionModel.index(row, column, parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index = QtCore.QPersistentModelIndex(cur_index)", "not None: count = 0 if thread_id is None: count", "self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, ref_val_call, ref_val_ret, ref_val_call.name, ref_val_call.type, nest_depth+1) # If return", "for column in xrange(0, column_num): if self.functionModel.hasIndex(row, column, parent.index()): cur_index", "successfully added to item, otherwise False \"\"\" try: current_thread_id =", "# Clear the model root_node = model.invisibleRootItem() self._make_model_headers(model) if self.die_db", "try: item.setBackground(QtGui.QColor('yellow')) cur_font = item.font() cur_font.setBold(True) item.setFont(cur_font) except Exception as", "the same reference from the return debug value. if ret_value", "return value is a container type (and call value is", "bp_view.Show() ############################################################################################### # View Delegates. class TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\" Delegate for", "isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context is not None: raise ValueError(\"Wrong value", "for func_context in func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return # @QtCore.Slot(str) def on_exclude_ea(self,", "on multi-thread data items @param thread_id: thread id to normalize", "call_value.reference_flink is not None: parsed_val_data = \"\" item_parsed_val_call = QtGui.QStandardItem(parsed_val_data)", "isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is not None: raise ValueError(\"Wrong value", "None and len(parsed_val_list) > 1: lines = [] for parsed_val", "is not None: ea = function.function_start if function.is_lib_func: ea =", "200) self.functionTreeView.setColumnWidth(1, 20) self.functionTreeView.setColumnWidth(2, 20) self.functionTreeView.setColumnWidth(3, 20) self.functionTreeView.setColumnWidth(4, 250) self.functionTreeView.setColumnWidth(5,", "# # if self.die_db.get_function_by_name(func_name) is None: # item_list_func = self._make_nonexec_function_time(func_name)", "not len(function_context_list) > 0: continue item_func_context_list = self._make_function_ea_item(function_context_list[0]) item_func_context_ea =", "\"Function View\", options=PluginForm.FORM_PERSIST) def OnCreate(self, form): \"\"\" Called when the", "thread_id \"\"\" root_item = self.functionModel.item(0, 0) rows = root_item.rowCount() thread_id", "is_function_item = index.data(role=DIE.UI.Function_Role) is_func_context_item = index.data(role=DIE.UI.FunctionContext_Role) is_value_item = index.data(role=DIE.UI.ParsedValueRole) if", "# if self.die_db.get_function_by_name(func_name) is None: # item_list_func = self._make_nonexec_function_time(func_name) #", "self.die_icons = DIE.UI.Die_Icons.get_die_icons() self.die_db = DIE.Lib.DIEDb.get_db() # Get parent widget", "ret_arg_type = \"VOID\" else: ret_arg_type = ret_arg.type # Add return", "parent) self.parent = parent def createEditor(self, parent, option, index): parsed_val_list", "index): parsed_val_list = index.data(role=DIE.UI.ParsedValuesRole) # Show combobox only if parsed_value", "self._add_model_arg_value(parent, nested_val_call, nested_val_ret, nested_val_call.name, nested_val_call.type, nest_depth+1) # If return value", "func_count_item = root_item.child(row, 1) func_count_item.setText(str(count)) ############################################################################################### # Highlight Items. def", "on_show_callgraph(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context is not", "self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) # Actions self.context_menu_param = None # Parameter to be", "header item_header = QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number of calls preformed to this", "to currently selected thread if thread_id == \"All Threads\": if", "%s\\n\" % ex) def clear_highlights(self): \"\"\" Clear all highlighted items", "indentation for argument types (for nested values) arg_ident = \"", "self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) # Actions self.context_menu_param = None # Parameter to", "Grid layout = QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView) self.parent.setLayout(layout) def OnClose(self, form):", "self.highligthed_items: if persistent_index.isValid(): item = self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white')) cur_font = item.font()", "is created \"\"\" self.value_view = DIE.UI.ValueViewEx.get_view() self.bp_handler = DIE.Lib.BpHandler.get_bp_handler() self.die_icons", "context current_call_values = self.die_db.get_call_values(function_context) current_ret_values = self.die_db.get_return_values(function_context) curret_ret_arg_value = self.die_db.get_return_arg_value(function_context)", "else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name) return #", "self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0, 200) self.functionTreeView.setColumnWidth(1, 20) self.functionTreeView.setColumnWidth(2, 20) self.functionTreeView.setColumnWidth(3,", "> 1: # If more the 1 item, show a", "self.die_db is not None: threads = self.die_db.get_thread_list() thread_id_list = []", "xrange(0, len(call_value.nested_values)): nested_val_call = self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret = None # Try", "row in xrange(0, rows): cur_item = root_item.child(row, 0) function =", "root_node.appendRow(item_list_func) # Add function contexts ea\\occurrences for the current function", "_QSortFilterProxyModel = QtGui.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly = QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop", "not parent.hasChildren(): self.highlight_item(parent) return row = item.row() column_num = parent.columnCount()", "class TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\" Delegate for parsed value viewing in the", "functionview visible @return: True if visible, otherwise False \"\"\" try:", "TreeView DoubleClicked Slot. @param index: QModelIndex object of the clicked", "item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if ret_value.derref_depth == 0:", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_nonexec_function_time(self, function_name):", "Delegate for parsed value viewing in the tree view \"\"\"", "self.functionModel.item(0, 0) rows = root_item.rowCount() thread_id = self.thread_id_combo.currentText() for row", "item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New Function\") model.setHorizontalHeaderItem(3,", "hex(ret_value.raw_value) if ret_value.nested_values or ret_value.reference_flink is not None: parsed_val_data =", "@param parent: @param call_value: @param ret_value: @param nest_depth: @return: \"\"\"", "data was successfully added to item, otherwise False \"\"\" try:", "QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView) self.parent.setLayout(layout) def OnClose(self, form): idaapi.msg(\"Closed\\n\") def isVisible(self):", "support filtering\\sorting on multi-thread data items @param thread_id: thread id", "= self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role) if parsed_vals is not None and", "self.functionModel.index(row, column, parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index = QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index) except Exception", "DIE.Lib.BpHandler import sark.ui class FunctionView(PluginForm): \"\"\" DIE Function View \"\"\"", "Details\", self.functionTreeView, triggered=lambda: self.on_value_detail(self.context_menu_param)) action_show_callgraph = QtWidgets.QAction(\"Show Call-Graph\", self.functionTreeView, triggered=lambda:", "= item.font() cur_font.setBold(False) item.setFont(cur_font) self.highligthed_items = [] except Exception as", "def itemDoubleClickSlot(self, index): \"\"\" TreeView DoubleClicked Slot. @param index: QModelIndex", "func_context in context_list: context_id = id(func_context) matched_items = self.functionModel.match(root_index, DIE.UI.ContextId_Role,", "ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent, None, nested_val_ret, nested_val_ret.name, nested_val_ret.type, nest_depth+1)", "if call_value.raw_value is not None: parsed_val_data = hex(call_value.raw_value) if len(call_value.nested_values)", "item.setData(current_thread_id, role=DIE.UI.ThreadId_Role) elif not current_thread_id in thread_data: item.setData(thread_data + current_thread_id,", "thread-ids (for example a item data value can be \"a123aa5672aa11112a\")", "self.highligthed_items = [] def Show(self): # Reset highlighted items self.highligthed_items", "= parent.rowCount() this_row_item = QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role) # Inherit thread", "index.data(role=DIE.UI.FunctionContext_Role) if func_context is not None: ea = func_context.calling_ea if", "Add a debug value @param parent: @param call_value: @param ret_value:", "None: if ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent, nested_val_call, nested_val_ret, nested_val_call.name,", "DIE Function View \"\"\" def __init__(self): super(FunctionView, self).__init__() self.value_view =", "= id(func_context) matched_items = self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id, -1, _MatchRecursive |", "Try to get the same member from the return debug", "and len(parsed_val_list) > 1: lines = [] for parsed_val in", "is a container type (and call value is not) elif", "\"\"\" def __init__(self, parent): QtWidgets.QStyledItemDelegate.__init__(self, parent) self.parent = parent def", "Call Value Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6, item_header) ###", "4, QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count, 5, QtGui.QStandardItem(arg_name)) parent.setChild(arg_count, 6, item_parsed_val_flag_call) parent.setChild(arg_count, 7,", "form_to_widget, use_qt5 if use_qt5: _QSortFilterProxyModel = QtCore.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchRecursive", "layout = QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView) self.parent.setLayout(layout) def OnClose(self, form): idaapi.msg(\"Closed\\n\")", "parsed_val_data = \"!MAX_DEREF!\" if call_value.raw_value is not None: parsed_val_data =", "object, Add its members to the module self._add_model_container_members(this_row_item, call_value, ret_value,", "is not idc.BADADDR: idc.Jump(ea) return True # @QtCore.Slot(QtCore.QPoint) def onCustomContextMenu(self,", "root_node.appendRow(item_list_func) def _make_model_headers(self, model): \"\"\" Set the model horizontal header", "@param item: table item \"\"\" try: if not item.index().isValid(): return", "hex(function_context.calling_ea)) item_func_context_ea = QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context),", "\"!MAX_DEREF!\" if ret_value.raw_value is not None: parsed_val_data = hex(ret_value.raw_value) if", "graph = nx.DiGraph() call_graph = self.die_db.get_call_graph_to(function_context) if not call_graph: idaapi.msg(\"No", "parent.rowCount() this_row_item = QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role) # Inherit thread data", "Build the function model. @param model: QStandardItemModel object \"\"\" model.clear()", "self.highligthed_items = [] except Exception as ex: idaapi.msg(\"Error while clearing", "ValueError(\"Wrong value sent to 'on_show_callgraph'\") graph = nx.DiGraph() call_graph =", "cur_item = root_item.child(row, 0) function = cur_item.data(role=DIE.UI.Function_Role) if function is", "networkx as nx from awesome.context import ignored import sark import", "the plugin form is created \"\"\" self.value_view = DIE.UI.ValueViewEx.get_view() self.bp_handler", "current_call_values[arg_index], current_ret_values[arg_index], current_arg.name, current_arg.type) except IndexError: break ret_arg = self.die_db.get_function_arg(function,", "self.functionTreeView.setColumnWidth(1, 20) self.functionTreeView.setColumnWidth(2, 20) self.functionTreeView.setColumnWidth(3, 20) self.functionTreeView.setColumnWidth(4, 250) self.functionTreeView.setColumnWidth(5, 100)", "parsed value viewing in the tree view \"\"\" def __init__(self,", "function is not None: count = 0 if thread_id is", "value sent to 'on_exclude_func_adrs'\") func_context_list = self.die_db.get_function_context_list(function) for func_context in", "a table item @param item: table item \"\"\" try: if", "object of the clicked tree index item. @return: \"\"\" function", "for the current function func_context_dict = self.die_db.get_function_context_dict(function) for function_context_ea in", "the model # for func_ea in idautils.Functions(): # func_name =", "item_func_context_ea = QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role)", "for parsed_val in parsed_val_list: line_txt = \"%d, %s, %s\" %", "\"\"\" # If call debug value is a reference if", "self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id, -1, _MatchRecursive | _MatchExactly) for index in", "column in xrange(0, column_num): if self.functionModel.hasIndex(row, column, parent.index()): cur_index =", "selected thread if thread_id == \"All Threads\": if not self.functionTreeView.model()", "= ret_arg.type # Add return argument self._add_model_arg_value(item_func_context, None, curret_ret_arg_value, \"ret_arg\",", "parent.hasChildren(): self.highlight_item(parent) return row = item.row() column_num = parent.columnCount() for", "= \"Occur %s\" % str(occur_num) item_func_context = QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5) item_func_context.setEditable(False)", "self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index = QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index) except Exception as ex: idaapi.msg(\"Error", "parsed_vals: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret = QtGui.QStandardItem(best_val.data) if is_guessed:", "function model. @param model: QStandardItemModel object \"\"\" model.clear() # Clear", "if is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: # If more", "item.data(role=DIE.UI.ThreadId_Role) if thread_data is None: item.setData(current_thread_id, role=DIE.UI.ThreadId_Role) elif not current_thread_id", "if ret_value.nested_values is not None: if ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(ret_value.nested_values[index])", "and ret_value.type == call_value.type: if ret_value.reference_flink is not None and", "call_value.type: if ret_value.nested_values is not None: if ret_value.nested_values: nested_val_ret =", "= \"\" item_parsed_val_ret = QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count, 0, this_row_item) parent.setChild(arg_count, 1,", "ref_val_ret = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, ref_val_call, ref_val_ret, ref_val_call.name, ref_val_call.type, nest_depth+1) #", "450) # Context menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) # Actions self.context_menu_param =", "item_header) def _make_thread_id_data(self, thread_id): \"\"\" Delimit thread_id data in order", "combo-box item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else: item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data =", "ref_val_ret, ref_val_call.name, ref_val_call.type, nest_depth+1) # If return debug value is", "item_header) ### Call Value Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6,", "%s\\n\" %ex) return False def _make_function_item(self, function): \"\"\" Build a", "True if visible, otherwise False \"\"\" try: return self.functionTreeView.isVisible() except:", "function_context_list = func_context_dict[function_context_ea] if not len(function_context_list) > 0: continue item_func_context_list", "QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index) except Exception as ex: idaapi.msg(\"Error while highlighting item", "item_list = [item_function, item_function_count] return item_list def _make_function_ea_item(self, function_context): \"\"\"", "if function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new = QtGui.QStandardItem() item_func_is_new.setEditable(False) if function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v)", "role=DIE.UI.ContextId_Role) # Used for module look-ups item_func_is_indirect = QtGui.QStandardItem() item_func_is_indirect.setEditable(False)", "None: self.context_menu_param = is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_func_context_item is not None:", "# root_node.appendRow(item_list_func) def _make_model_headers(self, model): \"\"\" Set the model horizontal", "False \"\"\" try: return self.functionTreeView.isVisible() except: return False def _model_builder(self,", "item_list_func = self._make_function_item(function) if function.is_lib_func: # Color library function for", "\"\"\" Find and highlight a function in current module @param", "None # Try to get the same member from the", "### Call Value Header item_header = QtGui.QStandardItem(\"Call Value\") item_header.setToolTip(\"Argument`s value", "according to currently selected thread if thread_id == \"All Threads\":", "is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question)", "model: the QStandardItemModel which headers should be set \"\"\" ###", "'on_exclude_func_adrs'\") if function.is_lib_func and function.lib_name is not None: self.bp_handler.add_module_exception(function.lib_name) return", "combo_box.addItems(lines) return combo_box def setEditorData(self, editor, index): editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False)", "self.die_icons = None self.die_db = None self.highligthed_items = [] def", "item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else: item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if ret_value.derref_depth", "not) elif ret_value is not None: if ret_value.reference_flink is not", "func_count_item.setText(str(count)) ############################################################################################### # Highlight Items. def highlight_item(self, item): \"\"\" Highlight", "# @QtCore.Slot(str) def on_value_detail(self, value): if not self.value_view.isVisible(): self.value_view.Show() self.value_view.find_value(value)", "tmp_item in item_list_func: tmp_item.setBackground(QtGui.QColor(184, 223, 220)) item_function = item_list_func[0] root_node.appendRow(item_list_func)", "'on_exclude_ea': %s. excpected dbFunction_Context\" % function_context.__class__) else: raise ValueError(\"Wrong value", "> 1: lines = [] for parsed_val in parsed_val_list: line_txt", "Function\") model.setHorizontalHeaderItem(3, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument", "function = cur_item.data(role=DIE.UI.Function_Role) if function is not None: count =", "index): editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False) # Singelton function_view = None def", "def onCustomContextMenu(self, point): index = self.functionTreeView.indexAt(point) is_function_item = index.data(role=DIE.UI.Function_Role) is_func_context_item", "if function.is_lib_func: # Color library function for tmp_item in item_list_func:", "slots action_exclude_func = QtWidgets.QAction(\"Exclude Function\", self.functionTreeView, triggered=lambda: self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs =", "is not) elif ret_value is not None: if ret_value.nested_values is", "the module self._add_model_container_members(this_row_item, call_value, ret_value, nest_depth) def _add_model_arg_ref(self, parent, call_value,", "\"\"\" Add a debug value @param parent: @param call_value: @param", "= \"%s+%s\" % (function_context.calling_func_name, hex(call_offset)) else: func_ea_txt = \"[%s]:%s\" %", "item_parsed_val_call = QtGui.QStandardItem() item_parsed_val_flag_ret = QtGui.QStandardItem() item_parsed_val_ret = QtGui.QStandardItem() #", "occurrences of it. if not index.data().startswith(\"Occur\"): continue item = self.functionModel.itemFromIndex(index)", "model.setHorizontalHeaderItem(3, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument Type\")", "in thread_id argument will be delimited by the _make_thread_id_data function", "index in matched_items: if not index.isValid(): continue # Do not", "* nest_depth arg_ident_type = arg_ident + arg_type item_parsed_val_flag_call = QtGui.QStandardItem()", "None: count = self.die_db.count_function_occurs(function) else: count = self.die_db.count_function_occurs(function, int(thread_id)) func_count_item", "is not None: if call_value.reference_flink is not None and not", "220)) item_function = item_list_func[0] root_node.appendRow(item_list_func) # Add function contexts ea\\occurrences", "for module look-ups item_func_is_indirect = QtGui.QStandardItem() item_func_is_indirect.setEditable(False) if function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v)", "self._make_function_item(function) if function.is_lib_func: # Color library function for tmp_item in", "self._add_model_arg_value(item_func_context, current_call_values[arg_index], current_ret_values[arg_index], current_arg.name, current_arg.type) except IndexError: break ret_arg =", "function contexts @param context_list: list of function contexts (of type", "delegate. if parsed_vals: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret = QtGui.QStandardItem(best_val.data)", "idaapi import PluginForm from sark.qt import QtGui, QtCore, QtWidgets, form_to_widget,", "import idaapi import idautils import idc from idaapi import PluginForm", "to the module self._add_model_container_members(this_row_item, call_value, ret_value, nest_depth) def _add_model_arg_ref(self, parent,", "nx.DiGraph() call_graph = self.die_db.get_call_graph_to(function_context) if not call_graph: idaapi.msg(\"No Execution Graph\")", "QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import DIE.UI.Die_Icons import DIE.UI.ValueViewEx import DIE.UI.ParserView import DIE.UI.BPView import", "arg_type, nest_depth=0): \"\"\" Add a debug value @param parent: @param", "None: parsed_vals = self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role) if parsed_vals is not", "item = self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white')) cur_font = item.font() cur_font.setBold(False) item.setFont(cur_font) self.highligthed_items", "idc.Jump(ea) return True # @QtCore.Slot(QtCore.QPoint) def onCustomContextMenu(self, point): index =", "to 'on_show_callgraph'\") graph = nx.DiGraph() call_graph = self.die_db.get_call_graph_to(function_context) if not", "= QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo) # Grid layout = QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar)", "function_context.thread_id) self._insert_thread_data(item_func_context_ea, function_context.thread_id) # Add function arguments to each context", "if function is not None: count = 0 if thread_id", "function contexts ea\\occurrences for the current function func_context_dict = self.die_db.get_function_context_dict(function)", "_make_func_occur_item(self, function_context, occur_num): \"\"\" Build a tree item for function", "return self.functionTreeView.isVisible() except: return False def _model_builder(self, model): \"\"\" Build", "self.highlight_item_row(item) return True except Exception as ex: idaapi.msg(\"Error while looking", "nested_val_ret = self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent, nested_val_call, nested_val_ret, nested_val_call.name, nested_val_call.type, nest_depth+1) #", "the model for function in self.die_db.get_functions(): item_list_func = self._make_function_item(function) if", "for thread in threads: thread_id_list.append(str(thread.thread_num)) self.thread_id_combo = QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change)", "to each context current_call_values = self.die_db.get_call_values(function_context) current_ret_values = self.die_db.get_return_values(function_context) curret_ret_arg_value", "a debug value @param parent: @param call_value: @param ret_value: @param", "Add its members to the module self._add_model_container_members(this_row_item, call_value, ret_value, nest_depth)", "to get the same reference from the return debug value.", "not None: parsed_val_data = \"\" item_parsed_val_call = QtGui.QStandardItem(parsed_val_data) # Get", "item_function.setEditable(False) item_list = [item_function, item_function_count] return item_list def _make_function_ea_item(self, function_context):", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_func_occur_item(self, function_context, occur_num):", "not None: if call_value.nested_values: for index in xrange(0, len(call_value.nested_values)): nested_val_call", "viewing in the tree view \"\"\" def __init__(self, parent): QtWidgets.QStyledItemDelegate.__init__(self,", "_make_function_item(self, function): \"\"\" Build a tree item for a function", "value on function call\") model.setHorizontalHeaderItem(7, item_header) ### Return Value Icon", "QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8, item_header) ### Return Value Header item_header = QtGui.QStandardItem(\"Return", "viewer = sark.ui.NXGraph(graph, \"Callgraph for {}\".format(function_name), handler=sark.ui.AddressNodeHandler()) viewer.Show() return #", "index: QModelIndex object of the clicked tree index item. @return:", "a reference (and call value is not) elif ret_value is", "QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent, None, nested_val_ret, nested_val_ret.name, nested_val_ret.type, nest_depth+1) def reset_function_count(self, thread_id=None):", "the function \"\"\" function_txt = \"%s\" % function.function_name item_function =", "item for function occurrence (level-2) @param function_context: a dbFunction_Context object", "threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel) def on_valueview_button(self): value_view = DIE.UI.ValueViewEx.get_view() value_view.Show() def on_pluginsview_button(self):", "and highlight a list of function contexts @param context_list: list", "reset_function_count(self, thread_id=None): \"\"\" Reset the function count and set the", "sark.Function(function_context.calling_ea).startEA if calling_function_start is not None: call_offset = function_context.calling_ea -", "%s, %s\" % (parsed_val.score, parsed_val.data, parsed_val.description) lines.append(line_txt) combo_box = QtWidgets.QComboBox(parent)", "combo-box item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else: item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data =", "[] thread_id_list.append(\"All Threads\") for thread in threads: thread_id_list.append(str(thread.thread_num)) self.thread_id_combo =", "except: return False def _model_builder(self, model): \"\"\" Build the function", "in item_list_func: tmp_item.setBackground(QtGui.QColor(184, 223, 220)) item_function = item_list_func[0] root_node.appendRow(item_list_func) #", "if self.functionModel.hasIndex(row, column, parent.index()): cur_index = self.functionModel.index(row, column, parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index))", "_MatchExactly = QtCore.Qt.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.PositionAtTop else: _QSortFilterProxyModel = QtGui.QSortFilterProxyModel", "self.functionTreeView, triggered=lambda: self.on_show_callgraph(self.context_menu_param)) # Function ContextMenu self.function_context_menu = QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func)", "argument self._add_model_arg_value(item_func_context, None, curret_ret_arg_value, \"ret_arg\", ret_arg_type) # Increment occurrence counter", "def setEditorData(self, editor, index): editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False) # Singelton function_view", "for a function name (for a non-executed function) @type: String", "call_value.raw_value is not None: parsed_val_data = hex(call_value.raw_value) if len(call_value.nested_values) >", "func_context_dict = self.die_db.get_function_context_dict(function) for function_context_ea in func_context_dict: function_context_list = func_context_dict[function_context_ea]", "tree item for a function name (for a non-executed function)", "context_id = id(func_context) matched_items = self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id, -1, _MatchRecursive", "single item @param item: module item \"\"\" try: item.setBackground(QtGui.QColor('yellow')) cur_font", "@QtCore.Slot(str) def on_exclude_func_adrs(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function", "if call_value is not None: if call_value.reference_flink is not None", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_nonexec_function_time(self,", "the clicked tree index item. @return: \"\"\" function = index.data(role=DIE.UI.Function_Role)", "data for ThreadId_Role \"\"\" return \"t%st\" % str(thread_id) def _insert_thread_data(self,", "= [] return PluginForm.Show(self, \"Function View\", options=PluginForm.FORM_PERSIST) def OnCreate(self, form):", "item_header = QtGui.QStandardItem(\"Return Value\") item_header.setToolTip(\"Argument`s value on function return\") model.setHorizontalHeaderItem(9,", "on_exclude_ea(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context is not", "def _make_nonexec_function_time(self, function_name): \"\"\" Build a tree item for a", "thread_data = item.data(role=DIE.UI.ThreadId_Role) if thread_data is None: item.setData(current_thread_id, role=DIE.UI.ThreadId_Role) elif", "item_header.setToolTip(\"Argument Type\") model.setHorizontalHeaderItem(4, item_header) ### New Function Header item_header =", "% function.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") if", "= QtWidgets.QAction(\"Exclude Function\", self.functionTreeView, triggered=lambda: self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs = QtWidgets.QAction(\"Exclude All", "Exception as ex: idaapi.msg(\"Error while inserting thread data: %s\\n\" %ex)", "count = self.die_db.count_function_occurs(function, int(thread_id)) func_count_item = root_item.child(row, 1) func_count_item.setText(str(count)) ###############################################################################################", "current_thread_id, role=DIE.UI.ThreadId_Role) return True except Exception as ex: idaapi.msg(\"Error while", "tree item for a function_ea node (level-1) @param function_context: a", "count according to currently selected thread if thread_id == \"All", "nest_depth+1) # If return value is a container type (and", "None: self.bp_handler.add_module_exception(function.lib_name) return # @QtCore.Slot(str) def on_value_detail(self, value): if not", "item_header.setToolTip(\"Number of calls preformed to this function\") model.setHorizontalHeaderItem(1, item_header) ###", "None and not ret_value.is_definitely_parsed: ref_val_ret = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, ref_val_call, ref_val_ret,", "item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for", "return\") model.setHorizontalHeaderItem(9, item_header) def _make_thread_id_data(self, thread_id): \"\"\" Delimit thread_id data", "= QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs) # Function ea ContextMenu self.ea_context_menu", "action_exclude_ea = QtWidgets.QAction(\"Exclude Address\", self.functionTreeView, triggered=lambda: self.on_exclude_ea(self.context_menu_param)) action_exclude_library = QtWidgets.QAction(\"Exclude", "form): idaapi.msg(\"Closed\\n\") def isVisible(self): \"\"\" Is functionview visible @return: True", "QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New Function\") model.setHorizontalHeaderItem(3, item_header) ### Indirect Header item_header =", "highlight the entire row containing a table item @param item:", "is_value_item is not None: self.context_menu_param = is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) # @QtCore.Slot(str)", "count = self.die_db.count_function_occurs(function) else: count = self.die_db.count_function_occurs(function, int(thread_id)) func_count_item =", "= None def initialize(): global function_view function_view = FunctionView() def", "return PluginForm.Show(self, \"Function View\", options=PluginForm.FORM_PERSIST) def OnCreate(self, form): \"\"\" Called", "def on_value_detail(self, value): if not self.value_view.isVisible(): self.value_view.Show() self.value_view.find_value(value) return def", "= index.data(role=DIE.UI.ParsedValuesRole) # Show combobox only if parsed_value as two", "current_ret_values[arg_index], current_arg.name, current_arg.type) except IndexError: break ret_arg = self.die_db.get_function_arg(function, -1)", "_insert_thread_data(self, item, thread_id): \"\"\" Insert thread_id data into a model", "[item_func_context, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()]", "container type (struct\\union\\etc) if call_value is not None and call_value.nested_values", "the model root_node = model.invisibleRootItem() self._make_model_headers(model) if self.die_db is None:", "found in thread_id argument will be delimited by the _make_thread_id_data", "= self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if len(parsed_vals)", "Function name \"\"\" self.clear_highlights() matched_items = self.functionModel.findItems(function_name) for item in", "= index.data(role=DIE.UI.ParsedValueRole) if is_function_item is not None: self.context_menu_param = is_function_item", "None: parent = item if not parent.hasChildren(): self.highlight_item(parent) return row", "QtGui.QStandardItem()] return item_list def _make_func_occur_item(self, function_context, occur_num): \"\"\" Build a", "call_value.reference_flink is not None and not call_value.is_definitely_parsed: ref_val_call = self.die_db.get_dbg_value(call_value.reference_flink)", "to the model for function in self.die_db.get_functions(): item_list_func = self._make_function_item(function)", "same reference from the return debug value. if ret_value is", "= QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function Name\") model.setHorizontalHeaderItem(0, item_header) ### Call number header", "= QtGui.QStandardItem() # Get Call Value if call_value is not", "item): \"\"\" Highlight a single item @param item: module item", "function_count = self.die_db.count_function_occurs(function) item_function_count = QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False) item_function.setEditable(False) item_list =", "\"%s+%s\" % (function_context.calling_func_name, hex(call_offset)) else: func_ea_txt = \"[%s]:%s\" % (function_context.calling_func_name,", "############################################################################################### # Slots. # @QtCore.Slot(QtCore.QModelIndex) def itemDoubleClickSlot(self, index): \"\"\" TreeView", "# View Delegates. class TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\" Delegate for parsed value", "ret_value.type == call_value.type: if ret_value.reference_flink is not None and not", "a tree item for a function name (for a non-executed", "\"\"\" model.clear() # Clear the model root_node = model.invisibleRootItem() self._make_model_headers(model)", "import PluginForm from sark.qt import QtGui, QtCore, QtWidgets, form_to_widget, use_qt5", "self.value_view.find_value(value) return def on_thread_combobox_change(self, thread_id): self.reset_function_count(thread_id) # reset function count", "for {}\".format(function_name), handler=sark.ui.AddressNodeHandler()) viewer.Show() return # @QtCore.Slot(str) def on_exclude_library(self, function):", "If call debug value is a reference if call_value is", "QtGui.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly = QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop", "self.highligthed_items = [] return PluginForm.Show(self, \"Function View\", options=PluginForm.FORM_PERSIST) def OnCreate(self,", "QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5) item_func_context.setEditable(False) item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for", "Insert thread_id data into a model item. The value found", "# If return debug value is a reference (and call", "1 item, show a combo-box item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else: item_parsed_val_ret.setData(parsed_vals[0],", "= self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, None, ref_val, ref_val.name, ref_val.type, nest_depth+1) def _add_model_container_members(self,", "(unique) child-item thread-ids (for example a item data value can", "Is functionview visible @return: True if visible, otherwise False \"\"\"", "self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return # @QtCore.Slot(str) def on_exclude_ea(self, function_context): if not isinstance(function_context,", "a combo-box item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else: item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data", "None: threads = self.die_db.get_thread_list() thread_id_list = [] thread_id_list.append(\"All Threads\") for", "@return: \"\"\" item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_name) item_function_count = QtGui.QStandardItem(\"0\") item_function_count.setEditable(False)", "# Slots. # @QtCore.Slot(QtCore.QModelIndex) def itemDoubleClickSlot(self, index): \"\"\" TreeView DoubleClicked", "arg_ident + arg_type item_parsed_val_flag_call = QtGui.QStandardItem() item_parsed_val_call = QtGui.QStandardItem() item_parsed_val_flag_ret", "self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo) # Grid layout = QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView) self.parent.setLayout(layout)", "\" \" * nest_depth arg_ident_type = arg_ident + arg_type item_parsed_val_flag_call", "ea = function.function_start if function.is_lib_func: ea = function.proto_ea if ea", "item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument Type\") model.setHorizontalHeaderItem(4,", "normalize @return: a normalized string of the thread_id to be", "should be set \"\"\" ### Function Header item_header = QtGui.QStandardItem(\"Function\")", "not None and ret_value.type == call_value.type: if ret_value.reference_flink is not", "len(call_value.nested_values)): nested_val_call = self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret = None # Try to", "and len(parsed_vals) > 0: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call =", "role=DIE.UI.RetValue_Role) # If len(parsed_vals)>1 create a combobox delegate. if parsed_vals:", "model.setHorizontalHeaderItem(6, item_header) ### Call Value Header item_header = QtGui.QStandardItem(\"Call Value\")", "thread_id == \"All Threads\": if not self.functionTreeView.model() is self.functionModel: self.functionTreeView.setModel(self.functionModel)", "QtGui.QStandardItemModel() self.functionTreeView = QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True) delegate = TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate)", "parsed_vals is not None and len(parsed_vals) > 0: is_guessed, best_val", "\"NULL\" if ret_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\" if ret_value.raw_value", "ret_value is not None: parsed_vals = self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role) #", "# Used for module look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role) item_list = [item_func_context,", "= item.row() column_num = parent.columnCount() for column in xrange(0, column_num):", "to 'on_show_callgraph': %s. excpected dbFunction_Context\" % function_context.__class__) else: raise ValueError(\"Wrong", "options=PluginForm.FORM_PERSIST) def OnCreate(self, form): \"\"\" Called when the plugin form", "Color library function for tmp_item in item_list_func: tmp_item.setBackground(QtGui.QColor(184, 223, 220))", "thread_id to be used sa data for ThreadId_Role \"\"\" return", "from parent # Set indentation for argument types (for nested", "Color library function # for tmp_item in item_list_func: # tmp_item.setBackground(QtGui.QColor(255,", "@QtCore.Slot(str) def on_exclude_ea(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context", "ret_value is not None: if ret_value.reference_flink is not None and", "ret_arg = self.die_db.get_function_arg(function, -1) if ret_arg is None: ret_arg_type =", "function occurrence (level-2) @param function_context: a dbFunction_Context object @param occur_num:", "dbFunction_Context object @param occur_num: occurrence number @return: QStandradItemModel item for", "parent, call_value, ret_value, nest_depth=0): \"\"\" Add a reference value to", "<filename>DIE/UI/FunctionViewEx.py<gh_stars>1-10 import networkx as nx from awesome.context import ignored import", "hidden_threads = \".*\" + self._make_thread_id_data(thread_id) + \".*\" threadProxyModel = _QSortFilterProxyModel()", "function = index.data(role=DIE.UI.Function_Role) if function is not None: ea =", "@param function_name: Function name \"\"\" self.clear_highlights() matched_items = self.functionModel.findItems(function_name) for", "highlighting item: %s\\n\" %ex) def highlight_item_row(self, item): \"\"\" highlight the", "@return: \"\"\" # If call debug value is a reference", "None, nested_val_ret, nested_val_ret.name, nested_val_ret.type, nest_depth+1) def reset_function_count(self, thread_id=None): \"\"\" Reset", "\"\"\" self.clear_highlights() matched_items = self.functionModel.findItems(function_name) for item in matched_items: self.functionTreeView.expand(item.index())", "0, 0, 127)) # # root_node.appendRow(item_list_func) def _make_model_headers(self, model): \"\"\"", "ignored import sark import idaapi import idautils import idc from", "a container type (struct\\union\\etc) if call_value is not None and", "up function context in FunctionView: %s\\n\" % ex) return False", "== 0: parsed_val_data = \"!MAX_DEREF!\" if call_value.raw_value is not None:", "func_context_list = self.die_db.get_function_context_list(function) for func_context in func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return #", "current function func_context_dict = self.die_db.get_function_context_dict(function) for function_context_ea in func_context_dict: function_context_list", "############################################################################################### # Find Items. def find_function(self, function_name): \"\"\" Find and", "not None: if ret_value.nested_values is not None: if ret_value.nested_values: for", "function call\") model.setHorizontalHeaderItem(7, item_header) ### Return Value Icon Header item_header", "return \"t%st\" % str(thread_id) def _insert_thread_data(self, item, thread_id): \"\"\" Insert", "len(function_context_list) > 0: continue item_func_context_list = self._make_function_ea_item(function_context_list[0]) item_func_context_ea = item_func_context_list[0]", "\"a123aa5672aa11112a\") for threads 123, 5672 and 111112 @param item: the", "if not len(function_context_list) > 0: continue item_func_context_list = self._make_function_ea_item(function_context_list[0]) item_func_context_ea", "return for func_context in context_list: context_id = id(func_context) matched_items =", "= root_item.child(row, 0) function = cur_item.data(role=DIE.UI.Function_Role) if function is not", "ref_val_ret = None # Try to get the same reference", "@QtCore.Slot(str) def on_value_detail(self, value): if not self.value_view.isVisible(): self.value_view.Show() self.value_view.find_value(value) return", "break ret_arg = self.die_db.get_function_arg(function, -1) if ret_arg is None: ret_arg_type", "\"\"\" Build a tree item for a function name (level-0)", "a tree item for function occurrence (level-2) @param function_context: a", "func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return # @QtCore.Slot(str) def on_exclude_ea(self, function_context): if not", "def reset_function_count(self, thread_id=None): \"\"\" Reset the function count and set", "self.functionTreeView.setColumnWidth(6, 20) self.functionTreeView.setColumnWidth(7, 450) self.functionTreeView.setColumnWidth(8, 20) self.functionTreeView.setColumnWidth(9, 450) # Context", "function_name): \"\"\" Find and highlight a function in current module", "is None: return # Add db functions to the model", "row containing a table item @param item: table item \"\"\"", "try: self.functionTreeView.collapseAll() for persistent_index in self.highligthed_items: if persistent_index.isValid(): item =", "item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module look-ups item_func_is_indirect = QtGui.QStandardItem()", "function context \"\"\" calling_function_start = None with ignored(sark.exceptions.SarkNoFunction): calling_function_start =", "Try to get the same reference from the return debug", "self.functionTreeView = QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True) delegate = TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot)", "for the function occurrence \"\"\" func_occur_txt = \"Occur %s\" %", "cur_font.setBold(False) item.setFont(cur_font) self.highligthed_items = [] except Exception as ex: idaapi.msg(\"Error", "value_view = DIE.UI.ValueViewEx.get_view() value_view.Show() def on_pluginsview_button(self): plugins_view = DIE.UI.ParserView.get_view() plugins_view.Show()", "setEditorData(self, editor, index): editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False) # Singelton function_view =", "(level-2) @param function_context: a dbFunction_Context object @param occur_num: occurrence number", "to 'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return # @QtCore.Slot(str) def on_show_callgraph(self, function_context): if", "Indirect Header item_header = QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect Call\") model.setHorizontalHeaderItem(2, item_header) ###", "return hidden_threads = \".*\" + self._make_thread_id_data(thread_id) + \".*\" threadProxyModel =", "\"\" item_parsed_val_call = QtGui.QStandardItem(parsed_val_data) # Get return value if ret_value", "normalized string of the thread_id to be used sa data", "import DIE.UI.ParserView import DIE.UI.BPView import DIE.Lib.IDAConnector import DIE.Lib.DIEDb import DIE.Lib.BpHandler", "value will then be appended to a string of concatenated", "a item data value can be \"a123aa5672aa11112a\") for threads 123,", "items. if parsed_val_list is not None and len(parsed_val_list) > 1:", "= \"%d, %s, %s\" % (parsed_val.score, parsed_val.data, parsed_val.description) lines.append(line_txt) combo_box", "and not ret_value.is_definitely_parsed: ref_val = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, None, ref_val, ref_val.name,", "contexts (of type dbFunction_Context) \"\"\" try: self.clear_highlights() root_index = self.functionModel.index(0,", "ret_value, nest_depth) # If current object is a container object,", "= QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6, item_header) ### Call Value Header item_header =", "thread_data is None: item.setData(current_thread_id, role=DIE.UI.ThreadId_Role) elif not current_thread_id in thread_data:", "### Function Header item_header = QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function Name\") model.setHorizontalHeaderItem(0, item_header)", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _add_model_arg_value(self, parent,", "value sent to 'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return # @QtCore.Slot(str) def on_show_callgraph(self,", "False def _model_builder(self, model): \"\"\" Build the function model. @param", "the thread_id to be used sa data for ThreadId_Role \"\"\"", "not current_thread_id in thread_data: item.setData(thread_data + current_thread_id, role=DIE.UI.ThreadId_Role) return True", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _add_model_arg_value(self, parent, call_value, ret_value,", "Get parent widget self.parent = form_to_widget(form) self.functionModel = QtGui.QStandardItemModel() self.functionTreeView", "nest_depth=0): \"\"\" Add container members to module @param parent: @param", "in thread_data: item.setData(thread_data + current_thread_id, role=DIE.UI.ThreadId_Role) return True except Exception", "\"\"\" Build a tree item for function occurrence (level-2) @param", "if call_value is not None and call_value.nested_values is not None:", "root_node = model.invisibleRootItem() self._make_model_headers(model) if self.die_db is None: return #", "len(parsed_vals)>1 create a combobox delegate. if parsed_vals: is_guessed, best_val =", "highlight \"ea root\" items, only occurrences of it. if not", "None and not call_value.is_definitely_parsed: ref_val_call = self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret = None", "currently selected thread_id @param thread_id: currently selected thread_id \"\"\" root_item", "is not None: count = 0 if thread_id is None:", "### Indirect Header item_header = QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect Call\") model.setHorizontalHeaderItem(2, item_header)", "func_name = DIE.Lib.IDAConnector.get_function_name(func_ea) # # if self.die_db.get_function_by_name(func_name) is None: #", "self.functionTreeView.isVisible() except: return False def _model_builder(self, model): \"\"\" Build the", "%ex) return False def _make_function_item(self, function): \"\"\" Build a tree", "QtGui.QStandardItem(self.die_icons.icon_function, function_txt) item_function.setData(function, role=DIE.UI.Function_Role) function_count = self.die_db.count_function_occurs(function) item_function_count = QtGui.QStandardItem(str(function_count))", "DIE.Lib.DIEDb.dbFunction): if function is not None: raise ValueError(\"Wrong value sent", "thread_id number @return: True if thread data was successfully added", "View\", options=PluginForm.FORM_PERSIST) def OnCreate(self, form): \"\"\" Called when the plugin", "preformed to this function\") model.setHorizontalHeaderItem(1, item_header) ### Indirect Header item_header", "item_list_func: # tmp_item.setBackground(QtGui.QColor(255, 0, 0, 127)) # # root_node.appendRow(item_list_func) def", "(of type dbFunction_Context) \"\"\" try: self.clear_highlights() root_index = self.functionModel.index(0, 0)", "%s. excpected dbFunction_Context\" % function_context.__class__) else: raise ValueError(\"Wrong value sent", "self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs) # Function ea ContextMenu self.ea_context_menu = QtWidgets.QMenu(self.functionTreeView)", "Function Header item_header = QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function Name\") model.setHorizontalHeaderItem(0, item_header) ###", "model.setHorizontalHeaderItem(1, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect Call\")", "# Toolbar self.function_toolbar = QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo) # Grid layout", "= QtGui.QStandardItem(\"Call Value\") item_header.setToolTip(\"Argument`s value on function call\") model.setHorizontalHeaderItem(7, item_header)", "self._add_model_arg_value(item_func_context, None, curret_ret_arg_value, \"ret_arg\", ret_arg_type) # Increment occurrence counter occurrence_num", "index): \"\"\" TreeView DoubleClicked Slot. @param index: QModelIndex object of", "plugins_view = DIE.UI.ParserView.get_view() plugins_view.Show() def on_bpview_button(self): bp_view = DIE.UI.BPView.get_view() bp_view.Show()", "= None self.die_icons = None self.die_db = None self.highligthed_items =", "item_list = [item_function, item_function_count, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "combo_box = QtWidgets.QComboBox(parent) combo_box.addItems(lines) return combo_box def setEditorData(self, editor, index):", "= item_list_func[0] root_node.appendRow(item_list_func) # Add function contexts ea\\occurrences for the", "return # @QtCore.Slot(str) def on_exclude_ea(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context):", "when the plugin form is created \"\"\" self.value_view = DIE.UI.ValueViewEx.get_view()", "QtGui.QStandardItem()) parent.setChild(arg_count, 4, QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count, 5, QtGui.QStandardItem(arg_name)) parent.setChild(arg_count, 6, item_parsed_val_flag_call)", "idaapi.msg(\"Error while clearing highlights: %s\\n\" % ex) ############################################################################################### # Find", "= QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect Call\") model.setHorizontalHeaderItem(2, item_header) ### Indirect Header item_header", "= index.data(role=DIE.UI.FunctionContext_Role) if func_context is not None: ea = func_context.calling_ea", "@return: QStandradItemModel item for the function occurrence \"\"\" func_occur_txt =", "= DIE.Lib.BpHandler.get_bp_handler() self.die_icons = DIE.UI.Die_Icons.get_die_icons() self.die_db = DIE.Lib.DIEDb.get_db() # Get", "item_header.setToolTip(\"New Function\") model.setHorizontalHeaderItem(3, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"Type\")", "model): \"\"\" Set the model horizontal header data @param model:", "to the model # for func_ea in idautils.Functions(): # func_name", "ret_value.reference_flink is not None: parsed_val_data = \"\" item_parsed_val_ret = QtGui.QStandardItem(parsed_val_data)", "self.highlight_item(parent) return row = item.row() column_num = parent.columnCount() for column", "createEditor(self, parent, option, index): parsed_val_list = index.data(role=DIE.UI.ParsedValuesRole) # Show combobox", "visible, otherwise False \"\"\" try: return self.functionTreeView.isVisible() except: return False", "item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role) item_list = [item_func_context, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel) def on_valueview_button(self): value_view = DIE.UI.ValueViewEx.get_view() value_view.Show() def", "not None: parsed_vals = self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role) # If len(parsed_vals)>1", "the QStandardItemModel which headers should be set \"\"\" ### Function", "# Increment occurrence counter occurrence_num += 1 # Add non-executed", "1 # Add non-executed function to the model # for", "QtGui.QStandardItem() item_func_is_indirect.setEditable(False) if function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new = QtGui.QStandardItem() item_func_is_new.setEditable(False) if", "except Exception as ex: idaapi.msg(\"Error while clearing highlights: %s\\n\" %", "Header item_header = QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New Function\") model.setHorizontalHeaderItem(3, item_header) ### Indirect", "item_header.setToolTip(\"Function Name\") model.setHorizontalHeaderItem(0, item_header) ### Call number header item_header =", "item_function_count, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return", "@return: \"\"\" arg_count = parent.rowCount() this_row_item = QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role)", "use_qt5 if use_qt5: _QSortFilterProxyModel = QtCore.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchRecursive _MatchExactly", "item.font() cur_font.setBold(True) item.setFont(cur_font) except Exception as ex: idaapi.msg(\"Error while highlighting", "self.die_db.count_function_occurs(function) else: count = self.die_db.count_function_occurs(function, int(thread_id)) func_count_item = root_item.child(row, 1)", "View Delegates. class TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\" Delegate for parsed value viewing", "parent # Set indentation for argument types (for nested values)", "lines.append(line_txt) combo_box = QtWidgets.QComboBox(parent) combo_box.addItems(lines) return combo_box def setEditorData(self, editor,", "more the 1 item, show a combo-box item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more)", "\") # Toolbar self.function_toolbar = QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo) # Grid", "ea is not idc.BADADDR: idc.Jump(ea) return True func_context = index.data(role=DIE.UI.FunctionContext_Role)", "if not self.value_view.isVisible(): self.value_view.Show() self.value_view.find_value(value) return def on_thread_combobox_change(self, thread_id): self.reset_function_count(thread_id)", "DIE.UI.ValueViewEx.get_view() self.bp_handler = DIE.Lib.BpHandler.get_bp_handler() self.die_icons = DIE.UI.Die_Icons.get_die_icons() self.die_db = DIE.Lib.DIEDb.get_db()", "@param thread_id: thread_id number @return: True if thread data was", "if function_context is not None: raise ValueError(\"Wrong value sent to", "data into a model item. The value found in thread_id", "curret_ret_arg_value, \"ret_arg\", ret_arg_type) # Increment occurrence counter occurrence_num += 1", "self.functionTreeView.scrollTo(index, _PositionAtTop) self.highlight_item_row(item) return True except Exception as ex: idaapi.msg(\"Error", "self.functionTreeView.indexAt(point) is_function_item = index.data(role=DIE.UI.Function_Role) is_func_context_item = index.data(role=DIE.UI.FunctionContext_Role) is_value_item = index.data(role=DIE.UI.ParsedValueRole)", "arguments to each context current_call_values = self.die_db.get_call_values(function_context) current_ret_values = self.die_db.get_return_values(function_context)", "return False def _model_builder(self, model): \"\"\" Build the function model.", "= QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument Name\") model.setHorizontalHeaderItem(5, item_header) ### Call Value Icon", "function.is_lib_func: # Color library function for tmp_item in item_list_func: tmp_item.setBackground(QtGui.QColor(184,", "# Used for module look-ups item_func_is_indirect = QtGui.QStandardItem() item_func_is_indirect.setEditable(False) if", "and highlight a function in current module @param function_name: Function", "_make_thread_id_data function (e.g: thread_id 123 will become 't123t') the delimited", "function\") model.setHorizontalHeaderItem(1, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect", "value_view.Show() def on_pluginsview_button(self): plugins_view = DIE.UI.ParserView.get_view() plugins_view.Show() def on_bpview_button(self): bp_view", "= item.font() cur_font.setBold(True) item.setFont(cur_font) except Exception as ex: idaapi.msg(\"Error while", "editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False) # Singelton function_view = None def initialize(): global", "show a combo-box item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else: item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else:", "filtering\\sorting on multi-thread data items @param thread_id: thread id to", "# # if function.is_lib_func: # Color library function # for", "### Indirect Header item_header = QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New Function\") model.setHorizontalHeaderItem(3, item_header)", "Address\", self.functionTreeView, triggered=lambda: self.on_exclude_ea(self.context_menu_param)) action_exclude_library = QtWidgets.QAction(\"Exclude Library\", self.functionTreeView, triggered=lambda:", "\"\"\" Highlight a single item @param item: module item \"\"\"", "\"\" item_parsed_val_ret = QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count, 0, this_row_item) parent.setChild(arg_count, 1, QtGui.QStandardItem())", "DIE.UI.ContextId_Role, context_id, -1, _MatchRecursive | _MatchExactly) for index in matched_items:", "function.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") if function.is_lib_func", "will then be appended to a string of concatenated (unique)", "thread_id): \"\"\" Insert thread_id data into a model item. The", "function in current module @param function_name: Function name \"\"\" self.clear_highlights()", "value is not) elif ret_value is not None: if ret_value.reference_flink", "triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea = QtWidgets.QAction(\"Exclude Address\", self.functionTreeView, triggered=lambda: self.on_exclude_ea(self.context_menu_param)) action_exclude_library", "self.on_show_callgraph(self.context_menu_param)) # Function ContextMenu self.function_context_menu = QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs)", "None: self.context_menu_param = is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_value_item is not None:", "QStandradItemModel item for the function occurrence \"\"\" func_occur_txt = \"Occur", "and call_value.nested_values is not None: if call_value.nested_values: for index in", "function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new = QtGui.QStandardItem() item_func_is_new.setEditable(False) if function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v) item_list", "### New Function Header item_header = QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument Name\") model.setHorizontalHeaderItem(5,", "function.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name) return", "item_header) ### Call number header item_header = QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number of", "DIE.UI.Die_Icons import DIE.UI.ValueViewEx import DIE.UI.ParserView import DIE.UI.BPView import DIE.Lib.IDAConnector import", "= DIE.UI.ParserView.get_view() plugins_view.Show() def on_bpview_button(self): bp_view = DIE.UI.BPView.get_view() bp_view.Show() ###############################################################################################", "self.thread_id_combo = QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label = QtWidgets.QLabel(\"Thread: \") #", "(function_context.calling_func_name, hex(function_context.calling_ea)) item_func_context_ea = QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role)", "dbFunction_Context object @return: QStandradItemModel item for the function context \"\"\"", "with ignored(sark.exceptions.SarkNoFunction): calling_function_start = sark.Function(function_context.calling_ea).startEA if calling_function_start is not None:", "IndexError: break ret_arg = self.die_db.get_function_arg(function, -1) if ret_arg is None:", "if not index.data().startswith(\"Occur\"): continue item = self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index, _PositionAtTop)", "highlighted items @return: \"\"\" try: self.functionTreeView.collapseAll() for persistent_index in self.highligthed_items:", "self._insert_thread_data(item_function, function_context.thread_id) self._insert_thread_data(item_func_context_ea, function_context.thread_id) # Add function arguments to each", "if call_value.reference_flink is not None and not call_value.is_definitely_parsed: ref_val_call =", "item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect Call\") model.setHorizontalHeaderItem(2,", "True except Exception as ex: idaapi.msg(\"Error while inserting thread data:", "thread_id argument will be delimited by the _make_thread_id_data function (e.g:", "idaapi import idautils import idc from idaapi import PluginForm from", "item.setData(thread_data + current_thread_id, role=DIE.UI.ThreadId_Role) return True except Exception as ex:", "== call_value.type: if ret_value.reference_flink is not None and not ret_value.is_definitely_parsed:", "def _model_builder(self, model): \"\"\" Build the function model. @param model:", "the function count and set the count according to currently", "not ret_value.is_definitely_parsed: ref_val_ret = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, ref_val_call, ref_val_ret, ref_val_call.name, ref_val_call.type,", "QtCore.Qt.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.PositionAtTop else: _QSortFilterProxyModel = QtGui.QSortFilterProxyModel _MatchRecursive =", "for function occurrence (level-2) @param function_context: a dbFunction_Context object @param", "onCustomContextMenu(self, point): index = self.functionTreeView.indexAt(point) is_function_item = index.data(role=DIE.UI.Function_Role) is_func_context_item =", "_PositionAtTop = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import DIE.UI.Die_Icons import DIE.UI.ValueViewEx import DIE.UI.ParserView import", "item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_txt) item_function.setData(function, role=DIE.UI.Function_Role) function_count = self.die_db.count_function_occurs(function) item_function_count", "Get return value if ret_value is not None: parsed_vals =", "= self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent, None, nested_val_ret, nested_val_ret.name, nested_val_ret.type, nest_depth+1) def reset_function_count(self,", "and not call_value.is_definitely_parsed: ref_val_call = self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret = None #", "is not None: parsed_val_data = \"\" item_parsed_val_call = QtGui.QStandardItem(parsed_val_data) #", "If more the 1 item, show a combo-box item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole)", "number header item_header = QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number of calls preformed to", "\"\"\" function_txt = \"%s\" % function.function_name item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_txt)", "item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id),", "parsed_vals = self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role) # If len(parsed_vals)>1 create a", "Reset the function count and set the count according to", "if ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent, nested_val_call, nested_val_ret, nested_val_call.name, nested_val_call.type,", "arg_count = parent.rowCount() this_row_item = QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role) # Inherit", "sent to 'on_exclude_ea'\") self.bp_handler.add_bp_ea_exception(function_context.calling_ea) return # @QtCore.Slot(str) def on_show_callgraph(self, function_context):", "FunctionView: %s\\n\" % ex) return False ############################################################################################### # Slots. #", "return True except Exception as ex: idaapi.msg(\"Error while inserting thread", "= QtGui.QStandardItem() item_parsed_val_flag_ret = QtGui.QStandardItem() item_parsed_val_ret = QtGui.QStandardItem() # Get", "None self.die_db = None self.highligthed_items = [] def Show(self): #", "223, 220)) item_function = item_list_func[0] root_node.appendRow(item_list_func) # Add function contexts", "123, 5672 and 111112 @param item: the model item to", "in the tree view \"\"\" def __init__(self, parent): QtWidgets.QStyledItemDelegate.__init__(self, parent)", "else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") if function.is_lib_func and", "in idautils.Functions(): # func_name = DIE.Lib.IDAConnector.get_function_name(func_ea) # # if self.die_db.get_function_by_name(func_name)", "### Call number header item_header = QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number of calls", "return row = item.row() column_num = parent.columnCount() for column in", "option, index): parsed_val_list = index.data(role=DIE.UI.ParsedValuesRole) # Show combobox only if", "itemDoubleClickSlot(self, index): \"\"\" TreeView DoubleClicked Slot. @param index: QModelIndex object", "ValueError(\"Wrong value sent to 'on_show_callgraph': %s. excpected dbFunction_Context\" % function_context.__class__)", "parsed_val_data = hex(call_value.raw_value) if len(call_value.nested_values) > 0 or call_value.reference_flink is", "'on_exclude_func_adrs': %s. excpected dbFunction_Context\" % function.__class__) else: raise ValueError(\"Wrong value", "item in matched_items: self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(), _PositionAtTop) self.highlight_item_row(item) def find_context_list(self, context_list):", "\"\"\" Delimit thread_id data in order to support filtering\\sorting on", "idaapi.msg(\"Error while looking up function context in FunctionView: %s\\n\" %", "### Return Value Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8, item_header)", "@QtCore.Slot(QtCore.QPoint) def onCustomContextMenu(self, point): index = self.functionTreeView.indexAt(point) is_function_item = index.data(role=DIE.UI.Function_Role)", "QtWidgets.QAction(\"Exclude Function\", self.functionTreeView, triggered=lambda: self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs = QtWidgets.QAction(\"Exclude All Function", "+= 1 # Add non-executed function to the model #", "model.setHorizontalHeaderItem(7, item_header) ### Return Value Icon Header item_header = QtGui.QStandardItem(\"\")", "QtGui.QStandardItem() # Get Call Value if call_value is not None:", "self.on_exclude_ea(self.context_menu_param)) action_exclude_library = QtWidgets.QAction(\"Exclude Library\", self.functionTreeView, triggered=lambda: self.on_exclude_library(self.context_menu_param)) action_value_detail =", "if len(call_value.nested_values) > 0 or call_value.reference_flink is not None: parsed_val_data", "call_value: @param ret_value: @param nest_depth: @return: \"\"\" # If call", "None: ea = func_context.calling_ea if ea is not None and", "except Exception as ex: idaapi.msg(\"Error while looking up function context", "action_show_callgraph = QtWidgets.QAction(\"Show Call-Graph\", self.functionTreeView, triggered=lambda: self.on_show_callgraph(self.context_menu_param)) # Function ContextMenu", "item_parsed_val_flag_ret = QtGui.QStandardItem() item_parsed_val_ret = QtGui.QStandardItem() # Get Call Value", "if thread data was successfully added to item, otherwise False", "= self.die_db.get_function_name(function_context.function) viewer = sark.ui.NXGraph(graph, \"Callgraph for {}\".format(function_name), handler=sark.ui.AddressNodeHandler()) viewer.Show()", "thread_id: thread id to normalize @return: a normalized string of", "debug value @param parent: @param call_value: @param ret_value: @param arg_name:", "8, item_parsed_val_flag_ret) parent.setChild(arg_count, 9, item_parsed_val_ret) # If current object contains", "= QtWidgets.QAction(\"Exclude Address\", self.functionTreeView, triggered=lambda: self.on_exclude_ea(self.context_menu_param)) action_exclude_library = QtWidgets.QAction(\"Exclude Library\",", "ex: idaapi.msg(\"Error while highlighting item row: %s\\n\" % ex) def", "table item \"\"\" try: if not item.index().isValid(): return parent =", "on_exclude_func_adrs(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is not", "a dbFunction_Context object @param occur_num: occurrence number @return: QStandradItemModel item", "not None: parsed_val_data = hex(ret_value.raw_value) if ret_value.nested_values or ret_value.reference_flink is", "values) arg_ident = \" \" * nest_depth arg_ident_type = arg_ident", "string of the thread_id to be used sa data for", "raise ValueError(\"Wrong value sent to 'on_show_callgraph'\") graph = nx.DiGraph() call_graph", "@return: a normalized string of the thread_id to be used", "item_parsed_val_flag_ret) parent.setChild(arg_count, 9, item_parsed_val_ret) # If current object contains reference", "not None: if ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent, nested_val_call, nested_val_ret,", "nested_val_call.type, nest_depth+1) # If return value is a container type", "if parsed_val_list is not None and len(parsed_val_list) > 1: lines", "True func_context = index.data(role=DIE.UI.FunctionContext_Role) if func_context is not None: ea", "value sent to 'on_show_callgraph': %s. excpected dbFunction_Context\" % function_context.__class__) else:", "# @QtCore.Slot(QtCore.QModelIndex) def itemDoubleClickSlot(self, index): \"\"\" TreeView DoubleClicked Slot. @param", "self.die_db.get_function_arg(function, arg_index) self._add_model_arg_value(item_func_context, current_call_values[arg_index], current_ret_values[arg_index], current_arg.name, current_arg.type) except IndexError: break", "QtGui.QStandardItem(\"0\") item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count] return item_list def", "return def on_thread_combobox_change(self, thread_id): self.reset_function_count(thread_id) # reset function count according", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return", "ea\\occurrences for the current function func_context_dict = self.die_db.get_function_context_dict(function) for function_context_ea", "tree item for function occurrence (level-2) @param function_context: a dbFunction_Context", "None, curret_ret_arg_value, \"ret_arg\", ret_arg_type) # Increment occurrence counter occurrence_num +=", "is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question)", "self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, None, ref_val, ref_val.name, ref_val.type, nest_depth+1) def _add_model_container_members(self, parent,", "# item_list_func = self._make_nonexec_function_time(func_name) # # if function.is_lib_func: # Color", "\"ret_arg\", ret_arg_type) # Increment occurrence counter occurrence_num += 1 #", "[] return PluginForm.Show(self, \"Function View\", options=PluginForm.FORM_PERSIST) def OnCreate(self, form): \"\"\"", "item, show a combo-box item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else: item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole)", "QtWidgets.QAction(\"Exclude Address\", self.functionTreeView, triggered=lambda: self.on_exclude_ea(self.context_menu_param)) action_exclude_library = QtWidgets.QAction(\"Exclude Library\", self.functionTreeView,", "triggered=lambda: self.on_exclude_ea(self.context_menu_param)) action_exclude_library = QtWidgets.QAction(\"Exclude Library\", self.functionTreeView, triggered=lambda: self.on_exclude_library(self.context_menu_param)) action_value_detail", "return item_list def _make_func_occur_item(self, function_context, occur_num): \"\"\" Build a tree", "combobox delegate. if parsed_vals: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret =", "nested_val_call = self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret = None # Try to get", "data to @param thread_id: thread_id number @return: True if thread", "item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else: item_parsed_val_ret.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\"", "= None # Parameter to be passed to context menu", "_add_model_arg_ref(self, parent, call_value, ret_value, nest_depth=0): \"\"\" Add a reference value", "= QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView) self.parent.setLayout(layout) def OnClose(self, form): idaapi.msg(\"Closed\\n\") def", "for function in self.die_db.get_functions(): item_list_func = self._make_function_item(function) if function.is_lib_func: #", "\"\"\" Insert thread_id data into a model item. The value", "more the 1 item, show a combo-box item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more)", "= QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5) item_func_context.setEditable(False) item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used", "\"\"\" item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_name) item_function_count = QtGui.QStandardItem(\"0\") item_function_count.setEditable(False) item_function.setEditable(False)", "be used sa data for ThreadId_Role \"\"\" return \"t%st\" %", "if ret_value.nested_values is not None: if ret_value.nested_values: for nested_value in", "0: parsed_val_data = \"!MAX_DEREF!\" if call_value.raw_value is not None: parsed_val_data", "0: parsed_val_data = \"!MAX_DEREF!\" if ret_value.raw_value is not None: parsed_val_data", "hex(call_value.raw_value) if len(call_value.nested_values) > 0 or call_value.reference_flink is not None:", "PluginForm.Show(self, \"Function View\", options=PluginForm.FORM_PERSIST) def OnCreate(self, form): \"\"\" Called when", "is_func_context_item is not None: self.context_menu_param = is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_value_item", "QtWidgets.QComboBox(parent) combo_box.addItems(lines) return combo_box def setEditorData(self, editor, index): editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index)))", "_add_model_container_members(self, parent, call_value, ret_value, nest_depth=0): \"\"\" Add container members to", "not None and not ret_value.is_definitely_parsed: ref_val = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, None,", "is not None: raise ValueError(\"Wrong value sent to 'on_show_callgraph': %s.", "a function_ea node (level-1) @param function_context: a dbFunction_Context object @return:", "self.functionTreeView, triggered=lambda: self.on_exclude_ea(self.context_menu_param)) action_exclude_library = QtWidgets.QAction(\"Exclude Library\", self.functionTreeView, triggered=lambda: self.on_exclude_library(self.context_menu_param))", "(level-1) @param function_context: a dbFunction_Context object @return: QStandradItemModel item for", "@return: QStandradItemModel item for the function \"\"\" function_txt = \"%s\"", "func_ea_txt = \"[%s]:%s\" % (function_context.calling_func_name, hex(function_context.calling_ea)) item_func_context_ea = QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False)", "item_function = item_list_func[0] root_node.appendRow(item_list_func) # Add function contexts ea\\occurrences for", "item \"\"\" try: if not item.index().isValid(): return parent = item.parent()", "+ self._make_thread_id_data(thread_id) + \".*\" threadProxyModel = _QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel)", "item_header.setToolTip(\"Argument`s value on function return\") model.setHorizontalHeaderItem(9, item_header) def _make_thread_id_data(self, thread_id):", "False def _make_function_item(self, function): \"\"\" Build a tree item for", "ret_value.nested_values or ret_value.reference_flink is not None: parsed_val_data = \"\" item_parsed_val_ret", "ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent, nested_val_call, nested_val_ret, nested_val_call.name, nested_val_call.type, nest_depth+1)", "450) self.functionTreeView.setColumnWidth(8, 20) self.functionTreeView.setColumnWidth(9, 450) # Context menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu)", "QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph) # Argument value ContextMenu self.value_context_menu = QtWidgets.QMenu(self.functionTreeView)", "parsed_val_data = \"\" item_parsed_val_ret = QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count, 0, this_row_item) parent.setChild(arg_count,", "Actions self.context_menu_param = None # Parameter to be passed to", "threadProxyModel = _QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel) def on_valueview_button(self): value_view", "thread_data: item.setData(thread_data + current_thread_id, role=DIE.UI.ThreadId_Role) return True except Exception as", "as nx from awesome.context import ignored import sark import idaapi", "is not None: if call_value.nested_values: for index in xrange(0, len(call_value.nested_values)):", "as ex: idaapi.msg(\"Error while highlighting item: %s\\n\" %ex) def highlight_item_row(self,", "continue item_func_context_list = self._make_function_ea_item(function_context_list[0]) item_func_context_ea = item_func_context_list[0] item_function.appendRow(item_func_context_list) occurrence_num =", "not None: if call_value.reference_flink is not None and not call_value.is_definitely_parsed:", "function_txt) item_function.setData(function, role=DIE.UI.Function_Role) function_count = self.die_db.count_function_occurs(function) item_function_count = QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False)", "def _add_model_arg_ref(self, parent, call_value, ret_value, nest_depth=0): \"\"\" Add a reference", "% ex) ############################################################################################### # Find Items. def find_function(self, function_name): \"\"\"", "parsed_val.description) lines.append(line_txt) combo_box = QtWidgets.QComboBox(parent) combo_box.addItems(lines) return combo_box def setEditorData(self,", "self.die_db.get_function_context_dict(function) for function_context_ea in func_context_dict: function_context_list = func_context_dict[function_context_ea] if not", "dbFunction_Context\" % function.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\")", "is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) # @QtCore.Slot(str) def on_exclude_func(self, function): if not isinstance(function,", "function.proto_ea if ea is not None and ea is not", "to 'on_exclude_ea': %s. excpected dbFunction_Context\" % function_context.__class__) else: raise ValueError(\"Wrong", "if parsed_vals is not None and len(parsed_vals) > 0: is_guessed,", "calls preformed to this function\") model.setHorizontalHeaderItem(1, item_header) ### Indirect Header", "@param function_context: a dbFunction_Context object @param occur_num: occurrence number @return:", "ref_val_call, ref_val_ret, ref_val_call.name, ref_val_call.type, nest_depth+1) # If return debug value", "if ret_arg is None: ret_arg_type = \"VOID\" else: ret_arg_type =", "None: parsed_val_data = hex(call_value.raw_value) if len(call_value.nested_values) > 0 or call_value.reference_flink", "20) self.functionTreeView.setColumnWidth(4, 250) self.functionTreeView.setColumnWidth(5, 100) self.functionTreeView.setColumnWidth(6, 20) self.functionTreeView.setColumnWidth(7, 450) self.functionTreeView.setColumnWidth(8,", "sa data for ThreadId_Role \"\"\" return \"t%st\" % str(thread_id) def", "QtGui.QStandardItem(\"Call Value\") item_header.setToolTip(\"Argument`s value on function call\") model.setHorizontalHeaderItem(7, item_header) ###", "while highlighting item row: %s\\n\" % ex) def clear_highlights(self): \"\"\"", "# Reset highlighted items self.highligthed_items = [] return PluginForm.Show(self, \"Function", "@param parent: @param call_value: @param ret_value: @param arg_name: @param arg_type:", "_model_builder(self, model): \"\"\" Build the function model. @param model: QStandardItemModel", "container members to module @param parent: @param call_value: @param ret_value:", "= QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number of calls preformed to this function\") model.setHorizontalHeaderItem(1,", "item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function, function_context.thread_id) self._insert_thread_data(item_func_context_ea, function_context.thread_id) # Add function arguments to", "item_header = QtGui.QStandardItem(\"Call Value\") item_header.setToolTip(\"Argument`s value on function call\") model.setHorizontalHeaderItem(7,", "function_context, occur_num): \"\"\" Build a tree item for function occurrence", "object is a container object, Add its members to the", "= index.data(role=DIE.UI.Function_Role) is_func_context_item = index.data(role=DIE.UI.FunctionContext_Role) is_value_item = index.data(role=DIE.UI.ParsedValueRole) if is_function_item", "not None: self.bp_handler.add_module_exception(function.lib_name) return # @QtCore.Slot(str) def on_value_detail(self, value): if", "name (level-0) @param function: dbFunction object @return: QStandradItemModel item for", "current object is a container object, Add its members to", "\"\"\" Reset the function count and set the count according", "item_list_func = self._make_nonexec_function_time(func_name) # # if function.is_lib_func: # Color library", "self.die_db.get_function_context_list(function) for func_context in func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return # @QtCore.Slot(str) def", "== call_value.type: if ret_value.nested_values is not None: if ret_value.nested_values: nested_val_ret", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_nonexec_function_time(self, function_name): \"\"\" Build", "self.die_db = DIE.Lib.DIEDb.get_db() # Get parent widget self.parent = form_to_widget(form)", "role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else: item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if", "Build a tree item for a function_ea node (level-1) @param", "on_valueview_button(self): value_view = DIE.UI.ValueViewEx.get_view() value_view.Show() def on_pluginsview_button(self): plugins_view = DIE.UI.ParserView.get_view()", "item_parsed_val_call) parent.setChild(arg_count, 8, item_parsed_val_flag_ret) parent.setChild(arg_count, 9, item_parsed_val_ret) # If current", "object @return: QStandradItemModel item for the function context \"\"\" calling_function_start", "module @param parent: @param call_value: @param ret_value: @param nest_depth: @return:", "= \"[%s]:%s\" % (function_context.calling_func_name, hex(function_context.calling_ea)) item_func_context_ea = QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea),", "ref_val_call.name, ref_val_call.type, nest_depth+1) # If return debug value is a", "be delimited by the _make_thread_id_data function (e.g: thread_id 123 will", "None def initialize(): global function_view function_view = FunctionView() def get_view():", "only occurrences of it. if not index.data().startswith(\"Occur\"): continue item =", "is not idc.BADADDR: idc.Jump(ea) return True func_context = index.data(role=DIE.UI.FunctionContext_Role) if", "function_name) item_function_count = QtGui.QStandardItem(\"0\") item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count]", "QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: # If", "thread_id 123 will become 't123t') the delimited value will then", "= \"!MAX_DEREF!\" if call_value.raw_value is not None: parsed_val_data = hex(call_value.raw_value)", "function_view = None def initialize(): global function_view function_view = FunctionView()", "index.data(role=DIE.UI.ParsedValuesRole) # Show combobox only if parsed_value as two or", "func_context in func_context_list: self.bp_handler.add_bp_ea_exception(func_context.calling_ea) return # @QtCore.Slot(str) def on_exclude_ea(self, function_context):", "= QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role) # Inherit thread data from parent", "@param function_context: a dbFunction_Context object @return: QStandradItemModel item for the", "item.setBackground(QtGui.QColor('white')) cur_font = item.font() cur_font.setBold(False) item.setFont(cur_font) self.highligthed_items = [] except", "QtGui.QStandardItem(\"Type\") item_header.setToolTip(\"Argument Type\") model.setHorizontalHeaderItem(4, item_header) ### New Function Header item_header", "\"\"\" root_item = self.functionModel.item(0, 0) rows = root_item.rowCount() thread_id =", "is_value_item = index.data(role=DIE.UI.ParsedValueRole) if is_function_item is not None: self.context_menu_param =", "None, ref_val, ref_val.name, ref_val.type, nest_depth+1) def _add_model_container_members(self, parent, call_value, ret_value,", "get the same member from the return debug value. if", "add them to the module self._add_model_arg_ref(this_row_item, call_value, ret_value, nest_depth) #", "not None: call_offset = function_context.calling_ea - calling_function_start func_ea_txt = \"%s+%s\"", "item @param item: table item \"\"\" try: if not item.index().isValid():", "DIE.Lib.IDAConnector.get_function_name(func_ea) # # if self.die_db.get_function_by_name(func_name) is None: # item_list_func =", "Called when the plugin form is created \"\"\" self.value_view =", "None and ea is not idc.BADADDR: idc.Jump(ea) return True func_context", "debug value is a reference if call_value is not None:", "@param model: the QStandardItemModel which headers should be set \"\"\"", "_MatchRecursive = QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly = QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import", "def on_bpview_button(self): bp_view = DIE.UI.BPView.get_view() bp_view.Show() ############################################################################################### # View Delegates.", "item_func_context.setEditable(False) item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module look-ups", "Call\") model.setHorizontalHeaderItem(2, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New", "Build a tree item for a function name (for a", "Add return argument self._add_model_arg_value(item_func_context, None, curret_ret_arg_value, \"ret_arg\", ret_arg_type) # Increment", "self.functionTreeView, triggered=lambda: self.on_value_detail(self.context_menu_param)) action_show_callgraph = QtWidgets.QAction(\"Show Call-Graph\", self.functionTreeView, triggered=lambda: self.on_show_callgraph(self.context_menu_param))", "Do not highlight \"ea root\" items, only occurrences of it.", "elif ret_value is not None: if ret_value.reference_flink is not None", "model: QStandardItemModel object \"\"\" model.clear() # Clear the model root_node", "self.value_context_menu = QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail) # Therad ComboBox threads = []", "self.thread_id_combo.currentText() for row in xrange(0, rows): cur_item = root_item.child(row, 0)", "is self.functionModel: self.functionTreeView.setModel(self.functionModel) return hidden_threads = \".*\" + self._make_thread_id_data(thread_id) +", "not None: threads = self.die_db.get_thread_list() thread_id_list = [] thread_id_list.append(\"All Threads\")", "item_header) ### Return Value Header item_header = QtGui.QStandardItem(\"Return Value\") item_header.setToolTip(\"Argument`s", "ret_value, nest_depth=0): \"\"\" Add container members to module @param parent:", "None: parsed_val_data = hex(ret_value.raw_value) if ret_value.nested_values or ret_value.reference_flink is not", "to the module self._add_model_arg_ref(this_row_item, call_value, ret_value, nest_depth) # If current", "5, QtGui.QStandardItem(arg_name)) parent.setChild(arg_count, 6, item_parsed_val_flag_call) parent.setChild(arg_count, 7, item_parsed_val_call) parent.setChild(arg_count, 8,", "%s\" % (parsed_val.score, parsed_val.data, parsed_val.description) lines.append(line_txt) combo_box = QtWidgets.QComboBox(parent) combo_box.addItems(lines)", "currently selected thread if thread_id == \"All Threads\": if not", "self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if len(parsed_vals) >", "# @QtCore.Slot(str) def on_exclude_ea(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if", "0) function = cur_item.data(role=DIE.UI.Function_Role) if function is not None: count", "idautils import idc from idaapi import PluginForm from sark.qt import", "delimited value will then be appended to a string of", "item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_name) item_function_count = QtGui.QStandardItem(\"0\") item_function_count.setEditable(False) item_function.setEditable(False) item_list", "or more items. if parsed_val_list is not None and len(parsed_val_list)", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list", "if ret_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\" if ret_value.raw_value is", "ex) ############################################################################################### # Find Items. def find_function(self, function_name): \"\"\" Find", "call_offset = function_context.calling_ea - calling_function_start func_ea_txt = \"%s+%s\" % (function_context.calling_func_name,", "look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role) item_list = [item_func_context, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "not None and not call_value.is_definitely_parsed: ref_val_call = self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret =", "function # for tmp_item in item_list_func: # tmp_item.setBackground(QtGui.QColor(255, 0, 0,", "a non-executed function) @type: String @param function_name: Function name @return:", "# Add db functions to the model for function in", "# If current object is a container object, Add its", "All Function Calls\", self.functionTreeView, triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea = QtWidgets.QAction(\"Exclude Address\",", "try: self.clear_highlights() root_index = self.functionModel.index(0, 0) if not root_index.isValid(): return", "each context current_call_values = self.die_db.get_call_values(function_context) current_ret_values = self.die_db.get_return_values(function_context) curret_ret_arg_value =", "call_value: @param ret_value: @param arg_name: @param arg_type: @return: \"\"\" arg_count", "None: if call_value.reference_flink is not None and not call_value.is_definitely_parsed: ref_val_call", "nest_depth=0): \"\"\" Add a reference value to module @param parent:", "self.die_db.get_call_values(function_context) current_ret_values = self.die_db.get_return_values(function_context) curret_ret_arg_value = self.die_db.get_return_arg_value(function_context) for arg_index in", "nest_depth+1) # If return debug value is a reference (and", "\"\"\" Build the function model. @param model: QStandardItemModel object \"\"\"", "function_ea node (level-1) @param function_context: a dbFunction_Context object @return: QStandradItemModel", "context_list: list of function contexts (of type dbFunction_Context) \"\"\" try:", "ret_value: @param nest_depth: @return: \"\"\" # If call value is", "None: item.setData(current_thread_id, role=DIE.UI.ThreadId_Role) elif not current_thread_id in thread_data: item.setData(thread_data +", "if parsed_vals: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret = QtGui.QStandardItem(best_val.data) if", "list of function contexts @param context_list: list of function contexts", "parent.columnCount() for column in xrange(0, column_num): if self.functionModel.hasIndex(row, column, parent.index()):", "item_function_count = QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count, QtGui.QStandardItem(),", "\"\"\" def __init__(self): super(FunctionView, self).__init__() self.value_view = None self.bp_handler =", "def initialize(): global function_view function_view = FunctionView() def get_view(): return", "Set indentation for argument types (for nested values) arg_ident =", "on_bpview_button(self): bp_view = DIE.UI.BPView.get_view() bp_view.Show() ############################################################################################### # View Delegates. class", "continue # Do not highlight \"ea root\" items, only occurrences", "call value is a container type (struct\\union\\etc) if call_value is", "index item. @return: \"\"\" function = index.data(role=DIE.UI.Function_Role) if function is", "[] except Exception as ex: idaapi.msg(\"Error while clearing highlights: %s\\n\"", "function_context.thread_id) # Add function arguments to each context current_call_values =", "Return Value Header item_header = QtGui.QStandardItem(\"Return Value\") item_header.setToolTip(\"Argument`s value on", "idautils.Functions(): # func_name = DIE.Lib.IDAConnector.get_function_name(func_ea) # # if self.die_db.get_function_by_name(func_name) is", "function name (for a non-executed function) @type: String @param function_name:", "self.die_db = None self.highligthed_items = [] def Show(self): # Reset", "raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs': %s. excpected dbFunction_Context\" %", "Exception as ex: idaapi.msg(\"Error while clearing highlights: %s\\n\" % ex)", "None and call_value.nested_values is not None: if call_value.nested_values: for index", "raise ValueError(\"Wrong value sent to 'on_exclude_ea': %s. excpected dbFunction_Context\" %", "best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if", "item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module", "container type (and call value is not) elif ret_value is", "return item_list def _add_model_arg_value(self, parent, call_value, ret_value, arg_name, arg_type, nest_depth=0):", "is not None: if ret_value.nested_values: for nested_value in ret_value.nested_values: nested_val_ret", "cur_item.data(role=DIE.UI.Function_Role) if function is not None: count = 0 if", "if is_func_context_item is not None: self.context_menu_param = is_func_context_item self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if", "# Add return argument self._add_model_arg_value(item_func_context, None, curret_ret_arg_value, \"ret_arg\", ret_arg_type) #", "module item \"\"\" try: item.setBackground(QtGui.QColor('yellow')) cur_font = item.font() cur_font.setBold(True) item.setFont(cur_font)", "# Argument value ContextMenu self.value_context_menu = QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail) # Therad", "QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import DIE.UI.Die_Icons import DIE.UI.ValueViewEx import DIE.UI.ParserView", "Header item_header = QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument Name\") model.setHorizontalHeaderItem(5, item_header) ### Call", "__init__(self, parent): QtWidgets.QStyledItemDelegate.__init__(self, parent) self.parent = parent def createEditor(self, parent,", "Add db functions to the model for function in self.die_db.get_functions():", "= self._make_thread_id_data(thread_id) thread_data = item.data(role=DIE.UI.ThreadId_Role) if thread_data is None: item.setData(current_thread_id,", "len(call_value.nested_values) > 0 or call_value.reference_flink is not None: parsed_val_data =", "True except Exception as ex: idaapi.msg(\"Error while looking up function", "None: call_offset = function_context.calling_ea - calling_function_start func_ea_txt = \"%s+%s\" %", "@param model: QStandardItemModel object \"\"\" model.clear() # Clear the model", "parent = item.parent() if parent is None: parent = item", "create a combobox delegate. if parsed_vals: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals)", "is None: # item_list_func = self._make_nonexec_function_time(func_name) # # if function.is_lib_func:", "not) elif ret_value is not None: if ret_value.nested_values is not", "self.die_db.get_return_values(function_context) curret_ret_arg_value = self.die_db.get_return_arg_value(function_context) for arg_index in xrange(0, function.arg_num): try:", "self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index, _PositionAtTop) self.highlight_item_row(item) return True except Exception as", "ContextMenu self.value_context_menu = QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail) # Therad ComboBox threads =", "return True func_context = index.data(role=DIE.UI.FunctionContext_Role) if func_context is not None:", "= self.die_db.get_call_graph_to(function_context) if not call_graph: idaapi.msg(\"No Execution Graph\") return for", "self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0, 200) self.functionTreeView.setColumnWidth(1, 20) self.functionTreeView.setColumnWidth(2, 20) self.functionTreeView.setColumnWidth(3, 20) self.functionTreeView.setColumnWidth(4,", "item_header = QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number of calls preformed to this function\")", "= [] if self.die_db is not None: threads = self.die_db.get_thread_list()", "used sa data for ThreadId_Role \"\"\" return \"t%st\" % str(thread_id)", "string of concatenated (unique) child-item thread-ids (for example a item", "idc.Jump(ea) return True func_context = index.data(role=DIE.UI.FunctionContext_Role) if func_context is not", "while inserting thread data: %s\\n\" %ex) return False def _make_function_item(self,", "the current function func_context_dict = self.die_db.get_function_context_dict(function) for function_context_ea in func_context_dict:", "self.functionModel = QtGui.QStandardItemModel() self.functionTreeView = QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True) delegate =", "if not item.index().isValid(): return parent = item.parent() if parent is", "value sent to 'on_show_callgraph'\") graph = nx.DiGraph() call_graph = self.die_db.get_call_graph_to(function_context)", "index.data(role=DIE.UI.FunctionContext_Role) is_value_item = index.data(role=DIE.UI.ParsedValueRole) if is_function_item is not None: self.context_menu_param", "None and ret_value.type == call_value.type: if ret_value.reference_flink is not None", "return # @QtCore.Slot(str) def on_exclude_func_adrs(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction):", "type (struct\\union\\etc) if call_value is not None and call_value.nested_values is", "not None and not ret_value.is_definitely_parsed: ref_val_ret = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, ref_val_call,", "triggered=lambda: self.on_exclude_library(self.context_menu_param)) action_value_detail = QtWidgets.QAction(\"Inspect Value Details\", self.functionTreeView, triggered=lambda: self.on_value_detail(self.context_menu_param))", "the 1 item, show a combo-box item_parsed_val_ret.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_ret.setIcon(self.die_icons.icon_more) else:", "xrange(0, rows): cur_item = root_item.child(row, 0) function = cur_item.data(role=DIE.UI.Function_Role) if", "thread_id): self.reset_function_count(thread_id) # reset function count according to currently selected", "Therad ComboBox threads = [] if self.die_db is not None:", "item_func_context = item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function, function_context.thread_id) self._insert_thread_data(item_func_context_ea, function_context.thread_id) # Add", "Parameter to be passed to context menu slots action_exclude_func =", "@param arg_type: @return: \"\"\" arg_count = parent.rowCount() this_row_item = QtGui.QStandardItem(\"\")", "order to support filtering\\sorting on multi-thread data items @param thread_id:", "value sent to 'on_exclude_ea': %s. excpected dbFunction_Context\" % function_context.__class__) else:", "xrange(0, column_num): if self.functionModel.hasIndex(row, column, parent.index()): cur_index = self.functionModel.index(row, column,", "item: table item \"\"\" try: if not item.index().isValid(): return parent", "import DIE.Lib.DIEDb import DIE.Lib.BpHandler import sark.ui class FunctionView(PluginForm): \"\"\" DIE", "\" * nest_depth arg_ident_type = arg_ident + arg_type item_parsed_val_flag_call =", "is not None: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs': %s.", "self.value_view = DIE.UI.ValueViewEx.get_view() self.bp_handler = DIE.Lib.BpHandler.get_bp_handler() self.die_icons = DIE.UI.Die_Icons.get_die_icons() self.die_db", "of function contexts @param context_list: list of function contexts (of", "the tree view \"\"\" def __init__(self, parent): QtWidgets.QStyledItemDelegate.__init__(self, parent) self.parent", "self.die_db.get_thread_list() thread_id_list = [] thread_id_list.append(\"All Threads\") for thread in threads:", "not None and ret_value.type == call_value.type: if ret_value.nested_values is not", "item_parsed_val_ret = QtGui.QStandardItem() # Get Call Value if call_value is", "column, parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index = QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index) except Exception as", "Slots. # @QtCore.Slot(QtCore.QModelIndex) def itemDoubleClickSlot(self, index): \"\"\" TreeView DoubleClicked Slot.", "self.die_db.get_function_arg(function, -1) if ret_arg is None: ret_arg_type = \"VOID\" else:", "item_header = QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument Name\") model.setHorizontalHeaderItem(5, item_header) ### Call Value", "DIE.Lib.IDAConnector import DIE.Lib.DIEDb import DIE.Lib.BpHandler import sark.ui class FunctionView(PluginForm): \"\"\"", "\"\"\" # If call value is a container type (struct\\union\\etc)", "@param index: QModelIndex object of the clicked tree index item.", "function_context is not None: raise ValueError(\"Wrong value sent to 'on_exclude_ea':", "def _make_function_ea_item(self, function_context): \"\"\" Build a tree item for a", "# Get parent widget self.parent = form_to_widget(form) self.functionModel = QtGui.QStandardItemModel()", "according to currently selected thread_id @param thread_id: currently selected thread_id", "= DIE.UI.ValueViewEx.get_view() self.bp_handler = DIE.Lib.BpHandler.get_bp_handler() self.die_icons = DIE.UI.Die_Icons.get_die_icons() self.die_db =", "self.on_exclude_library(self.context_menu_param)) action_value_detail = QtWidgets.QAction(\"Inspect Value Details\", self.functionTreeView, triggered=lambda: self.on_value_detail(self.context_menu_param)) action_show_callgraph", "ret_value.nested_values is not None: if ret_value.nested_values: for nested_value in ret_value.nested_values:", "contexts @param context_list: list of function contexts (of type dbFunction_Context)", "= [item_func_context, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "QtWidgets, form_to_widget, use_qt5 if use_qt5: _QSortFilterProxyModel = QtCore.QSortFilterProxyModel _MatchRecursive =", "OnClose(self, form): idaapi.msg(\"Closed\\n\") def isVisible(self): \"\"\" Is functionview visible @return:", "call value is not) elif ret_value is not None: if", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _add_model_arg_value(self,", "= QtGui.QStandardItem() item_parsed_val_ret = QtGui.QStandardItem() # Get Call Value if", "call_graph = self.die_db.get_call_graph_to(function_context) if not call_graph: idaapi.msg(\"No Execution Graph\") return", "item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: # If more the 1", "viewer.Show() return # @QtCore.Slot(str) def on_exclude_library(self, function): if not isinstance(function,", "return for ctxt_node in call_graph: (from_address, to_address) = ctxt_node graph.add_edge(from_address,", "for function_context_ea in func_context_dict: function_context_list = func_context_dict[function_context_ea] if not len(function_context_list)", "form_to_widget(form) self.functionModel = QtGui.QStandardItemModel() self.functionTreeView = QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True) delegate", "root_item.child(row, 1) func_count_item.setText(str(count)) ############################################################################################### # Highlight Items. def highlight_item(self, item):", "for module look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role) item_list = [item_func_context, QtGui.QStandardItem(), QtGui.QStandardItem(),", "> 0 or call_value.reference_flink is not None: parsed_val_data = \"\"", "DIE.Lib.BpHandler.get_bp_handler() self.die_icons = DIE.UI.Die_Icons.get_die_icons() self.die_db = DIE.Lib.DIEDb.get_db() # Get parent", "Delimit thread_id data in order to support filtering\\sorting on multi-thread", "call_value, ret_value, nest_depth) # If current object is a container", "QtGui.QStandardItem() item_parsed_val_ret = QtGui.QStandardItem() # Get Call Value if call_value", "current_arg = self.die_db.get_function_arg(function, arg_index) self._add_model_arg_value(item_func_context, current_call_values[arg_index], current_ret_values[arg_index], current_arg.name, current_arg.type) except", "same member from the return debug value. if ret_value is", "lines = [] for parsed_val in parsed_val_list: line_txt = \"%d,", "parsed_val_data = \"NULL\" if ret_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\"", "ex) def clear_highlights(self): \"\"\" Clear all highlighted items @return: \"\"\"", "### Return Value Header item_header = QtGui.QStandardItem(\"Return Value\") item_header.setToolTip(\"Argument`s value", "self.functionTreeView.collapseAll() for persistent_index in self.highligthed_items: if persistent_index.isValid(): item = self.functionModel.itemFromIndex(persistent_index)", "is not None: parsed_vals = self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role) # If", "idc from idaapi import PluginForm from sark.qt import QtGui, QtCore,", "context in FunctionView: %s\\n\" % ex) return False ############################################################################################### #", "\"Callgraph for {}\".format(function_name), handler=sark.ui.AddressNodeHandler()) viewer.Show() return # @QtCore.Slot(str) def on_exclude_library(self,", "action_exclude_library = QtWidgets.QAction(\"Exclude Library\", self.functionTreeView, triggered=lambda: self.on_exclude_library(self.context_menu_param)) action_value_detail = QtWidgets.QAction(\"Inspect", "Threads\": if not self.functionTreeView.model() is self.functionModel: self.functionTreeView.setModel(self.functionModel) return hidden_threads =", "is not None: threads = self.die_db.get_thread_list() thread_id_list = [] thread_id_list.append(\"All", "parent.setChild(arg_count, 7, item_parsed_val_call) parent.setChild(arg_count, 8, item_parsed_val_flag_ret) parent.setChild(arg_count, 9, item_parsed_val_ret) #", "rows = root_item.rowCount() thread_id = self.thread_id_combo.currentText() for row in xrange(0,", "= sark.ui.NXGraph(graph, \"Callgraph for {}\".format(function_name), handler=sark.ui.AddressNodeHandler()) viewer.Show() return # @QtCore.Slot(str)", "def __init__(self, parent): QtWidgets.QStyledItemDelegate.__init__(self, parent) self.parent = parent def createEditor(self,", "role=DIE.UI.ThreadId_Role) # Inherit thread data from parent # Set indentation", "model for function in self.die_db.get_functions(): item_list_func = self._make_function_item(function) if function.is_lib_func:", "all highlighted items @return: \"\"\" try: self.functionTreeView.collapseAll() for persistent_index in", "else: _QSortFilterProxyModel = QtGui.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly = QtCore.Qt.MatchFlag.MatchExactly", "currently selected thread_id \"\"\" root_item = self.functionModel.item(0, 0) rows =", "a function name (level-0) @param function: dbFunction object @return: QStandradItemModel", "item for a function name (level-0) @param function: dbFunction object", "is not None: self.context_menu_param = is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) # @QtCore.Slot(str) def", "= \"NULL\" if ret_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\" if", "the return debug value. if ret_value is not None and", "while looking up function context in FunctionView: %s\\n\" % ex)", "self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea = QtWidgets.QAction(\"Exclude Address\", self.functionTreeView, triggered=lambda: self.on_exclude_ea(self.context_menu_param)) action_exclude_library =", "not None: self.context_menu_param = is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) # @QtCore.Slot(str) def on_exclude_func(self,", "{}\".format(function_name), handler=sark.ui.AddressNodeHandler()) viewer.Show() return # @QtCore.Slot(str) def on_exclude_library(self, function): if", "if function.is_lib_func: # Color library function # for tmp_item in", "from awesome.context import ignored import sark import idaapi import idautils", "index.data().startswith(\"Occur\"): continue item = self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index, _PositionAtTop) self.highlight_item_row(item) return", "a model item. The value found in thread_id argument will", "def __init__(self): super(FunctionView, self).__init__() self.value_view = None self.bp_handler = None", "occur_num): \"\"\" Build a tree item for function occurrence (level-2)", "import sark.ui class FunctionView(PluginForm): \"\"\" DIE Function View \"\"\" def", "QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count, 0, this_row_item) parent.setChild(arg_count, 1, QtGui.QStandardItem()) parent.setChild(arg_count, 2, QtGui.QStandardItem())", "to item, otherwise False \"\"\" try: current_thread_id = self._make_thread_id_data(thread_id) thread_data", "if parent is None: parent = item if not parent.hasChildren():", "items @param thread_id: thread id to normalize @return: a normalized", "clearing highlights: %s\\n\" % ex) ############################################################################################### # Find Items. def", "the same member from the return debug value. if ret_value", "try: if not item.index().isValid(): return parent = item.parent() if parent", "ref_val = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, None, ref_val, ref_val.name, ref_val.type, nest_depth+1) def", "= self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if len(parsed_vals)", "_MatchRecursive | _MatchExactly) for index in matched_items: if not index.isValid():", "+ current_thread_id, role=DIE.UI.ThreadId_Role) return True except Exception as ex: idaapi.msg(\"Error", "func_context_dict: function_context_list = func_context_dict[function_context_ea] if not len(function_context_list) > 0: continue", "xrange(0, function.arg_num): try: current_arg = self.die_db.get_function_arg(function, arg_index) self._add_model_arg_value(item_func_context, current_call_values[arg_index], current_ret_values[arg_index],", "# for tmp_item in item_list_func: # tmp_item.setBackground(QtGui.QColor(255, 0, 0, 127))", "= QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label = QtWidgets.QLabel(\"Thread: \") # Toolbar", "self.thread_id_label = QtWidgets.QLabel(\"Thread: \") # Toolbar self.function_toolbar = QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label)", "= DIE.Lib.IDAConnector.get_function_name(func_ea) # # if self.die_db.get_function_by_name(func_name) is None: # item_list_func", "root_item.rowCount() thread_id = self.thread_id_combo.currentText() for row in xrange(0, rows): cur_item", "nest_depth: @return: \"\"\" # If call value is a container", "Return Value Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8, item_header) ###", "sark import idaapi import idautils import idc from idaapi import", "_add_model_arg_value(self, parent, call_value, ret_value, arg_name, arg_type, nest_depth=0): \"\"\" Add a", "= QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: #", "if persistent_index.isValid(): item = self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white')) cur_font = item.font() cur_font.setBold(False)", "thread_id is None: count = self.die_db.count_function_occurs(function) else: count = self.die_db.count_function_occurs(function,", "count according to currently selected thread_id @param thread_id: currently selected", "import idautils import idc from idaapi import PluginForm from sark.qt", "ValueError(\"Wrong value sent to 'on_exclude_ea': %s. excpected dbFunction_Context\" % function_context.__class__)", "best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_call.setIcon(self.die_icons.icon_question) if", "item data value can be \"a123aa5672aa11112a\") for threads 123, 5672", "if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is not None: raise", "The value found in thread_id argument will be delimited by", "= self.functionModel.findItems(function_name) for item in matched_items: self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(), _PositionAtTop) self.highlight_item_row(item)", "it. if not index.data().startswith(\"Occur\"): continue item = self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index,", "is not None: parsed_val_data = hex(ret_value.raw_value) if ret_value.nested_values or ret_value.reference_flink", "value sent to 'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name) return # @QtCore.Slot(str) def on_exclude_func_adrs(self,", "ret_value is not None: if ret_value.nested_values is not None: if", "thread_id data in order to support filtering\\sorting on multi-thread data", "super(FunctionView, self).__init__() self.value_view = None self.bp_handler = None self.die_icons =", "DIE.UI.ValueViewEx import DIE.UI.ParserView import DIE.UI.BPView import DIE.Lib.IDAConnector import DIE.Lib.DIEDb import", "parent.setChild(arg_count, 1, QtGui.QStandardItem()) parent.setChild(arg_count, 2, QtGui.QStandardItem()) parent.setChild(arg_count, 3, QtGui.QStandardItem()) parent.setChild(arg_count,", "thread_id=None): \"\"\" Reset the function count and set the count", "is None: item.setData(current_thread_id, role=DIE.UI.ThreadId_Role) elif not current_thread_id in thread_data: item.setData(thread_data", "only if parsed_value as two or more items. if parsed_val_list", "handler=sark.ui.AddressNodeHandler()) viewer.Show() return # @QtCore.Slot(str) def on_exclude_library(self, function): if not", "item, otherwise False \"\"\" try: current_thread_id = self._make_thread_id_data(thread_id) thread_data =", "call_value.is_definitely_parsed: ref_val_call = self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret = None # Try to", "role=DIE.UI.ThreadId_Role) return True except Exception as ex: idaapi.msg(\"Error while inserting", "is not None: if ret_value.nested_values: nested_val_ret = self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent, nested_val_call,", "self.functionTreeView.setColumnWidth(9, 450) # Context menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) # Actions self.context_menu_param", "plugins_view.Show() def on_bpview_button(self): bp_view = DIE.UI.BPView.get_view() bp_view.Show() ############################################################################################### # View", "else: parsed_val_data = \"NULL\" if ret_value.derref_depth == 0: parsed_val_data =", "item_func_context_list = self._make_func_occur_item(function_context, occurrence_num) item_func_context = item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function, function_context.thread_id)", "self.die_db.count_function_occurs(function) item_function_count = QtGui.QStandardItem(str(function_count)) item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count,", "= DIE.UI.Die_Icons.get_die_icons() self.die_db = DIE.Lib.DIEDb.get_db() # Get parent widget self.parent", "= QtWidgets.QAction(\"Exclude All Function Calls\", self.functionTreeView, triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea =", "= model.invisibleRootItem() self._make_model_headers(model) if self.die_db is None: return # Add", "# func_name = DIE.Lib.IDAConnector.get_function_name(func_ea) # # if self.die_db.get_function_by_name(func_name) is None:", "= QtCore.Qt.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.PositionAtTop else: _QSortFilterProxyModel = QtGui.QSortFilterProxyModel _MatchRecursive", "None: count = 0 if thread_id is None: count =", "return argument self._add_model_arg_value(item_func_context, None, curret_ret_arg_value, \"ret_arg\", ret_arg_type) # Increment occurrence", "self.bp_handler.add_module_exception(function.lib_name) return # @QtCore.Slot(str) def on_value_detail(self, value): if not self.value_view.isVisible():", "nested_val_ret = self.die_db.get_dbg_value(nested_value) self._add_model_arg_value(parent, None, nested_val_ret, nested_val_ret.name, nested_val_ret.type, nest_depth+1) def", "header data @param model: the QStandardItemModel which headers should be", "func_ea_txt = \"%s+%s\" % (function_context.calling_func_name, hex(call_offset)) else: func_ea_txt = \"[%s]:%s\"", "@QtCore.Slot(str) def on_show_callgraph(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context", "None and len(parsed_vals) > 0: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_call", "for function_context in function_context_list: item_func_context_list = self._make_func_occur_item(function_context, occurrence_num) item_func_context =", "= self.functionModel.index(0, 0) if not root_index.isValid(): return for func_context in", "row: %s\\n\" % ex) def clear_highlights(self): \"\"\" Clear all highlighted", "is a container type (struct\\union\\etc) if call_value is not None", "# If more the 1 item, show a combo-box item_parsed_val_call.setData(parsed_vals,", "Value Details\", self.functionTreeView, triggered=lambda: self.on_value_detail(self.context_menu_param)) action_show_callgraph = QtWidgets.QAction(\"Show Call-Graph\", self.functionTreeView,", "on function call\") model.setHorizontalHeaderItem(7, item_header) ### Return Value Icon Header", "def find_context_list(self, context_list): \"\"\" Find and highlight a list of", "be passed to context menu slots action_exclude_func = QtWidgets.QAction(\"Exclude Function\",", "persistent_index in self.highligthed_items: if persistent_index.isValid(): item = self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white')) cur_font", "if self.die_db.get_function_by_name(func_name) is None: # item_list_func = self._make_nonexec_function_time(func_name) # #", "None: parsed_vals = self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role) # If len(parsed_vals)>1 create", "# Singelton function_view = None def initialize(): global function_view function_view", "passed to context menu slots action_exclude_func = QtWidgets.QAction(\"Exclude Function\", self.functionTreeView,", "Delegates. class TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\" Delegate for parsed value viewing in", "to 'on_exclude_func_adrs': %s. excpected dbFunction_Context\" % function.__class__) else: raise ValueError(\"Wrong", "QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label = QtWidgets.QLabel(\"Thread: \") # Toolbar self.function_toolbar", "# Function ContextMenu self.function_context_menu = QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs) #", "= hex(ret_value.raw_value) if ret_value.nested_values or ret_value.reference_flink is not None: parsed_val_data", "nested_val_ret = None # Try to get the same member", "count = 0 if thread_id is None: count = self.die_db.count_function_occurs(function)", "self.clear_highlights() matched_items = self.functionModel.findItems(function_name) for item in matched_items: self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(),", "ret_value.is_definitely_parsed: ref_val_ret = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, ref_val_call, ref_val_ret, ref_val_call.name, ref_val_call.type, nest_depth+1)", "= \"\" item_parsed_val_call = QtGui.QStandardItem(parsed_val_data) # Get return value if", "if thread_id is None: count = self.die_db.count_function_occurs(function) else: count =", "= [] for parsed_val in parsed_val_list: line_txt = \"%d, %s,", "raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") func_context_list = self.die_db.get_function_context_list(function) for", "QStandradItemModel item for the function context \"\"\" calling_function_start = None", "dbFunction_Context\" % function_context.__class__) else: raise ValueError(\"Wrong value sent to 'on_show_callgraph'\")", "self.ea_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_value_item is not None: self.context_menu_param = is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point))", "model # for func_ea in idautils.Functions(): # func_name = DIE.Lib.IDAConnector.get_function_name(func_ea)", "column, parent.index()): cur_index = self.functionModel.index(row, column, parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index =", "from sark.qt import QtGui, QtCore, QtWidgets, form_to_widget, use_qt5 if use_qt5:", "counter occurrence_num += 1 # Add non-executed function to the", "self.value_context_menu.addAction(action_value_detail) # Therad ComboBox threads = [] if self.die_db is", "= QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8, item_header) ### Return Value Header item_header =", "is None: ret_arg_type = \"VOID\" else: ret_arg_type = ret_arg.type #", "@param nest_depth: @return: \"\"\" # If call value is a", "@param arg_name: @param arg_type: @return: \"\"\" arg_count = parent.rowCount() this_row_item", "| _MatchExactly) for index in matched_items: if not index.isValid(): continue", "function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context is not None:", "self.functionTreeView.setColumnWidth(3, 20) self.functionTreeView.setColumnWidth(4, 250) self.functionTreeView.setColumnWidth(5, 100) self.functionTreeView.setColumnWidth(6, 20) self.functionTreeView.setColumnWidth(7, 450)", "function.is_lib_func and function.lib_name is not None: self.bp_handler.add_module_exception(function.lib_name) return # @QtCore.Slot(str)", "not index.isValid(): continue # Do not highlight \"ea root\" items,", "ref_val_call = self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret = None # Try to get", "self.ea_context_menu.addAction(action_show_callgraph) # Argument value ContextMenu self.value_context_menu = QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail) #", "is not None: parsed_vals = self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role) if parsed_vals", "\"\"\" try: item.setBackground(QtGui.QColor('yellow')) cur_font = item.font() cur_font.setBold(True) item.setFont(cur_font) except Exception", "layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView) self.parent.setLayout(layout) def OnClose(self, form): idaapi.msg(\"Closed\\n\") def isVisible(self): \"\"\"", "item.setFont(cur_font) except Exception as ex: idaapi.msg(\"Error while highlighting item: %s\\n\"", "function func_context_dict = self.die_db.get_function_context_dict(function) for function_context_ea in func_context_dict: function_context_list =", "not None: raise ValueError(\"Wrong value sent to 'on_exclude_ea': %s. excpected", "function_context: a dbFunction_Context object @return: QStandradItemModel item for the function", "# Do not highlight \"ea root\" items, only occurrences of", "Value if call_value is not None: parsed_vals = self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals,", "to normalize @return: a normalized string of the thread_id to", "parent: @param call_value: @param ret_value: @param nest_depth: @return: \"\"\" #", "@param call_value: @param ret_value: @param nest_depth: @return: \"\"\" # If", "@param item: the model item to add the data to", "else: ret_arg_type = ret_arg.type # Add return argument self._add_model_arg_value(item_func_context, None,", "def OnCreate(self, form): \"\"\" Called when the plugin form is", "graph.add_edge(from_address, to_address) function_name = self.die_db.get_function_name(function_context.function) viewer = sark.ui.NXGraph(graph, \"Callgraph for", "form): \"\"\" Called when the plugin form is created \"\"\"", "value. if ret_value is not None and ret_value.type == call_value.type:", "# If current object contains reference values, add them to", "value sent to 'on_exclude_func_adrs'\") if function.is_lib_func and function.lib_name is not", "parent.setChild(arg_count, 6, item_parsed_val_flag_call) parent.setChild(arg_count, 7, item_parsed_val_call) parent.setChild(arg_count, 8, item_parsed_val_flag_ret) parent.setChild(arg_count,", "250) self.functionTreeView.setColumnWidth(5, 100) self.functionTreeView.setColumnWidth(6, 20) self.functionTreeView.setColumnWidth(7, 450) self.functionTreeView.setColumnWidth(8, 20) self.functionTreeView.setColumnWidth(9,", "function for tmp_item in item_list_func: tmp_item.setBackground(QtGui.QColor(184, 223, 220)) item_function =", "to context menu slots action_exclude_func = QtWidgets.QAction(\"Exclude Function\", self.functionTreeView, triggered=lambda:", "self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0, 200) self.functionTreeView.setColumnWidth(1, 20) self.functionTreeView.setColumnWidth(2, 20) self.functionTreeView.setColumnWidth(3, 20)", "0: continue item_func_context_list = self._make_function_ea_item(function_context_list[0]) item_func_context_ea = item_func_context_list[0] item_function.appendRow(item_func_context_list) occurrence_num", "Function Header item_header = QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument Name\") model.setHorizontalHeaderItem(5, item_header) ###", "\"NULL\" if call_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\" if call_value.raw_value", "function_context_ea in func_context_dict: function_context_list = func_context_dict[function_context_ea] if not len(function_context_list) >", "QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count, 5, QtGui.QStandardItem(arg_name)) parent.setChild(arg_count, 6, item_parsed_val_flag_call) parent.setChild(arg_count, 7, item_parsed_val_call)", "(for example a item data value can be \"a123aa5672aa11112a\") for", "QtCore.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchRecursive _MatchExactly = QtCore.Qt.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.PositionAtTop", "ref_val.type, nest_depth+1) def _add_model_container_members(self, parent, call_value, ret_value, nest_depth=0): \"\"\" Add", "not None: parsed_val_data = hex(call_value.raw_value) if len(call_value.nested_values) > 0 or", "def _make_func_occur_item(self, function_context, occur_num): \"\"\" Build a tree item for", "\".*\" + self._make_thread_id_data(thread_id) + \".*\" threadProxyModel = _QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads)", "is_func_context_item = index.data(role=DIE.UI.FunctionContext_Role) is_value_item = index.data(role=DIE.UI.ParsedValueRole) if is_function_item is not", "bp_view = DIE.UI.BPView.get_view() bp_view.Show() ############################################################################################### # View Delegates. class TreeViewDelegate(QtWidgets.QStyledItemDelegate):", "if call_value.nested_values: for index in xrange(0, len(call_value.nested_values)): nested_val_call = self.die_db.get_dbg_value(call_value.nested_values[index])", "tree view \"\"\" def __init__(self, parent): QtWidgets.QStyledItemDelegate.__init__(self, parent) self.parent =", "self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(), _PositionAtTop) self.highlight_item_row(item) def find_context_list(self, context_list): \"\"\" Find and", "item_header) ### Call Value Header item_header = QtGui.QStandardItem(\"Call Value\") item_header.setToolTip(\"Argument`s", "column_num = parent.columnCount() for column in xrange(0, column_num): if self.functionModel.hasIndex(row,", "Function ea ContextMenu self.ea_context_menu = QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph) # Argument", "in FunctionView: %s\\n\" % ex) return False ############################################################################################### # Slots.", "QtGui.QStandardItem(\"Name\") item_header.setToolTip(\"Argument Name\") model.setHorizontalHeaderItem(5, item_header) ### Call Value Icon Header", "appended to a string of concatenated (unique) child-item thread-ids (for", "= parent def createEditor(self, parent, option, index): parsed_val_list = index.data(role=DIE.UI.ParsedValuesRole)", "== 0: parsed_val_data = \"!MAX_DEREF!\" if ret_value.raw_value is not None:", "Build a tree item for a function name (level-0) @param", "% (parsed_val.score, parsed_val.data, parsed_val.description) lines.append(line_txt) combo_box = QtWidgets.QComboBox(parent) combo_box.addItems(lines) return", "object contains reference values, add them to the module self._add_model_arg_ref(this_row_item,", "nest_depth+1) def reset_function_count(self, thread_id=None): \"\"\" Reset the function count and", "= func_context_dict[function_context_ea] if not len(function_context_list) > 0: continue item_func_context_list =", "threads = [] if self.die_db is not None: threads =", "self.parent.setLayout(layout) def OnClose(self, form): idaapi.msg(\"Closed\\n\") def isVisible(self): \"\"\" Is functionview", "curret_ret_arg_value = self.die_db.get_return_arg_value(function_context) for arg_index in xrange(0, function.arg_num): try: current_arg", "= self._make_nonexec_function_time(func_name) # # if function.is_lib_func: # Color library function", "@param ret_value: @param nest_depth: @return: \"\"\" # If call debug", "QtGui, QtCore, QtWidgets, form_to_widget, use_qt5 if use_qt5: _QSortFilterProxyModel = QtCore.QSortFilterProxyModel", "parent.setChild(arg_count, 9, item_parsed_val_ret) # If current object contains reference values,", "False ############################################################################################### # Slots. # @QtCore.Slot(QtCore.QModelIndex) def itemDoubleClickSlot(self, index): \"\"\"", "= cur_item.data(role=DIE.UI.Function_Role) if function is not None: count = 0", "ref_val_call.type, nest_depth+1) # If return debug value is a reference", "self.functionTreeView.setColumnWidth(2, 20) self.functionTreeView.setColumnWidth(3, 20) self.functionTreeView.setColumnWidth(4, 250) self.functionTreeView.setColumnWidth(5, 100) self.functionTreeView.setColumnWidth(6, 20)", "20) self.functionTreeView.setColumnWidth(7, 450) self.functionTreeView.setColumnWidth(8, 20) self.functionTreeView.setColumnWidth(9, 450) # Context menus", "QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role) # Inherit thread data from parent #", "self.context_menu_param = is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_func_context_item is not None: self.context_menu_param", "this_row_item = QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role), role=DIE.UI.ThreadId_Role) # Inherit thread data from", "as ex: idaapi.msg(\"Error while looking up function context in FunctionView:", "if not self.functionTreeView.model() is self.functionModel: self.functionTreeView.setModel(self.functionModel) return hidden_threads = \".*\"", "item_func_is_indirect.setEditable(False) if function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new = QtGui.QStandardItem() item_func_is_new.setEditable(False) if function_context.is_new_func:", "arg_ident_type = arg_ident + arg_type item_parsed_val_flag_call = QtGui.QStandardItem() item_parsed_val_call =", "% function.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name)", "entire row containing a table item @param item: table item", "self._make_model_headers(model) if self.die_db is None: return # Add db functions", "nest_depth=0): \"\"\" Add a debug value @param parent: @param call_value:", "\"VOID\" else: ret_arg_type = ret_arg.type # Add return argument self._add_model_arg_value(item_func_context,", "thread in threads: thread_id_list.append(str(thread.thread_num)) self.thread_id_combo = QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label", "on_pluginsview_button(self): plugins_view = DIE.UI.ParserView.get_view() plugins_view.Show() def on_bpview_button(self): bp_view = DIE.UI.BPView.get_view()", "String @param function_name: Function name @return: \"\"\" item_function = QtGui.QStandardItem(self.die_icons.icon_function,", "ex: idaapi.msg(\"Error while looking up function context in FunctionView: %s\\n\"", "self.functionTreeView, triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea = QtWidgets.QAction(\"Exclude Address\", self.functionTreeView, triggered=lambda: self.on_exclude_ea(self.context_menu_param))", "if not index.isValid(): continue # Do not highlight \"ea root\"", "index.data(role=DIE.UI.ParsedValueRole) if is_function_item is not None: self.context_menu_param = is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point))", "% ex) return False ############################################################################################### # Slots. # @QtCore.Slot(QtCore.QModelIndex) def", "if function_context.is_new_func: item_func_is_new.setIcon(self.die_icons.icon_v) item_list = [item_func_context_ea, QtGui.QStandardItem(), item_func_is_indirect, item_func_is_new, QtGui.QStandardItem(),", "function): \"\"\" Build a tree item for a function name", "item: the model item to add the data to @param", "library function # for tmp_item in item_list_func: # tmp_item.setBackground(QtGui.QColor(255, 0,", "\"\"\" return \"t%st\" % str(thread_id) def _insert_thread_data(self, item, thread_id): \"\"\"", "excpected dbFunction_Context\" % function.__class__) else: raise ValueError(\"Wrong value sent to", "= DIE.UI.BPView.get_view() bp_view.Show() ############################################################################################### # View Delegates. class TreeViewDelegate(QtWidgets.QStyledItemDelegate): \"\"\"", "function count according to currently selected thread if thread_id ==", "def _make_function_item(self, function): \"\"\" Build a tree item for a", "parsed_val_data = \"NULL\" if call_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\"", "is not) elif ret_value is not None: if ret_value.reference_flink is", "ret_value.is_definitely_parsed: ref_val = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, None, ref_val, ref_val.name, ref_val.type, nest_depth+1)", "(from_address, to_address) = ctxt_node graph.add_edge(from_address, to_address) function_name = self.die_db.get_function_name(function_context.function) viewer", "QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _add_model_arg_value(self, parent, call_value, ret_value, arg_name,", "(struct\\union\\etc) if call_value is not None and call_value.nested_values is not", "continue item = self.functionModel.itemFromIndex(index) self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index, _PositionAtTop) self.highlight_item_row(item) return True", "# Highlight Items. def highlight_item(self, item): \"\"\" Highlight a single", "idaapi.msg(\"Error while highlighting item: %s\\n\" %ex) def highlight_item_row(self, item): \"\"\"", "editor.blockSignals(False) # Singelton function_view = None def initialize(): global function_view", "Set the model horizontal header data @param model: the QStandardItemModel", "ea = function.proto_ea if ea is not None and ea", "table item @param item: table item \"\"\" try: if not", "function.function_start if function.is_lib_func: ea = function.proto_ea if ea is not", "sent to 'on_exclude_func_adrs'\") if function.is_lib_func and function.lib_name is not None:", "a tree item for a function name (level-0) @param function:", "item_func_is_indirect, item_func_is_new, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list", "item for the function \"\"\" function_txt = \"%s\" % function.function_name", "ret_arg.type # Add return argument self._add_model_arg_value(item_func_context, None, curret_ret_arg_value, \"ret_arg\", ret_arg_type)", "item_func_context_list[0] item_function.appendRow(item_func_context_list) occurrence_num = 0 for function_context in function_context_list: item_func_context_list", "parent, call_value, ret_value, nest_depth=0): \"\"\" Add container members to module", "class FunctionView(PluginForm): \"\"\" DIE Function View \"\"\" def __init__(self): super(FunctionView,", "thread data was successfully added to item, otherwise False \"\"\"", "def on_pluginsview_button(self): plugins_view = DIE.UI.ParserView.get_view() plugins_view.Show() def on_bpview_button(self): bp_view =", "ignored(sark.exceptions.SarkNoFunction): calling_function_start = sark.Function(function_context.calling_ea).startEA if calling_function_start is not None: call_offset", "elif ret_value is not None: if ret_value.nested_values is not None:", "awesome.context import ignored import sark import idaapi import idautils import", "return debug value. if ret_value is not None and ret_value.type", "then be appended to a string of concatenated (unique) child-item", "FunctionView(PluginForm): \"\"\" DIE Function View \"\"\" def __init__(self): super(FunctionView, self).__init__()", "item for the function context \"\"\" calling_function_start = None with", "if ret_value.nested_values or ret_value.reference_flink is not None: parsed_val_data = \"\"", "item.parent() if parent is None: parent = item if not", "if len(parsed_vals) > 1: # If more the 1 item,", "QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function Name\") model.setHorizontalHeaderItem(0, item_header) ### Call number header item_header", "function.is_lib_func: ea = function.proto_ea if ea is not None and", "more items. if parsed_val_list is not None and len(parsed_val_list) >", "= 0 for function_context in function_context_list: item_func_context_list = self._make_func_occur_item(function_context, occurrence_num)", "Name\") model.setHorizontalHeaderItem(5, item_header) ### Call Value Icon Header item_header =", "Value\") item_header.setToolTip(\"Argument`s value on function return\") model.setHorizontalHeaderItem(9, item_header) def _make_thread_id_data(self,", "otherwise False \"\"\" try: current_thread_id = self._make_thread_id_data(thread_id) thread_data = item.data(role=DIE.UI.ThreadId_Role)", "%s. excpected dbFunction_Context\" % function.__class__) else: raise ValueError(\"Wrong value sent", "item_header.setToolTip(\"Argument`s value on function call\") model.setHorizontalHeaderItem(7, item_header) ### Return Value", "= self.die_db.get_function_arg(function, arg_index) self._add_model_arg_value(item_func_context, current_call_values[arg_index], current_ret_values[arg_index], current_arg.name, current_arg.type) except IndexError:", "context_id, -1, _MatchRecursive | _MatchExactly) for index in matched_items: if", "= self.functionModel.index(row, column, parent.index()) self.highlight_item(self.functionModel.itemFromIndex(cur_index)) persistent_index = QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index) except", "call_value, ret_value, nest_depth=0): \"\"\" Add a reference value to module", "@type: String @param function_name: Function name @return: \"\"\" item_function =", "a function name (for a non-executed function) @type: String @param", "= QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True) delegate = TreeViewDelegate(self.functionTreeView) self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel)", "model.setHorizontalHeaderItem(9, item_header) def _make_thread_id_data(self, thread_id): \"\"\" Delimit thread_id data in", "dbFunction_Context\" % function_context.__class__) else: raise ValueError(\"Wrong value sent to 'on_exclude_ea'\")", "arg_index) self._add_model_arg_value(item_func_context, current_call_values[arg_index], current_ret_values[arg_index], current_arg.name, current_arg.type) except IndexError: break ret_arg", "self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs = QtWidgets.QAction(\"Exclude All Function Calls\", self.functionTreeView, triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param))", "QStandradItemModel item for the function \"\"\" function_txt = \"%s\" %", "module self._add_model_arg_ref(this_row_item, call_value, ret_value, nest_depth) # If current object is", "# Add function contexts ea\\occurrences for the current function func_context_dict", "Header item_header = QtGui.QStandardItem(\"Call Value\") item_header.setToolTip(\"Argument`s value on function call\")", "Used for module look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role) item_list = [item_func_context, QtGui.QStandardItem(),", "QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_nonexec_function_time(self, function_name): \"\"\"", "call_graph: idaapi.msg(\"No Execution Graph\") return for ctxt_node in call_graph: (from_address,", "a dbFunction_Context object @return: QStandradItemModel item for the function context", "the function context \"\"\" calling_function_start = None with ignored(sark.exceptions.SarkNoFunction): calling_function_start", "functions to the model for function in self.die_db.get_functions(): item_list_func =", "self.highligthed_items.append(persistent_index) except Exception as ex: idaapi.msg(\"Error while highlighting item row:", "parent.setChild(arg_count, 4, QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count, 5, QtGui.QStandardItem(arg_name)) parent.setChild(arg_count, 6, item_parsed_val_flag_call) parent.setChild(arg_count,", "+ \".*\" threadProxyModel = _QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel) def", "for ThreadId_Role \"\"\" return \"t%st\" % str(thread_id) def _insert_thread_data(self, item,", "ea is not None and ea is not idc.BADADDR: idc.Jump(ea)", "self.function_context_menu = QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs) # Function ea ContextMenu", "item row: %s\\n\" % ex) def clear_highlights(self): \"\"\" Clear all", "root_item.child(row, 0) function = cur_item.data(role=DIE.UI.Function_Role) if function is not None:", "# Try to get the same reference from the return", "data: %s\\n\" %ex) return False def _make_function_item(self, function): \"\"\" Build", "call_value is not None: parsed_vals = self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role) if", "# for func_ea in idautils.Functions(): # func_name = DIE.Lib.IDAConnector.get_function_name(func_ea) #", "self.functionTreeView.setItemDelegate(delegate) self.functionTreeView.doubleClicked.connect(self.itemDoubleClickSlot) self._model_builder(self.functionModel) self.functionTreeView.setModel(self.functionModel) self.functionTreeView.setColumnWidth(0, 200) self.functionTreeView.setColumnWidth(1, 20) self.functionTreeView.setColumnWidth(2, 20)", "def _make_model_headers(self, model): \"\"\" Set the model horizontal header data", "value is a container type (struct\\union\\etc) if call_value is not", "return parent = item.parent() if parent is None: parent =", "headers should be set \"\"\" ### Function Header item_header =", "function: dbFunction object @return: QStandradItemModel item for the function \"\"\"", "= None self.highligthed_items = [] def Show(self): # Reset highlighted", "QtGui.QStandardItem(), item_func_is_indirect, item_func_is_new, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()] return", "self.functionTreeView.setColumnWidth(8, 20) self.functionTreeView.setColumnWidth(9, 450) # Context menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) #", "None: ret_arg_type = \"VOID\" else: ret_arg_type = ret_arg.type # Add", "view \"\"\" def __init__(self, parent): QtWidgets.QStyledItemDelegate.__init__(self, parent) self.parent = parent", "item_parsed_val_flag_call) parent.setChild(arg_count, 7, item_parsed_val_call) parent.setChild(arg_count, 8, item_parsed_val_flag_ret) parent.setChild(arg_count, 9, item_parsed_val_ret)", "QStandardItemModel which headers should be set \"\"\" ### Function Header", "# Color library function for tmp_item in item_list_func: tmp_item.setBackground(QtGui.QColor(184, 223,", "func_occur_txt = \"Occur %s\" % str(occur_num) item_func_context = QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5)", "# # root_node.appendRow(item_list_func) def _make_model_headers(self, model): \"\"\" Set the model", "= \"!MAX_DEREF!\" if ret_value.raw_value is not None: parsed_val_data = hex(ret_value.raw_value)", "= self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret = None # Try to get the", "nested_val_call.name, nested_val_call.type, nest_depth+1) # If return value is a container", "= parent.columnCount() for column in xrange(0, column_num): if self.functionModel.hasIndex(row, column,", "self.die_db.get_dbg_value(call_value.nested_values[index]) nested_val_ret = None # Try to get the same", "\"\"\" try: current_thread_id = self._make_thread_id_data(thread_id) thread_data = item.data(role=DIE.UI.ThreadId_Role) if thread_data", "model root_node = model.invisibleRootItem() self._make_model_headers(model) if self.die_db is None: return", "None # Try to get the same reference from the", "= self.die_db.get_dbg_value(ret_value.nested_values[index]) self._add_model_arg_value(parent, nested_val_call, nested_val_ret, nested_val_call.name, nested_val_call.type, nest_depth+1) # If", "# tmp_item.setBackground(QtGui.QColor(255, 0, 0, 127)) # # root_node.appendRow(item_list_func) def _make_model_headers(self,", "is a reference if call_value is not None: if call_value.reference_flink", "a string of concatenated (unique) child-item thread-ids (for example a", "Call Value Header item_header = QtGui.QStandardItem(\"Call Value\") item_header.setToolTip(\"Argument`s value on", "@return: True if thread data was successfully added to item,", "index = self.functionTreeView.indexAt(point) is_function_item = index.data(role=DIE.UI.Function_Role) is_func_context_item = index.data(role=DIE.UI.FunctionContext_Role) is_value_item", "is not None: self.context_menu_param = is_function_item self.function_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) if is_func_context_item is", "plugin form is created \"\"\" self.value_view = DIE.UI.ValueViewEx.get_view() self.bp_handler =", "menu slots action_exclude_func = QtWidgets.QAction(\"Exclude Function\", self.functionTreeView, triggered=lambda: self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs", "function.arg_num): try: current_arg = self.die_db.get_function_arg(function, arg_index) self._add_model_arg_value(item_func_context, current_call_values[arg_index], current_ret_values[arg_index], current_arg.name,", "return # @QtCore.Slot(str) def on_exclude_library(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction):", "as ex: idaapi.msg(\"Error while inserting thread data: %s\\n\" %ex) return", "self.on_value_detail(self.context_menu_param)) action_show_callgraph = QtWidgets.QAction(\"Show Call-Graph\", self.functionTreeView, triggered=lambda: self.on_show_callgraph(self.context_menu_param)) # Function", "sent to 'on_show_callgraph'\") graph = nx.DiGraph() call_graph = self.die_db.get_call_graph_to(function_context) if", "child-item thread-ids (for example a item data value can be", "item): \"\"\" highlight the entire row containing a table item", "data in order to support filtering\\sorting on multi-thread data items", "item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else: item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if call_value.derref_depth", "Add function contexts ea\\occurrences for the current function func_context_dict =", "Items. def highlight_item(self, item): \"\"\" Highlight a single item @param", "item_header = QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect Call\") model.setHorizontalHeaderItem(2, item_header) ### Indirect Header", "return item_list def _make_nonexec_function_time(self, function_name): \"\"\" Build a tree item", "item.index().isValid(): return parent = item.parent() if parent is None: parent", "not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context is not None: raise ValueError(\"Wrong", "nest_depth arg_ident_type = arg_ident + arg_type item_parsed_val_flag_call = QtGui.QStandardItem() item_parsed_val_call", "item to add the data to @param thread_id: thread_id number", "if self.die_db is not None: threads = self.die_db.get_thread_list() thread_id_list =", "call_value.derref_depth == 0: parsed_val_data = \"!MAX_DEREF!\" if call_value.raw_value is not", "thread_id: thread_id number @return: True if thread data was successfully", "@param call_value: @param ret_value: @param arg_name: @param arg_type: @return: \"\"\"", "@return: QStandradItemModel item for the function context \"\"\" calling_function_start =", "idaapi.msg(\"No Execution Graph\") return for ctxt_node in call_graph: (from_address, to_address)", "None: return # Add db functions to the model for", "sark.ui.NXGraph(graph, \"Callgraph for {}\".format(function_name), handler=sark.ui.AddressNodeHandler()) viewer.Show() return # @QtCore.Slot(str) def", "members to the module self._add_model_container_members(this_row_item, call_value, ret_value, nest_depth) def _add_model_arg_ref(self,", "library function for tmp_item in item_list_func: tmp_item.setBackground(QtGui.QColor(184, 223, 220)) item_function", "reset function count according to currently selected thread if thread_id", "Argument value ContextMenu self.value_context_menu = QtWidgets.QMenu(self.functionTreeView) self.value_context_menu.addAction(action_value_detail) # Therad ComboBox", "in self.die_db.get_functions(): item_list_func = self._make_function_item(function) if function.is_lib_func: # Color library", "self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role) # If len(parsed_vals)>1 create a combobox delegate.", "import DIE.UI.BPView import DIE.Lib.IDAConnector import DIE.Lib.DIEDb import DIE.Lib.BpHandler import sark.ui", "item.setFont(cur_font) self.highligthed_items = [] except Exception as ex: idaapi.msg(\"Error while", "function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is not None:", "@param ret_value: @param nest_depth: @return: \"\"\" # If call value", "highlight a function in current module @param function_name: Function name", "[] if self.die_db is not None: threads = self.die_db.get_thread_list() thread_id_list", "0 or call_value.reference_flink is not None: parsed_val_data = \"\" item_parsed_val_call", "is not None and not call_value.is_definitely_parsed: ref_val_call = self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret", "ret_value: @param nest_depth: @return: \"\"\" # If call debug value", "if function.is_lib_func: ea = function.proto_ea if ea is not None", "ret_arg_type) # Increment occurrence counter occurrence_num += 1 # Add", "parent.setChild(arg_count, 8, item_parsed_val_flag_ret) parent.setChild(arg_count, 9, item_parsed_val_ret) # If current object", "(and call value is not) elif ret_value is not None:", "role=DIE.UI.ContextId_Role) # Used for module look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role) item_list =", "If current object is a container object, Add its members", "self._add_model_arg_ref(this_row_item, call_value, ret_value, nest_depth) # If current object is a", "call_value, ret_value, arg_name, arg_type, nest_depth=0): \"\"\" Add a debug value", "[item_function, item_function_count, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()]", "-1) if ret_arg is None: ret_arg_type = \"VOID\" else: ret_arg_type", "sark.ui class FunctionView(PluginForm): \"\"\" DIE Function View \"\"\" def __init__(self):", "True if thread data was successfully added to item, otherwise", "# Inherit thread data from parent # Set indentation for", "except Exception as ex: idaapi.msg(\"Error while highlighting item: %s\\n\" %ex)", "created \"\"\" self.value_view = DIE.UI.ValueViewEx.get_view() self.bp_handler = DIE.Lib.BpHandler.get_bp_handler() self.die_icons =", "QtGui.QStandardItem(parsed_val_data) # Get return value if ret_value is not None:", "(for a non-executed function) @type: String @param function_name: Function name", "None and not ret_value.is_definitely_parsed: ref_val = self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, None, ref_val,", "= self.die_db.get_function_context_dict(function) for function_context_ea in func_context_dict: function_context_list = func_context_dict[function_context_ea] if", "idc.BADADDR: idc.Jump(ea) return True # @QtCore.Slot(QtCore.QPoint) def onCustomContextMenu(self, point): index", "of calls preformed to this function\") model.setHorizontalHeaderItem(1, item_header) ### Indirect", "= self.die_db.count_function_occurs(function) else: count = self.die_db.count_function_occurs(function, int(thread_id)) func_count_item = root_item.child(row,", "a function in current module @param function_name: Function name \"\"\"", "calling_function_start = None with ignored(sark.exceptions.SarkNoFunction): calling_function_start = sark.Function(function_context.calling_ea).startEA if calling_function_start", "items @return: \"\"\" try: self.functionTreeView.collapseAll() for persistent_index in self.highligthed_items: if", "@param ret_value: @param arg_name: @param arg_type: @return: \"\"\" arg_count =", "for the function context \"\"\" calling_function_start = None with ignored(sark.exceptions.SarkNoFunction):", "role=DIE.UI.CallValue_Role) if parsed_vals is not None and len(parsed_vals) > 0:", "value): if not self.value_view.isVisible(): self.value_view.Show() self.value_view.find_value(value) return def on_thread_combobox_change(self, thread_id):", "module look-ups item_func_is_indirect = QtGui.QStandardItem() item_func_is_indirect.setEditable(False) if function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new", "a combobox delegate. if parsed_vals: is_guessed, best_val = self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret", "item for a function name (for a non-executed function) @type:", "ret_value is not None and ret_value.type == call_value.type: if ret_value.reference_flink", "if visible, otherwise False \"\"\" try: return self.functionTreeView.isVisible() except: return", "selected thread_id @param thread_id: currently selected thread_id \"\"\" root_item =", "if ret_value.raw_value is not None: parsed_val_data = hex(ret_value.raw_value) if ret_value.nested_values", "'on_show_callgraph'\") graph = nx.DiGraph() call_graph = self.die_db.get_call_graph_to(function_context) if not call_graph:", "self.context_menu_param = None # Parameter to be passed to context", "in call_graph: (from_address, to_address) = ctxt_node graph.add_edge(from_address, to_address) function_name =", "not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is not None: raise ValueError(\"Wrong", "and ret_value.type == call_value.type: if ret_value.nested_values is not None: if", "= QtWidgets.QLabel(\"Thread: \") # Toolbar self.function_toolbar = QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo)", "function_context is not None: raise ValueError(\"Wrong value sent to 'on_show_callgraph':", "in xrange(0, column_num): if self.functionModel.hasIndex(row, column, parent.index()): cur_index = self.functionModel.index(row,", "111112 @param item: the model item to add the data", "index.isValid(): continue # Do not highlight \"ea root\" items, only", "thread data from parent # Set indentation for argument types", "# If more the 1 item, show a combo-box item_parsed_val_ret.setData(parsed_vals,", "parsed_val.data, parsed_val.description) lines.append(line_txt) combo_box = QtWidgets.QComboBox(parent) combo_box.addItems(lines) return combo_box def", "QStandardItemModel object \"\"\" model.clear() # Clear the model root_node =", "in matched_items: if not index.isValid(): continue # Do not highlight", "Function ContextMenu self.function_context_menu = QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs) # Function", "# Function ea ContextMenu self.ea_context_menu = QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph) #", "def highlight_item(self, item): \"\"\" Highlight a single item @param item:", "look-ups item_func_is_indirect = QtGui.QStandardItem() item_func_is_indirect.setEditable(False) if function_context.is_indirect: item_func_is_indirect.setIcon(self.die_icons.icon_v) item_func_is_new =", "highlight a list of function contexts @param context_list: list of", "editor, index): editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False) # Singelton function_view = None", "model.setHorizontalHeaderItem(5, item_header) ### Call Value Icon Header item_header = QtGui.QStandardItem(\"\")", "= QtGui.QStandardItemModel() self.functionTreeView = QtWidgets.QTreeView() self.functionTreeView.setExpandsOnDoubleClick(False) #self.functionTreeView.setSortingEnabled(True) delegate = TreeViewDelegate(self.functionTreeView)", "Value Header item_header = QtGui.QStandardItem(\"Call Value\") item_header.setToolTip(\"Argument`s value on function", "argument will be delimited by the _make_thread_id_data function (e.g: thread_id", "id to normalize @return: a normalized string of the thread_id", "Get Call Value if call_value is not None: parsed_vals =", "1) func_count_item.setText(str(count)) ############################################################################################### # Highlight Items. def highlight_item(self, item): \"\"\"", "else: raise ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") func_context_list = self.die_db.get_function_context_list(function)", "parent def createEditor(self, parent, option, index): parsed_val_list = index.data(role=DIE.UI.ParsedValuesRole) #", "QtGui.QStandardItem()] return item_list def _add_model_arg_value(self, parent, call_value, ret_value, arg_name, arg_type,", "parent.setChild(arg_count, 3, QtGui.QStandardItem()) parent.setChild(arg_count, 4, QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count, 5, QtGui.QStandardItem(arg_name)) parent.setChild(arg_count,", "Function Calls\", self.functionTreeView, triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea = QtWidgets.QAction(\"Exclude Address\", self.functionTreeView,", "ContextMenu self.function_context_menu = QtWidgets.QMenu(self.functionTreeView) self.function_context_menu.addAction(action_exclude_func) self.function_context_menu.addAction(action_exclude_library) self.function_context_menu.addAction(action_exclude_func_adrs) # Function ea", "def on_valueview_button(self): value_view = DIE.UI.ValueViewEx.get_view() value_view.Show() def on_pluginsview_button(self): plugins_view =", "into a model item. The value found in thread_id argument", "== \"All Threads\": if not self.functionTreeView.model() is self.functionModel: self.functionTreeView.setModel(self.functionModel) return", "= self.die_db.get_dbg_value(ret_value.reference_flink) self._add_model_arg_value(parent, ref_val_call, ref_val_ret, ref_val_call.name, ref_val_call.type, nest_depth+1) # If", "if parsed_value as two or more items. if parsed_val_list is", "QModelIndex object of the clicked tree index item. @return: \"\"\"", "%s\\n\" % ex) ############################################################################################### # Find Items. def find_function(self, function_name):", "Value\") item_header.setToolTip(\"Argument`s value on function call\") model.setHorizontalHeaderItem(7, item_header) ### Return", "thread data: %s\\n\" %ex) return False def _make_function_item(self, function): \"\"\"", "def Show(self): # Reset highlighted items self.highligthed_items = [] return", "item. The value found in thread_id argument will be delimited", "item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module look-ups item_func_is_indirect", "in current module @param function_name: Function name \"\"\" self.clear_highlights() matched_items", "# Parameter to be passed to context menu slots action_exclude_func", "# Get Call Value if call_value is not None: parsed_vals", "6, item_parsed_val_flag_call) parent.setChild(arg_count, 7, item_parsed_val_call) parent.setChild(arg_count, 8, item_parsed_val_flag_ret) parent.setChild(arg_count, 9,", "%s\" % str(occur_num) item_func_context = QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5) item_func_context.setEditable(False) item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role)", "in threads: thread_id_list.append(str(thread.thread_num)) self.thread_id_combo = QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label =", "raise ValueError(\"Wrong value sent to 'on_show_callgraph': %s. excpected dbFunction_Context\" %", "for func_context in context_list: context_id = id(func_context) matched_items = self.functionModel.match(root_index,", "contexts ea\\occurrences for the current function func_context_dict = self.die_db.get_function_context_dict(function) for", "the delimited value will then be appended to a string", "number @return: True if thread data was successfully added to", "not call_value.is_definitely_parsed: ref_val_call = self.die_db.get_dbg_value(call_value.reference_flink) ref_val_ret = None # Try", "\"Occur %s\" % str(occur_num) item_func_context = QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5) item_func_context.setEditable(False) item_func_context.setData(function_context,", "\"\"\" try: if not item.index().isValid(): return parent = item.parent() if", "[] def Show(self): # Reset highlighted items self.highligthed_items = []", "QtGui.QStandardItem() item_parsed_val_call = QtGui.QStandardItem() item_parsed_val_flag_ret = QtGui.QStandardItem() item_parsed_val_ret = QtGui.QStandardItem()", "self.functionTreeView.expand(index) self.functionTreeView.scrollTo(index, _PositionAtTop) self.highlight_item_row(item) return True except Exception as ex:", "for parsed value viewing in the tree view \"\"\" def", "return True # @QtCore.Slot(QtCore.QPoint) def onCustomContextMenu(self, point): index = self.functionTreeView.indexAt(point)", "ex: idaapi.msg(\"Error while inserting thread data: %s\\n\" %ex) return False", "thread_id = self.thread_id_combo.currentText() for row in xrange(0, rows): cur_item =", "return # Add db functions to the model for function", "else: raise ValueError(\"Wrong value sent to 'on_show_callgraph'\") graph = nx.DiGraph()", "[item_func_context_ea, QtGui.QStandardItem(), item_func_is_indirect, item_func_is_new, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem()]", "If len(parsed_vals)>1 create a combobox delegate. if parsed_vals: is_guessed, best_val", "None: self.context_menu_param = is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) # @QtCore.Slot(str) def on_exclude_func(self, function):", "hex(call_offset)) else: func_ea_txt = \"[%s]:%s\" % (function_context.calling_func_name, hex(function_context.calling_ea)) item_func_context_ea =", "None: raise ValueError(\"Wrong value sent to 'on_exclude_ea': %s. excpected dbFunction_Context\"", "self.functionModel: self.functionTreeView.setModel(self.functionModel) return hidden_threads = \".*\" + self._make_thread_id_data(thread_id) + \".*\"", "not idc.BADADDR: idc.Jump(ea) return True func_context = index.data(role=DIE.UI.FunctionContext_Role) if func_context", "def on_exclude_ea(self, function_context): if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context is", "= \".*\" + self._make_thread_id_data(thread_id) + \".*\" threadProxyModel = _QSortFilterProxyModel() threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role)", "_make_thread_id_data(self, thread_id): \"\"\" Delimit thread_id data in order to support", "not None: parsed_val_data = \"\" item_parsed_val_ret = QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count, 0,", "item @param item: module item \"\"\" try: item.setBackground(QtGui.QColor('yellow')) cur_font =", "= self.die_db.get_call_values(function_context) current_ret_values = self.die_db.get_return_values(function_context) curret_ret_arg_value = self.die_db.get_return_arg_value(function_context) for arg_index", "ctxt_node in call_graph: (from_address, to_address) = ctxt_node graph.add_edge(from_address, to_address) function_name", "20) self.functionTreeView.setColumnWidth(2, 20) self.functionTreeView.setColumnWidth(3, 20) self.functionTreeView.setColumnWidth(4, 250) self.functionTreeView.setColumnWidth(5, 100) self.functionTreeView.setColumnWidth(6,", "value sent to 'on_exclude_func_adrs': %s. excpected dbFunction_Context\" % function.__class__) else:", "if func_context is not None: ea = func_context.calling_ea if ea", "QtWidgets.QAbstractItemView.PositionAtTop else: _QSortFilterProxyModel = QtGui.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly =", "If call value is a container type (struct\\union\\etc) if call_value", "item_list def _add_model_arg_value(self, parent, call_value, ret_value, arg_name, arg_type, nest_depth=0): \"\"\"", "Value Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6, item_header) ### Call", "item. @return: \"\"\" function = index.data(role=DIE.UI.Function_Role) if function is not", "= self._make_function_ea_item(function_context_list[0]) item_func_context_ea = item_func_context_list[0] item_function.appendRow(item_func_context_list) occurrence_num = 0 for", "function_context.__class__) else: raise ValueError(\"Wrong value sent to 'on_show_callgraph'\") graph =", "item for a function_ea node (level-1) @param function_context: a dbFunction_Context", "item: module item \"\"\" try: item.setBackground(QtGui.QColor('yellow')) cur_font = item.font() cur_font.setBold(True)", "Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(6, item_header) ### Call Value Header", "non-executed function) @type: String @param function_name: Function name @return: \"\"\"", "\"\"\" func_occur_txt = \"Occur %s\" % str(occur_num) item_func_context = QtGui.QStandardItem(func_occur_txt)", "(for nested values) arg_ident = \" \" * nest_depth arg_ident_type", "If current object contains reference values, add them to the", "5672 and 111112 @param item: the model item to add", "Header item_header = QtGui.QStandardItem(\"I\") item_header.setToolTip(\"Indirect Call\") model.setHorizontalHeaderItem(2, item_header) ### Indirect", "root_index.isValid(): return for func_context in context_list: context_id = id(func_context) matched_items", "model item to add the data to @param thread_id: thread_id", "Function View \"\"\" def __init__(self): super(FunctionView, self).__init__() self.value_view = None", "\"\"\" Add container members to module @param parent: @param call_value:", "QtGui.QStandardItem()] return item_list def _make_nonexec_function_time(self, function_name): \"\"\" Build a tree", "while clearing highlights: %s\\n\" % ex) ############################################################################################### # Find Items.", "arg_type item_parsed_val_flag_call = QtGui.QStandardItem() item_parsed_val_call = QtGui.QStandardItem() item_parsed_val_flag_ret = QtGui.QStandardItem()", "current_call_values = self.die_db.get_call_values(function_context) current_ret_values = self.die_db.get_return_values(function_context) curret_ret_arg_value = self.die_db.get_return_arg_value(function_context) for", "for tmp_item in item_list_func: tmp_item.setBackground(QtGui.QColor(184, 223, 220)) item_function = item_list_func[0]", "a tree item for a function_ea node (level-1) @param function_context:", "threads: thread_id_list.append(str(thread.thread_num)) self.thread_id_combo = QtWidgets.QComboBox() self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label = QtWidgets.QLabel(\"Thread:", "= QtGui.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchFlag.MatchRecursive _MatchExactly = QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop =", "containing a table item @param item: table item \"\"\" try:", "not None: parsed_vals = self.die_db.get_parsed_values(call_value) this_row_item.setData(parsed_vals, role=DIE.UI.CallValue_Role) if parsed_vals is", "item_func_context = QtGui.QStandardItem(func_occur_txt) item_func_context.setColumnCount(5) item_func_context.setEditable(False) item_func_context.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role) #", "is not None: parsed_val_data = hex(call_value.raw_value) if len(call_value.nested_values) > 0", "if ret_value.reference_flink is not None and not ret_value.is_definitely_parsed: ref_val_ret =", "QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1: # If", "None: if call_value.nested_values: for index in xrange(0, len(call_value.nested_values)): nested_val_call =", "not highlight \"ea root\" items, only occurrences of it. if", "combobox only if parsed_value as two or more items. if", "# Grid layout = QtWidgets.QGridLayout() layout.addWidget(self.function_toolbar) layout.addWidget(self.functionTreeView) self.parent.setLayout(layout) def OnClose(self,", "Items. def find_function(self, function_name): \"\"\" Find and highlight a function", "_PositionAtTop) self.highlight_item_row(item) def find_context_list(self, context_list): \"\"\" Find and highlight a", "call_value is not None: if call_value.reference_flink is not None and", "Add container members to module @param parent: @param call_value: @param", "nested_val_ret.name, nested_val_ret.type, nest_depth+1) def reset_function_count(self, thread_id=None): \"\"\" Reset the function", "if not root_index.isValid(): return for func_context in context_list: context_id =", "func_context = index.data(role=DIE.UI.FunctionContext_Role) if func_context is not None: ea =", "Context menus self.functionTreeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.functionTreeView.customContextMenuRequested.connect(self.onCustomContextMenu) # Actions self.context_menu_param = None #", "function name (level-0) @param function: dbFunction object @return: QStandradItemModel item", "sent to 'on_exclude_func_adrs'\") self.bp_handler.add_bp_funcname_exception(function.function_name) return # @QtCore.Slot(str) def on_exclude_func_adrs(self, function):", "nested_val_ret.type, nest_depth+1) def reset_function_count(self, thread_id=None): \"\"\" Reset the function count", "\"\"\" Build a tree item for a function_ea node (level-1)", "[] for parsed_val in parsed_val_list: line_txt = \"%d, %s, %s\"", "item_parsed_val_call.setData(parsed_vals, role=DIE.UI.ParsedValuesRole) item_parsed_val_flag_call.setIcon(self.die_icons.icon_more) else: item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\"", "None: parsed_val_data = \"\" item_parsed_val_ret = QtGui.QStandardItem(parsed_val_data) parent.setChild(arg_count, 0, this_row_item)", "a container object, Add its members to the module self._add_model_container_members(this_row_item,", "def _add_model_container_members(self, parent, call_value, ret_value, nest_depth=0): \"\"\" Add container members", "Find Items. def find_function(self, function_name): \"\"\" Find and highlight a", "self.functionTreeView.setColumnWidth(0, 200) self.functionTreeView.setColumnWidth(1, 20) self.functionTreeView.setColumnWidth(2, 20) self.functionTreeView.setColumnWidth(3, 20) self.functionTreeView.setColumnWidth(4, 250)", "not None: ea = func_context.calling_ea if ea is not None", "Reset highlighted items self.highligthed_items = [] return PluginForm.Show(self, \"Function View\",", "model): \"\"\" Build the function model. @param model: QStandardItemModel object", "# reset function count according to currently selected thread if", "self.thread_id_combo.addItems(thread_id_list) self.thread_id_combo.activated[str].connect(self.on_thread_combobox_change) self.thread_id_label = QtWidgets.QLabel(\"Thread: \") # Toolbar self.function_toolbar =", "value viewing in the tree view \"\"\" def __init__(self, parent):", "dbFunction object @return: QStandradItemModel item for the function \"\"\" function_txt", "in context_list: context_id = id(func_context) matched_items = self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id,", "Used for module look-ups item_func_is_indirect = QtGui.QStandardItem() item_func_is_indirect.setEditable(False) if function_context.is_indirect:", "None with ignored(sark.exceptions.SarkNoFunction): calling_function_start = sark.Function(function_context.calling_ea).startEA if calling_function_start is not", "(parsed_val.score, parsed_val.data, parsed_val.description) lines.append(line_txt) combo_box = QtWidgets.QComboBox(parent) combo_box.addItems(lines) return combo_box", "to be passed to context menu slots action_exclude_func = QtWidgets.QAction(\"Exclude", "= QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index) except Exception as ex: idaapi.msg(\"Error while highlighting", "QtCore.Qt.MatchRecursive _MatchExactly = QtCore.Qt.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.PositionAtTop else: _QSortFilterProxyModel =", "ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") if function.is_lib_func and function.lib_name is", "ret_arg is None: ret_arg_type = \"VOID\" else: ret_arg_type = ret_arg.type", "9, item_parsed_val_ret) # If current object contains reference values, add", "occurrence number @return: QStandradItemModel item for the function occurrence \"\"\"", "@return: True if visible, otherwise False \"\"\" try: return self.functionTreeView.isVisible()", "thread id to normalize @return: a normalized string of the", "Singelton function_view = None def initialize(): global function_view function_view =", "value is a reference (and call value is not) elif", "0, 127)) # # root_node.appendRow(item_list_func) def _make_model_headers(self, model): \"\"\" Set", "in matched_items: self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(), _PositionAtTop) self.highlight_item_row(item) def find_context_list(self, context_list): \"\"\"", "if self.die_db is None: return # Add db functions to", "arg_type: @return: \"\"\" arg_count = parent.rowCount() this_row_item = QtGui.QStandardItem(\"\") this_row_item.setData(parent.data(role=DIE.UI.ThreadId_Role),", "# Find Items. def find_function(self, function_name): \"\"\" Find and highlight", "not None: raise ValueError(\"Wrong value sent to 'on_show_callgraph': %s. excpected", "arg_name, arg_type, nest_depth=0): \"\"\" Add a debug value @param parent:", "= is_value_item self.value_context_menu.exec_(self.functionTreeView.mapToGlobal(point)) # @QtCore.Slot(str) def on_exclude_func(self, function): if not", "if function.is_lib_func and function.lib_name is not None: self.bp_handler.add_module_exception(function.lib_name) return #", "by the _make_thread_id_data function (e.g: thread_id 123 will become 't123t')", "action_exclude_func = QtWidgets.QAction(\"Exclude Function\", self.functionTreeView, triggered=lambda: self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs = QtWidgets.QAction(\"Exclude", "model item. The value found in thread_id argument will be", "(level-0) @param function: dbFunction object @return: QStandradItemModel item for the", "module look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role) item_list = [item_func_context, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "ret_value.reference_flink is not None and not ret_value.is_definitely_parsed: ref_val = self.die_db.get_dbg_value(ret_value.reference_flink)", "= self.functionModel.item(0, 0) rows = root_item.rowCount() thread_id = self.thread_id_combo.currentText() for", "int(thread_id)) func_count_item = root_item.child(row, 1) func_count_item.setText(str(count)) ############################################################################################### # Highlight Items.", "argument types (for nested values) arg_ident = \" \" *", "role=DIE.UI.FunctionContext_Role) item_func_context.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used for module look-ups item_func_context.setData(self._make_thread_id_data(function_context.thread_id), role=DIE.UI.ThreadId_Role)", "else: func_ea_txt = \"[%s]:%s\" % (function_context.calling_func_name, hex(function_context.calling_ea)) item_func_context_ea = QtGui.QStandardItem(func_ea_txt)", "cur_font = item.font() cur_font.setBold(True) item.setFont(cur_font) except Exception as ex: idaapi.msg(\"Error", "function.function_name item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_txt) item_function.setData(function, role=DIE.UI.Function_Role) function_count = self.die_db.count_function_occurs(function)", "item_list = [item_func_context, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "+ arg_type item_parsed_val_flag_call = QtGui.QStandardItem() item_parsed_val_call = QtGui.QStandardItem() item_parsed_val_flag_ret =", "parent): QtWidgets.QStyledItemDelegate.__init__(self, parent) self.parent = parent def createEditor(self, parent, option,", "= QtWidgets.QComboBox(parent) combo_box.addItems(lines) return combo_box def setEditorData(self, editor, index): editor.blockSignals(True)", "self.die_db.get_best_parsed_val(parsed_vals) item_parsed_val_ret = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if len(parsed_vals) >", "item_parsed_val_ret = QtGui.QStandardItem(best_val.data) if is_guessed: item_parsed_val_flag_ret.setIcon(self.die_icons.icon_question) if len(parsed_vals) > 1:", "list of function contexts (of type dbFunction_Context) \"\"\" try: self.clear_highlights()", "current module @param function_name: Function name \"\"\" self.clear_highlights() matched_items =", "if ret_value is not None: parsed_vals = self.die_db.get_parsed_values(ret_value) this_row_item.setData(parsed_vals, role=DIE.UI.RetValue_Role)", "QtGui.QStandardItem(), QtGui.QStandardItem()] return item_list def _make_nonexec_function_time(self, function_name): \"\"\" Build a", "= None # Try to get the same member from", "inserting thread data: %s\\n\" %ex) return False def _make_function_item(self, function):", "Inherit thread data from parent # Set indentation for argument", "node (level-1) @param function_context: a dbFunction_Context object @return: QStandradItemModel item", "combo_box def setEditorData(self, editor, index): editor.blockSignals(True) editor.setCurrentIndex(int(index.model().data(index))) editor.blockSignals(False) # Singelton", "for threads 123, 5672 and 111112 @param item: the model", "@param thread_id: currently selected thread_id \"\"\" root_item = self.functionModel.item(0, 0)", "threadProxyModel.setFilterRole(DIE.UI.ThreadId_Role) threadProxyModel.setFilterRegExp(hidden_threads) threadProxyModel.setSourceModel(self.functionModel) self.functionTreeView.setModel(threadProxyModel) def on_valueview_button(self): value_view = DIE.UI.ValueViewEx.get_view() value_view.Show()", "\"\"\" try: self.functionTreeView.collapseAll() for persistent_index in self.highligthed_items: if persistent_index.isValid(): item", "% ex) def clear_highlights(self): \"\"\" Clear all highlighted items @return:", "= [] thread_id_list.append(\"All Threads\") for thread in threads: thread_id_list.append(str(thread.thread_num)) self.thread_id_combo", "Add function arguments to each context current_call_values = self.die_db.get_call_values(function_context) current_ret_values", "will be delimited by the _make_thread_id_data function (e.g: thread_id 123", "matched_items: self.functionTreeView.expand(item.index()) self.functionTreeView.scrollTo(item.index(), _PositionAtTop) self.highlight_item_row(item) def find_context_list(self, context_list): \"\"\" Find", "context menu slots action_exclude_func = QtWidgets.QAction(\"Exclude Function\", self.functionTreeView, triggered=lambda: self.on_exclude_func(self.context_menu_param))", "triggered=lambda: self.on_exclude_func(self.context_menu_param)) action_exclude_func_adrs = QtWidgets.QAction(\"Exclude All Function Calls\", self.functionTreeView, triggered=lambda:", "nx from awesome.context import ignored import sark import idaapi import", "= QtCore.Qt.MatchFlag.MatchExactly _PositionAtTop = QtWidgets.QAbstractItemView.ScrollHint.PositionAtTop import DIE.UI.Die_Icons import DIE.UI.ValueViewEx import", "self.functionModel.itemFromIndex(persistent_index) item.setBackground(QtGui.QColor('white')) cur_font = item.font() cur_font.setBold(False) item.setFont(cur_font) self.highligthed_items = []", "Highlight Items. def highlight_item(self, item): \"\"\" Highlight a single item", "ValueError(\"Wrong value sent to 'on_exclude_func_adrs'\") func_context_list = self.die_db.get_function_context_list(function) for func_context", "self.function_toolbar = QtWidgets.QToolBar() self.function_toolbar.addWidget(self.thread_id_label) self.function_toolbar.addWidget(self.thread_id_combo) # Grid layout = QtWidgets.QGridLayout()", "@return: \"\"\" function = index.data(role=DIE.UI.Function_Role) if function is not None:", "elif not current_thread_id in thread_data: item.setData(thread_data + current_thread_id, role=DIE.UI.ThreadId_Role) return", "item_header.setToolTip(\"Indirect Call\") model.setHorizontalHeaderItem(2, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"N\")", "the entire row containing a table item @param item: table", "call debug value is a reference if call_value is not", "reference value to module @param parent: @param call_value: @param ret_value:", "self.functionTreeView, triggered=lambda: self.on_exclude_library(self.context_menu_param)) action_value_detail = QtWidgets.QAction(\"Inspect Value Details\", self.functionTreeView, triggered=lambda:", "Show(self): # Reset highlighted items self.highligthed_items = [] return PluginForm.Show(self,", "Header item_header = QtGui.QStandardItem(\"Function\") item_header.setToolTip(\"Function Name\") model.setHorizontalHeaderItem(0, item_header) ### Call", "persistent_index = QtCore.QPersistentModelIndex(cur_index) self.highligthed_items.append(persistent_index) except Exception as ex: idaapi.msg(\"Error while", "ea ContextMenu self.ea_context_menu = QtWidgets.QMenu(self.functionTreeView) self.ea_context_menu.addAction(action_exclude_ea) self.ea_context_menu.addAction(action_show_callgraph) # Argument value", "parent.setChild(arg_count, 2, QtGui.QStandardItem()) parent.setChild(arg_count, 3, QtGui.QStandardItem()) parent.setChild(arg_count, 4, QtGui.QStandardItem(arg_ident_type)) parent.setChild(arg_count,", "DIE.UI.Die_Icons.get_die_icons() self.die_db = DIE.Lib.DIEDb.get_db() # Get parent widget self.parent =", "None: if ret_value.nested_values is not None: if ret_value.nested_values: for nested_value", "if not isinstance(function_context, DIE.Lib.DIEDb.dbFunction_Context): if function_context is not None: raise", "= self._make_func_occur_item(function_context, occurrence_num) item_func_context = item_func_context_list[0] item_func_context_ea.appendRow(item_func_context_list) self._insert_thread_data(item_function, function_context.thread_id) self._insert_thread_data(item_func_context_ea,", "function to the model # for func_ea in idautils.Functions(): #", "else: item_parsed_val_call.setData(parsed_vals[0], role=DIE.UI.ParsedValueRole) else: parsed_val_data = \"NULL\" if call_value.derref_depth ==", "function_context in function_context_list: item_func_context_list = self._make_func_occur_item(function_context, occurrence_num) item_func_context = item_func_context_list[0]", "type (and call value is not) elif ret_value is not", "QtWidgets.QAction(\"Inspect Value Details\", self.functionTreeView, triggered=lambda: self.on_value_detail(self.context_menu_param)) action_show_callgraph = QtWidgets.QAction(\"Show Call-Graph\",", "get the same reference from the return debug value. if", "DIE.Lib.DIEDb.get_db() # Get parent widget self.parent = form_to_widget(form) self.functionModel =", "which headers should be set \"\"\" ### Function Header item_header", "model.setHorizontalHeaderItem(2, item_header) ### Indirect Header item_header = QtGui.QStandardItem(\"N\") item_header.setToolTip(\"New Function\")", "current object contains reference values, add them to the module", "Clear the model root_node = model.invisibleRootItem() self._make_model_headers(model) if self.die_db is", "= QtGui.QStandardItem(self.die_icons.icon_function, function_txt) item_function.setData(function, role=DIE.UI.Function_Role) function_count = self.die_db.count_function_occurs(function) item_function_count =", "def find_function(self, function_name): \"\"\" Find and highlight a function in", "= self.functionTreeView.indexAt(point) is_function_item = index.data(role=DIE.UI.Function_Role) is_func_context_item = index.data(role=DIE.UI.FunctionContext_Role) is_value_item =", "Calls\", self.functionTreeView, triggered=lambda: self.on_exclude_func_adrs(self.context_menu_param)) action_exclude_ea = QtWidgets.QAction(\"Exclude Address\", self.functionTreeView, triggered=lambda:", "Icon Header item_header = QtGui.QStandardItem(\"\") model.setHorizontalHeaderItem(8, item_header) ### Return Value", "arg_name: @param arg_type: @return: \"\"\" arg_count = parent.rowCount() this_row_item =", "thread_id_list = [] thread_id_list.append(\"All Threads\") for thread in threads: thread_id_list.append(str(thread.thread_num))", "QtGui.QStandardItem(func_ea_txt) item_func_context_ea.setEditable(False) item_func_context_ea.setData(hex(function_context.calling_ea), role=QtCore.Qt.ToolTipRole) item_func_context_ea.setData(function_context, role=DIE.UI.FunctionContext_Role) item_func_context_ea.setData(id(function_context), role=DIE.UI.ContextId_Role) # Used", "on_exclude_func(self, function): if not isinstance(function, DIE.Lib.DIEDb.dbFunction): if function is not", "_PositionAtTop = QtWidgets.QAbstractItemView.PositionAtTop else: _QSortFilterProxyModel = QtGui.QSortFilterProxyModel _MatchRecursive = QtCore.Qt.MatchFlag.MatchRecursive", "% function.function_name item_function = QtGui.QStandardItem(self.die_icons.icon_function, function_txt) item_function.setData(function, role=DIE.UI.Function_Role) function_count =", "data @param model: the QStandardItemModel which headers should be set", "QtGui.QStandardItem(\"#\") item_header.setToolTip(\"Number of calls preformed to this function\") model.setHorizontalHeaderItem(1, item_header)", "item_function_count.setEditable(False) item_function.setEditable(False) item_list = [item_function, item_function_count, QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(), QtGui.QStandardItem(),", "= QtWidgets.QAction(\"Exclude Library\", self.functionTreeView, triggered=lambda: self.on_exclude_library(self.context_menu_param)) action_value_detail = QtWidgets.QAction(\"Inspect Value", "parsed_val in parsed_val_list: line_txt = \"%d, %s, %s\" % (parsed_val.score,", "not None: if ret_value.nested_values: for nested_value in ret_value.nested_values: nested_val_ret =" ]
[ "False super().__init__() async def on_ready(self): stringifiedUserId = str(self.args['userId']) self.logger =", "super().__init__() async def on_ready(self): stringifiedUserId = str(self.args['userId']) self.logger = Logger.getLogger(\"PeerBot", "args): return { 'user' : await self.fetch_user(int(args['userId'])), 'protocolChannel' : await", "discord class PeerBot(discord.Client): def __init__(self, args): self.args = args self.isBotReady", "def on_message(self, message): if self.isBotReady: self.logger.trace(\"on_message called\") self.stateMachine.execute(message) async def", "self.stateMachine = PeerBotStateMachine(await self._getStateMachineArgs(self.args)) self.isBotReady = True self.stateMachine.start() async def", "async def on_ready(self): stringifiedUserId = str(self.args['userId']) self.logger = Logger.getLogger(\"PeerBot -", "+ stringifiedUserId) self.logger.trace(\"on_ready called\") self.stateMachine = PeerBotStateMachine(await self._getStateMachineArgs(self.args)) self.isBotReady =", "stringifiedUserId = str(self.args['userId']) self.logger = Logger.getLogger(\"PeerBot - \" + stringifiedUserId)", "await self.fetch_user(int(args['userId'])), 'protocolChannel' : await self.fetch_channel(int(args['protocolChannelId'])), 'appInfo' : await self.application_info()", "self.isBotReady: self.logger.trace(\"on_message called\") self.stateMachine.execute(message) async def _getStateMachineArgs(self, args): return {", "= PeerBotStateMachine(await self._getStateMachineArgs(self.args)) self.isBotReady = True self.stateMachine.start() async def on_message(self,", "True self.stateMachine.start() async def on_message(self, message): if self.isBotReady: self.logger.trace(\"on_message called\")", "self.isBotReady = False super().__init__() async def on_ready(self): stringifiedUserId = str(self.args['userId'])", "on_ready(self): stringifiedUserId = str(self.args['userId']) self.logger = Logger.getLogger(\"PeerBot - \" +", "self.fetch_user(int(args['userId'])), 'protocolChannel' : await self.fetch_channel(int(args['protocolChannelId'])), 'appInfo' : await self.application_info() }", "PeerBot(discord.Client): def __init__(self, args): self.args = args self.isBotReady = False", "self.logger.trace(\"on_message called\") self.stateMachine.execute(message) async def _getStateMachineArgs(self, args): return { 'user'", "called\") self.stateMachine.execute(message) async def _getStateMachineArgs(self, args): return { 'user' :", "called\") self.stateMachine = PeerBotStateMachine(await self._getStateMachineArgs(self.args)) self.isBotReady = True self.stateMachine.start() async", "args): self.args = args self.isBotReady = False super().__init__() async def", "self._getStateMachineArgs(self.args)) self.isBotReady = True self.stateMachine.start() async def on_message(self, message): if", ": await self.fetch_user(int(args['userId'])), 'protocolChannel' : await self.fetch_channel(int(args['protocolChannelId'])), 'appInfo' : await", "def _getStateMachineArgs(self, args): return { 'user' : await self.fetch_user(int(args['userId'])), 'protocolChannel'", "message): if self.isBotReady: self.logger.trace(\"on_message called\") self.stateMachine.execute(message) async def _getStateMachineArgs(self, args):", "def __init__(self, args): self.args = args self.isBotReady = False super().__init__()", "'user' : await self.fetch_user(int(args['userId'])), 'protocolChannel' : await self.fetch_channel(int(args['protocolChannelId'])), 'appInfo' :", "async def _getStateMachineArgs(self, args): return { 'user' : await self.fetch_user(int(args['userId'])),", "= str(self.args['userId']) self.logger = Logger.getLogger(\"PeerBot - \" + stringifiedUserId) self.logger.trace(\"on_ready", "self.stateMachine.execute(message) async def _getStateMachineArgs(self, args): return { 'user' : await", "utils.Logger import Logger import discord class PeerBot(discord.Client): def __init__(self, args):", "= False super().__init__() async def on_ready(self): stringifiedUserId = str(self.args['userId']) self.logger", "= True self.stateMachine.start() async def on_message(self, message): if self.isBotReady: self.logger.trace(\"on_message", "\" + stringifiedUserId) self.logger.trace(\"on_ready called\") self.stateMachine = PeerBotStateMachine(await self._getStateMachineArgs(self.args)) self.isBotReady", "- \" + stringifiedUserId) self.logger.trace(\"on_ready called\") self.stateMachine = PeerBotStateMachine(await self._getStateMachineArgs(self.args))", "stringifiedUserId) self.logger.trace(\"on_ready called\") self.stateMachine = PeerBotStateMachine(await self._getStateMachineArgs(self.args)) self.isBotReady = True", "on_message(self, message): if self.isBotReady: self.logger.trace(\"on_message called\") self.stateMachine.execute(message) async def _getStateMachineArgs(self,", "if self.isBotReady: self.logger.trace(\"on_message called\") self.stateMachine.execute(message) async def _getStateMachineArgs(self, args): return", "return { 'user' : await self.fetch_user(int(args['userId'])), 'protocolChannel' : await self.fetch_channel(int(args['protocolChannelId'])),", "{ 'user' : await self.fetch_user(int(args['userId'])), 'protocolChannel' : await self.fetch_channel(int(args['protocolChannelId'])), 'appInfo'", "class PeerBot(discord.Client): def __init__(self, args): self.args = args self.isBotReady =", "str(self.args['userId']) self.logger = Logger.getLogger(\"PeerBot - \" + stringifiedUserId) self.logger.trace(\"on_ready called\")", "import Logger import discord class PeerBot(discord.Client): def __init__(self, args): self.args", "from peerbot.PeerBotStateMachine import PeerBotStateMachine from utils.Logger import Logger import discord", "__init__(self, args): self.args = args self.isBotReady = False super().__init__() async", "PeerBotStateMachine from utils.Logger import Logger import discord class PeerBot(discord.Client): def", "Logger.getLogger(\"PeerBot - \" + stringifiedUserId) self.logger.trace(\"on_ready called\") self.stateMachine = PeerBotStateMachine(await", "self.stateMachine.start() async def on_message(self, message): if self.isBotReady: self.logger.trace(\"on_message called\") self.stateMachine.execute(message)", "from utils.Logger import Logger import discord class PeerBot(discord.Client): def __init__(self,", "= Logger.getLogger(\"PeerBot - \" + stringifiedUserId) self.logger.trace(\"on_ready called\") self.stateMachine =", "def on_ready(self): stringifiedUserId = str(self.args['userId']) self.logger = Logger.getLogger(\"PeerBot - \"", "async def on_message(self, message): if self.isBotReady: self.logger.trace(\"on_message called\") self.stateMachine.execute(message) async", "PeerBotStateMachine(await self._getStateMachineArgs(self.args)) self.isBotReady = True self.stateMachine.start() async def on_message(self, message):", "self.args = args self.isBotReady = False super().__init__() async def on_ready(self):", "_getStateMachineArgs(self, args): return { 'user' : await self.fetch_user(int(args['userId'])), 'protocolChannel' :", "self.isBotReady = True self.stateMachine.start() async def on_message(self, message): if self.isBotReady:", "= args self.isBotReady = False super().__init__() async def on_ready(self): stringifiedUserId", "import discord class PeerBot(discord.Client): def __init__(self, args): self.args = args", "peerbot.PeerBotStateMachine import PeerBotStateMachine from utils.Logger import Logger import discord class", "self.logger.trace(\"on_ready called\") self.stateMachine = PeerBotStateMachine(await self._getStateMachineArgs(self.args)) self.isBotReady = True self.stateMachine.start()", "self.logger = Logger.getLogger(\"PeerBot - \" + stringifiedUserId) self.logger.trace(\"on_ready called\") self.stateMachine", "<reponame>danerprog/PeerHostedDiscordBot from peerbot.PeerBotStateMachine import PeerBotStateMachine from utils.Logger import Logger import", "import PeerBotStateMachine from utils.Logger import Logger import discord class PeerBot(discord.Client):", "args self.isBotReady = False super().__init__() async def on_ready(self): stringifiedUserId =", "Logger import discord class PeerBot(discord.Client): def __init__(self, args): self.args =" ]
[ "= TokenManager(github_tokens) proxy_accommodator = GithubTokenProxyAccommodator(token_manager, proxy_manager, shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner =", "proxies = [] for line in proxy_confs['reserved_proxies']: proxies.append(f'http://{line}') proxy_service =", "DAG from airflow.operators.python import PythonOperator # v0.0.1 from oss_know.libs.base_dict.variable_key import", "params[\"repo\"] # since = params[\"since\"] since = None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner,", "deserialize_json=True) opensearch_conn_info = Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True) proxy_confs = Variable.get(PROXY_CONFS, deserialize_json=True) proxies", ") as dag: def scheduler_init_github_issues_timeline(ds, **kwargs): return 'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline =", "proxies.append(f'http://{line}') proxy_service = KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid']) proxy_manager = ProxyManager(proxies, proxy_service) token_manager", "oss_know.libs.util.token import TokenManager with DAG( dag_id='github_init_issues_timeline_v1', schedule_interval=None, start_date=datetime(2000, 1, 1),", "= [] from airflow.models import Variable need_init_github_issues_timeline_repos = Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True)", "for need_init_github_issues_timeline_repo in need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline = PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"], repo=need_init_github_issues_timeline_repo[\"repo\"]),", "do_init_github_issues_timeline(params): from airflow.models import Variable from oss_know.libs.github import init_issues_timeline github_tokens", "Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True) for need_init_github_issues_timeline_repo in need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline = PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format(", "PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"], repo=need_init_github_issues_timeline_repo[\"repo\"]), python_callable=do_init_github_issues_timeline, op_kwargs={'params': need_init_github_issues_timeline_repo}, ) op_scheduler_init_github_issues_timeline >>", "schedule_interval=None, start_date=datetime(2000, 1, 1), catchup=False, tags=['github'], ) as dag: def", "oss_know.libs.base_dict.variable_key import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS, \\ OPENSEARCH_CONN_DATA, PROXY_CONFS from oss_know.libs.util.proxy import", "from airflow import DAG from airflow.operators.python import PythonOperator # v0.0.1", "proxy_confs = Variable.get(PROXY_CONFS, deserialize_json=True) proxies = [] for line in", "from airflow.models import Variable need_init_github_issues_timeline_repos = Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True) for need_init_github_issues_timeline_repo", "= [] for line in proxy_confs['reserved_proxies']: proxies.append(f'http://{line}') proxy_service = KuaiProxyService(proxy_confs['api_url'],", "from airflow.models import Variable from oss_know.libs.github import init_issues_timeline github_tokens =", "Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True) proxy_confs = Variable.get(PROXY_CONFS, deserialize_json=True) proxies = [] for", "proxy_manager = ProxyManager(proxies, proxy_service) token_manager = TokenManager(github_tokens) proxy_accommodator = GithubTokenProxyAccommodator(token_manager,", "need_init_github_issues_timeline_repos = Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True) for need_init_github_issues_timeline_repo in need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline =", "need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline = PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"], repo=need_init_github_issues_timeline_repo[\"repo\"]), python_callable=do_init_github_issues_timeline, op_kwargs={'params': need_init_github_issues_timeline_repo},", "proxy_accommodator, since) return params need_do_init_ops = [] from airflow.models import", "params[\"owner\"] repo = params[\"repo\"] # since = params[\"since\"] since =", "= GithubTokenProxyAccommodator(token_manager, proxy_manager, shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner = params[\"owner\"] repo =", "KuaiProxyService, ProxyManager, GithubTokenProxyAccommodator from oss_know.libs.util.token import TokenManager with DAG( dag_id='github_init_issues_timeline_v1',", "= params[\"repo\"] # since = params[\"since\"] since = None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info,", "start_date=datetime(2000, 1, 1), catchup=False, tags=['github'], ) as dag: def scheduler_init_github_issues_timeline(ds,", "policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner = params[\"owner\"] repo = params[\"repo\"] # since =", "from oss_know.libs.github import init_issues_timeline github_tokens = Variable.get(GITHUB_TOKENS, deserialize_json=True) opensearch_conn_info =", "= KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid']) proxy_manager = ProxyManager(proxies, proxy_service) token_manager = TokenManager(github_tokens)", "Variable.get(GITHUB_TOKENS, deserialize_json=True) opensearch_conn_info = Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True) proxy_confs = Variable.get(PROXY_CONFS, deserialize_json=True)", "python_callable=scheduler_init_github_issues_timeline ) def do_init_github_issues_timeline(params): from airflow.models import Variable from oss_know.libs.github", "with DAG( dag_id='github_init_issues_timeline_v1', schedule_interval=None, start_date=datetime(2000, 1, 1), catchup=False, tags=['github'], )", "task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline ) def do_init_github_issues_timeline(params): from airflow.models import Variable from", "repo, proxy_accommodator, since) return params need_do_init_ops = [] from airflow.models", "from oss_know.libs.util.proxy import KuaiProxyService, ProxyManager, GithubTokenProxyAccommodator from oss_know.libs.util.token import TokenManager", "import KuaiProxyService, ProxyManager, GithubTokenProxyAccommodator from oss_know.libs.util.token import TokenManager with DAG(", "dag_id='github_init_issues_timeline_v1', schedule_interval=None, start_date=datetime(2000, 1, 1), catchup=False, tags=['github'], ) as dag:", "v0.0.1 from oss_know.libs.base_dict.variable_key import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS, \\ OPENSEARCH_CONN_DATA, PROXY_CONFS from", "= PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"], repo=need_init_github_issues_timeline_repo[\"repo\"]), python_callable=do_init_github_issues_timeline, op_kwargs={'params': need_init_github_issues_timeline_repo}, ) op_scheduler_init_github_issues_timeline", "= params[\"owner\"] repo = params[\"repo\"] # since = params[\"since\"] since", "oss_know.libs.util.proxy import KuaiProxyService, ProxyManager, GithubTokenProxyAccommodator from oss_know.libs.util.token import TokenManager with", "proxy_accommodator = GithubTokenProxyAccommodator(token_manager, proxy_manager, shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner = params[\"owner\"] repo", "return 'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline = PythonOperator( task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline ) def do_init_github_issues_timeline(params):", "return params need_do_init_ops = [] from airflow.models import Variable need_init_github_issues_timeline_repos", "deserialize_json=True) for need_init_github_issues_timeline_repo in need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline = PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"],", "since = params[\"since\"] since = None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner, repo, proxy_accommodator,", "= None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner, repo, proxy_accommodator, since) return params need_do_init_ops", "ProxyManager(proxies, proxy_service) token_manager = TokenManager(github_tokens) proxy_accommodator = GithubTokenProxyAccommodator(token_manager, proxy_manager, shuffle=True,", "from datetime import datetime from airflow import DAG from airflow.operators.python", "from oss_know.libs.base_dict.variable_key import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS, \\ OPENSEARCH_CONN_DATA, PROXY_CONFS from oss_know.libs.util.proxy", "from oss_know.libs.util.token import TokenManager with DAG( dag_id='github_init_issues_timeline_v1', schedule_interval=None, start_date=datetime(2000, 1,", "def do_init_github_issues_timeline(params): from airflow.models import Variable from oss_know.libs.github import init_issues_timeline", "ProxyManager, GithubTokenProxyAccommodator from oss_know.libs.util.token import TokenManager with DAG( dag_id='github_init_issues_timeline_v1', schedule_interval=None,", "airflow.models import Variable need_init_github_issues_timeline_repos = Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True) for need_init_github_issues_timeline_repo in", "import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS, \\ OPENSEARCH_CONN_DATA, PROXY_CONFS from oss_know.libs.util.proxy import KuaiProxyService,", "import PythonOperator # v0.0.1 from oss_know.libs.base_dict.variable_key import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS, \\", "init_issues_timeline github_tokens = Variable.get(GITHUB_TOKENS, deserialize_json=True) opensearch_conn_info = Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True) proxy_confs", "airflow import DAG from airflow.operators.python import PythonOperator # v0.0.1 from", "in need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline = PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"], repo=need_init_github_issues_timeline_repo[\"repo\"]), python_callable=do_init_github_issues_timeline, op_kwargs={'params':", "\\ OPENSEARCH_CONN_DATA, PROXY_CONFS from oss_know.libs.util.proxy import KuaiProxyService, ProxyManager, GithubTokenProxyAccommodator from", "TokenManager with DAG( dag_id='github_init_issues_timeline_v1', schedule_interval=None, start_date=datetime(2000, 1, 1), catchup=False, tags=['github'],", "Variable.get(PROXY_CONFS, deserialize_json=True) proxies = [] for line in proxy_confs['reserved_proxies']: proxies.append(f'http://{line}')", "airflow.models import Variable from oss_know.libs.github import init_issues_timeline github_tokens = Variable.get(GITHUB_TOKENS,", "= ProxyManager(proxies, proxy_service) token_manager = TokenManager(github_tokens) proxy_accommodator = GithubTokenProxyAccommodator(token_manager, proxy_manager,", "PythonOperator # v0.0.1 from oss_know.libs.base_dict.variable_key import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS, \\ OPENSEARCH_CONN_DATA,", "import TokenManager with DAG( dag_id='github_init_issues_timeline_v1', schedule_interval=None, start_date=datetime(2000, 1, 1), catchup=False,", "line in proxy_confs['reserved_proxies']: proxies.append(f'http://{line}') proxy_service = KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid']) proxy_manager =", "= params[\"since\"] since = None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner, repo, proxy_accommodator, since)", "import Variable from oss_know.libs.github import init_issues_timeline github_tokens = Variable.get(GITHUB_TOKENS, deserialize_json=True)", "# since = params[\"since\"] since = None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner, repo,", "owner, repo, proxy_accommodator, since) return params need_do_init_ops = [] from", "datetime from airflow import DAG from airflow.operators.python import PythonOperator #", "import DAG from airflow.operators.python import PythonOperator # v0.0.1 from oss_know.libs.base_dict.variable_key", "OPENSEARCH_CONN_DATA, PROXY_CONFS from oss_know.libs.util.proxy import KuaiProxyService, ProxyManager, GithubTokenProxyAccommodator from oss_know.libs.util.token", "as dag: def scheduler_init_github_issues_timeline(ds, **kwargs): return 'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline = PythonOperator(", "# v0.0.1 from oss_know.libs.base_dict.variable_key import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS, \\ OPENSEARCH_CONN_DATA, PROXY_CONFS", "tags=['github'], ) as dag: def scheduler_init_github_issues_timeline(ds, **kwargs): return 'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline", "NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS, \\ OPENSEARCH_CONN_DATA, PROXY_CONFS from oss_know.libs.util.proxy import KuaiProxyService, ProxyManager,", "PythonOperator( task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline ) def do_init_github_issues_timeline(params): from airflow.models import Variable", "Variable from oss_know.libs.github import init_issues_timeline github_tokens = Variable.get(GITHUB_TOKENS, deserialize_json=True) opensearch_conn_info", "catchup=False, tags=['github'], ) as dag: def scheduler_init_github_issues_timeline(ds, **kwargs): return 'End:scheduler_init_github_issues_timeline'", "GithubTokenProxyAccommodator(token_manager, proxy_manager, shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner = params[\"owner\"] repo = params[\"repo\"]", "= Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True) for need_init_github_issues_timeline_repo in need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline = PythonOperator(", "= Variable.get(GITHUB_TOKENS, deserialize_json=True) opensearch_conn_info = Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True) proxy_confs = Variable.get(PROXY_CONFS,", "proxy_confs['orderid']) proxy_manager = ProxyManager(proxies, proxy_service) token_manager = TokenManager(github_tokens) proxy_accommodator =", "proxy_manager, shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner = params[\"owner\"] repo = params[\"repo\"] #", "dag: def scheduler_init_github_issues_timeline(ds, **kwargs): return 'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline = PythonOperator( task_id='op_scheduler_init_github_issues_timeline',", "datetime import datetime from airflow import DAG from airflow.operators.python import", "KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid']) proxy_manager = ProxyManager(proxies, proxy_service) token_manager = TokenManager(github_tokens) proxy_accommodator", "token_manager = TokenManager(github_tokens) proxy_accommodator = GithubTokenProxyAccommodator(token_manager, proxy_manager, shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner", "GITHUB_TOKENS, \\ OPENSEARCH_CONN_DATA, PROXY_CONFS from oss_know.libs.util.proxy import KuaiProxyService, ProxyManager, GithubTokenProxyAccommodator", "'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline = PythonOperator( task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline ) def do_init_github_issues_timeline(params): from", "GithubTokenProxyAccommodator from oss_know.libs.util.token import TokenManager with DAG( dag_id='github_init_issues_timeline_v1', schedule_interval=None, start_date=datetime(2000,", "op_scheduler_init_github_issues_timeline = PythonOperator( task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline ) def do_init_github_issues_timeline(params): from airflow.models", "import init_issues_timeline github_tokens = Variable.get(GITHUB_TOKENS, deserialize_json=True) opensearch_conn_info = Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True)", "oss_know.libs.github import init_issues_timeline github_tokens = Variable.get(GITHUB_TOKENS, deserialize_json=True) opensearch_conn_info = Variable.get(OPENSEARCH_CONN_DATA,", "PROXY_CONFS from oss_know.libs.util.proxy import KuaiProxyService, ProxyManager, GithubTokenProxyAccommodator from oss_know.libs.util.token import", "shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner = params[\"owner\"] repo = params[\"repo\"] # since", "for line in proxy_confs['reserved_proxies']: proxies.append(f'http://{line}') proxy_service = KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid']) proxy_manager", ") def do_init_github_issues_timeline(params): from airflow.models import Variable from oss_know.libs.github import", "task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"], repo=need_init_github_issues_timeline_repo[\"repo\"]), python_callable=do_init_github_issues_timeline, op_kwargs={'params': need_init_github_issues_timeline_repo}, ) op_scheduler_init_github_issues_timeline >> op_do_init_github_issues_timeline", "**kwargs): return 'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline = PythonOperator( task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline ) def", "import datetime from airflow import DAG from airflow.operators.python import PythonOperator", "owner = params[\"owner\"] repo = params[\"repo\"] # since = params[\"since\"]", "deserialize_json=True) proxies = [] for line in proxy_confs['reserved_proxies']: proxies.append(f'http://{line}') proxy_service", "repo = params[\"repo\"] # since = params[\"since\"] since = None", "Variable need_init_github_issues_timeline_repos = Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True) for need_init_github_issues_timeline_repo in need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline", "TokenManager(github_tokens) proxy_accommodator = GithubTokenProxyAccommodator(token_manager, proxy_manager, shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP) owner = params[\"owner\"]", "DAG( dag_id='github_init_issues_timeline_v1', schedule_interval=None, start_date=datetime(2000, 1, 1), catchup=False, tags=['github'], ) as", "github_tokens = Variable.get(GITHUB_TOKENS, deserialize_json=True) opensearch_conn_info = Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True) proxy_confs =", "[] for line in proxy_confs['reserved_proxies']: proxies.append(f'http://{line}') proxy_service = KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid'])", "1), catchup=False, tags=['github'], ) as dag: def scheduler_init_github_issues_timeline(ds, **kwargs): return", "proxy_service = KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid']) proxy_manager = ProxyManager(proxies, proxy_service) token_manager =", "= PythonOperator( task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline ) def do_init_github_issues_timeline(params): from airflow.models import", "proxy_confs['reserved_proxies']: proxies.append(f'http://{line}') proxy_service = KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid']) proxy_manager = ProxyManager(proxies, proxy_service)", "init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner, repo, proxy_accommodator, since) return params need_do_init_ops = []", "1, 1), catchup=False, tags=['github'], ) as dag: def scheduler_init_github_issues_timeline(ds, **kwargs):", "import Variable need_init_github_issues_timeline_repos = Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True) for need_init_github_issues_timeline_repo in need_init_github_issues_timeline_repos:", "params[\"since\"] since = None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner, repo, proxy_accommodator, since) return", "from airflow.operators.python import PythonOperator # v0.0.1 from oss_know.libs.base_dict.variable_key import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS,", "op_do_init_github_issues_timeline = PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"], repo=need_init_github_issues_timeline_repo[\"repo\"]), python_callable=do_init_github_issues_timeline, op_kwargs={'params': need_init_github_issues_timeline_repo}, )", "need_init_github_issues_timeline_repo in need_init_github_issues_timeline_repos: op_do_init_github_issues_timeline = PythonOperator( task_id='op_do_init_github_issues_timeline_{owner}_{repo}'.format( owner=need_init_github_issues_timeline_repo[\"owner\"], repo=need_init_github_issues_timeline_repo[\"repo\"]), python_callable=do_init_github_issues_timeline,", "need_do_init_ops = [] from airflow.models import Variable need_init_github_issues_timeline_repos = Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS,", "in proxy_confs['reserved_proxies']: proxies.append(f'http://{line}') proxy_service = KuaiProxyService(proxy_confs['api_url'], proxy_confs['orderid']) proxy_manager = ProxyManager(proxies,", "scheduler_init_github_issues_timeline(ds, **kwargs): return 'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline = PythonOperator( task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline )", "opensearch_conn_info = Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True) proxy_confs = Variable.get(PROXY_CONFS, deserialize_json=True) proxies =", "def scheduler_init_github_issues_timeline(ds, **kwargs): return 'End:scheduler_init_github_issues_timeline' op_scheduler_init_github_issues_timeline = PythonOperator( task_id='op_scheduler_init_github_issues_timeline', python_callable=scheduler_init_github_issues_timeline", "params need_do_init_ops = [] from airflow.models import Variable need_init_github_issues_timeline_repos =", "airflow.operators.python import PythonOperator # v0.0.1 from oss_know.libs.base_dict.variable_key import NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, GITHUB_TOKENS,", "since = None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner, repo, proxy_accommodator, since) return params", "[] from airflow.models import Variable need_init_github_issues_timeline_repos = Variable.get(NEED_INIT_GITHUB_ISSUES_TIMELINE_REPOS, deserialize_json=True) for", "proxy_service) token_manager = TokenManager(github_tokens) proxy_accommodator = GithubTokenProxyAccommodator(token_manager, proxy_manager, shuffle=True, policy=GithubTokenProxyAccommodator.POLICY_FIXED_MAP)", "= Variable.get(OPENSEARCH_CONN_DATA, deserialize_json=True) proxy_confs = Variable.get(PROXY_CONFS, deserialize_json=True) proxies = []", "= Variable.get(PROXY_CONFS, deserialize_json=True) proxies = [] for line in proxy_confs['reserved_proxies']:", "None init_issues_timeline.init_sync_github_issues_timeline(opensearch_conn_info, owner, repo, proxy_accommodator, since) return params need_do_init_ops =", "deserialize_json=True) proxy_confs = Variable.get(PROXY_CONFS, deserialize_json=True) proxies = [] for line", "since) return params need_do_init_ops = [] from airflow.models import Variable" ]
[ "import sys from conans.client.command import main def run(): main(sys.argv[1:]) if", "import main def run(): main(sys.argv[1:]) if __name__ == '__main__': run()", "conans.client.command import main def run(): main(sys.argv[1:]) if __name__ == '__main__':", "from conans.client.command import main def run(): main(sys.argv[1:]) if __name__ ==", "<reponame>laundry-96/conan import sys from conans.client.command import main def run(): main(sys.argv[1:])", "sys from conans.client.command import main def run(): main(sys.argv[1:]) if __name__" ]
[ "in French url = page.get_absolute_url(language=\"fr\") response = self.client.get(url) self.assertContains( response,", "richie.apps.persons.models import PersonPluginModel class PersonPluginTestCase(TestCase): \"\"\" Test that PersonPlugin correctly", "present # pylint: disable=no-member self.assertContains(response, image.file.name) # Short resume should", "Test that PersonPlugin correctly displays a Person's page placeholders content", "a Person person = PersonFactory() person_page = person.extended_object # Add", "Create a page to add the plugin to page =", "url = page.get_absolute_url(language=\"fr\") response = self.client.get(url) self.assertContains( response, '<a href=\"{url}\"", "add_plugin( portrait_placeholder, PicturePlugin, \"fr\", **{\"picture\": image, \"attributes\": {\"alt\": \"description du", "richie.apps.core.helpers import create_i18n_page from richie.apps.persons.cms_plugins import PersonPlugin from richie.apps.persons.factories import", "class Meta: model = PersonPluginModel exclude = () person =", "{\"alt\": \"portrait description\"}} ) add_plugin( portrait_placeholder, PicturePlugin, \"fr\", **{\"picture\": image,", "box. \"\"\" class PersonPluginModelForm(forms.ModelForm): \"\"\"A form for testing the choices", "test_cms_plugins_person_form_page_choices(self): \"\"\" The form to create a person plugin should", "the select box\"\"\" class Meta: model = PersonPluginModel exclude =", "add_plugin( resume_placeholder, PlaintextPlugin, \"fr\", **{\"body\": \"Un résumé court\"} ) #", "from django import forms from django.conf import settings from django.test", "a page to add the plugin to page = create_i18n_page({\"en\":", "Check the page content in English url = page.get_absolute_url(language=\"en\") response", "self.assertContains( response, '<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name() ), html=True, ) # Same", "PlaintextPlugin, \"fr\", **{\"body\": \"Un résumé court\"} ) # Create a", "testing the choices in the select box\"\"\" class Meta: model", "and its model \"\"\" from django import forms from django.conf", "import PersonPlugin from richie.apps.persons.factories import PersonFactory from richie.apps.persons.models import PersonPluginModel", "from django.test import TestCase from cms.api import add_plugin, create_page from", "select box. \"\"\" class PersonPluginModelForm(forms.ModelForm): \"\"\"A form for testing the", "person.get_full_name() ), html=True, ) # Same checks in French url", "'<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name() ), html=True, ) # Same checks in", "'<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) # pylint:", "PersonPluginModel exclude = () person = PersonFactory() other_page_title = \"other", "'<div class=\"person-plugin__content__text\">A short resume</div>', html=True, ) # The person's full", "cmsplugin_plain_text.cms_plugins import PlaintextPlugin from djangocms_picture.cms_plugins import PicturePlugin from richie.apps.core.factories import", "\"portrait description\"}} ) add_plugin( portrait_placeholder, PicturePlugin, \"fr\", **{\"picture\": image, \"attributes\":", "person}) add_plugin(placeholder, PersonPlugin, \"fr\", **{\"person\": person}) page.publish(\"en\") page.publish(\"fr\") # Check", "), html=True, ) # Same checks in French url =", "portrait and its properties should be present # pylint: disable=no-member", "image = FilerImageFactory(owner=staff) # Create a Person person = PersonFactory()", "of the link self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title()", "placeholders content \"\"\" def test_cms_plugins_person_form_page_choices(self): \"\"\" The form to create", "Person's name should be present as a link to the", "pylint: disable=no-member self.assertContains(response, image.file.name) # Short resume should be present", "import PersonPluginModel class PersonPluginTestCase(TestCase): \"\"\" Test that PersonPlugin correctly displays", "create_i18n_page from richie.apps.persons.cms_plugins import PersonPlugin from richie.apps.persons.factories import PersonFactory from", "a PersonPlugin correctly renders person's page specific information \"\"\" #", "test_cms_plugins_person_render(self): \"\"\" Test that a PersonPlugin correctly renders person's page", "response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) self.assertContains(response,", "PersonPlugin correctly displays a Person's page placeholders content \"\"\" def", "# Create a Person person = PersonFactory() person_page = person.extended_object", "from richie.apps.persons.models import PersonPluginModel class PersonPluginTestCase(TestCase): \"\"\" Test that PersonPlugin", "Short resume should be present self.assertContains( response, '<div class=\"person-plugin__content__text\">A short", "to create a person plugin should only list person pages", "\"fr\", **{\"body\": \"Un résumé court\"} ) # Create a page", "to the cms page # And CMS page title should", "self.client.get(url) # Person's name should be present as a link", "from richie.apps.persons.factories import PersonFactory from richie.apps.persons.models import PersonPluginModel class PersonPluginTestCase(TestCase):", "resume\"} ) add_plugin( resume_placeholder, PlaintextPlugin, \"fr\", **{\"body\": \"Un résumé court\"}", "title attribute of the link self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format(", "django.conf import settings from django.test import TestCase from cms.api import", "import forms from django.conf import settings from django.test import TestCase", "class=\"person-plugin__content__text\">A short resume</div>', html=True, ) # The person's full name", "import PersonFactory from richie.apps.persons.models import PersonPluginModel class PersonPluginTestCase(TestCase): \"\"\" Test", "link to the cms page # And CMS page title", ") # Create a page to add the plugin to", "\"other page\" create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE) plugin_form = PersonPluginModelForm() self.assertIn(person.get_full_name(), plugin_form.as_table())", "fake image staff = UserFactory(is_staff=True, is_superuser=True) image = FilerImageFactory(owner=staff) #", "Person person = PersonFactory() person_page = person.extended_object # Add portrait", ") # pylint: disable=no-member self.assertContains(response, image.file.name) self.assertContains( response, '<div class=\"person-plugin__content__text\">Un", "djangocms_picture.cms_plugins import PicturePlugin from richie.apps.core.factories import FilerImageFactory, UserFactory from richie.apps.core.helpers", "\"fr\", **{\"person\": person}) page.publish(\"en\") page.publish(\"fr\") # Check the page content", "page placeholders content \"\"\" def test_cms_plugins_person_form_page_choices(self): \"\"\" The form to", "the page content in English url = page.get_absolute_url(language=\"en\") response =", "= \"other page\" create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE) plugin_form = PersonPluginModelForm() self.assertIn(person.get_full_name(),", "du portrait\"}} ) # A resume to related placeholder resume_placeholder", "Meta: model = PersonPluginModel exclude = () person = PersonFactory()", "title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) self.assertContains(response, person.get_full_name(), html=True) #", "response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) #", "add_plugin(placeholder, PersonPlugin, \"en\", **{\"person\": person}) add_plugin(placeholder, PersonPlugin, \"fr\", **{\"person\": person})", "= page.get_absolute_url(language=\"fr\") response = self.client.get(url) self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format(", "# Person's portrait and its properties should be present #", "a link to the cms page # And CMS page", "present as a link to the cms page # And", "), status_code=200, ) # pylint: disable=no-member self.assertContains(response, image.file.name) self.assertContains( response,", "page\"}) placeholder = page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder, PersonPlugin, \"en\", **{\"person\": person}) add_plugin(placeholder,", "response, '<div class=\"person-plugin__content__text\">A short resume</div>', html=True, ) # The person's", "href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) self.assertContains(response, person.get_full_name(), html=True)", "{\"alt\": \"description du portrait\"}} ) # A resume to related", "= UserFactory(is_staff=True, is_superuser=True) image = FilerImageFactory(owner=staff) # Create a Person", "# pylint: disable=no-member self.assertContains(response, image.file.name) self.assertContains( response, '<div class=\"person-plugin__content__text\">Un résumé", "PersonPluginModelForm(forms.ModelForm): \"\"\"A form for testing the choices in the select", "url = page.get_absolute_url(language=\"en\") response = self.client.get(url) # Person's name should", "list person pages in the select box. \"\"\" class PersonPluginModelForm(forms.ModelForm):", "to add the plugin to page = create_i18n_page({\"en\": \"A page\",", "import FilerImageFactory, UserFactory from richie.apps.core.helpers import create_i18n_page from richie.apps.persons.cms_plugins import", "portrait_placeholder, PicturePlugin, \"fr\", **{\"picture\": image, \"attributes\": {\"alt\": \"description du portrait\"}}", "settings.LANGUAGE_CODE) plugin_form = PersonPluginModelForm() self.assertIn(person.get_full_name(), plugin_form.as_table()) self.assertNotIn(other_page_title, plugin_form.as_table()) def test_cms_plugins_person_render(self):", "person plugin should only list person pages in the select", "plugin should only list person pages in the select box.", "in English url = page.get_absolute_url(language=\"en\") response = self.client.get(url) # Person's", "pylint: disable=no-member self.assertContains(response, image.file.name) self.assertContains( response, '<div class=\"person-plugin__content__text\">Un résumé court</div>',", "title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) # pylint: disable=no-member self.assertContains(response,", "CMS page title should be in title attribute of the", "page_title=person_page.get_title() ), status_code=200, ) self.assertContains(response, person.get_full_name(), html=True) # Person's portrait", "model \"\"\" from django import forms from django.conf import settings", "from djangocms_picture.cms_plugins import PicturePlugin from richie.apps.core.factories import FilerImageFactory, UserFactory from", "create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE) plugin_form = PersonPluginModelForm() self.assertIn(person.get_full_name(), plugin_form.as_table()) self.assertNotIn(other_page_title, plugin_form.as_table())", "Same checks in French url = page.get_absolute_url(language=\"fr\") response = self.client.get(url)", "title should be in title attribute of the link self.assertContains(", "be wrapped in a h2 self.assertContains( response, '<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name()", "django import forms from django.conf import settings from django.test import", "disable=no-member self.assertContains(response, image.file.name) self.assertContains( response, '<div class=\"person-plugin__content__text\">Un résumé court</div>', html=True,", "= PersonPluginModel exclude = () person = PersonFactory() other_page_title =", "html=True, ) # The person's full name should be wrapped", "portrait_placeholder = person_page.placeholders.get(slot=\"portrait\") add_plugin( portrait_placeholder, PicturePlugin, \"en\", **{\"picture\": image, \"attributes\":", "A resume to related placeholder resume_placeholder = person_page.placeholders.get(slot=\"resume\") add_plugin( resume_placeholder,", "self.assertIn(person.get_full_name(), plugin_form.as_table()) self.assertNotIn(other_page_title, plugin_form.as_table()) def test_cms_plugins_person_render(self): \"\"\" Test that a", "PicturePlugin from richie.apps.core.factories import FilerImageFactory, UserFactory from richie.apps.core.helpers import create_i18n_page", "= person_page.placeholders.get(slot=\"portrait\") add_plugin( portrait_placeholder, PicturePlugin, \"en\", **{\"picture\": image, \"attributes\": {\"alt\":", "import PicturePlugin from richie.apps.core.factories import FilerImageFactory, UserFactory from richie.apps.core.helpers import", "placeholder resume_placeholder = person_page.placeholders.get(slot=\"resume\") add_plugin( resume_placeholder, PlaintextPlugin, \"en\", **{\"body\": \"A", "should be wrapped in a h2 self.assertContains( response, '<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format(", "its model \"\"\" from django import forms from django.conf import", "PersonPluginModel class PersonPluginTestCase(TestCase): \"\"\" Test that PersonPlugin correctly displays a", "**{\"picture\": image, \"attributes\": {\"alt\": \"description du portrait\"}} ) # A", "from richie.apps.core.helpers import create_i18n_page from richie.apps.persons.cms_plugins import PersonPlugin from richie.apps.persons.factories", "import TestCase from cms.api import add_plugin, create_page from cmsplugin_plain_text.cms_plugins import", "portrait to related placeholder portrait_placeholder = person_page.placeholders.get(slot=\"portrait\") add_plugin( portrait_placeholder, PicturePlugin,", "cms page # And CMS page title should be in", "Person plugin and its model \"\"\" from django import forms", "person_page = person.extended_object # Add portrait to related placeholder portrait_placeholder", "English url = page.get_absolute_url(language=\"en\") response = self.client.get(url) # Person's name", "person = PersonFactory() person_page = person.extended_object # Add portrait to", "And CMS page title should be in title attribute of", "self.assertContains(response, person.get_full_name(), html=True) # Person's portrait and its properties should", "the choices in the select box\"\"\" class Meta: model =", "content in English url = page.get_absolute_url(language=\"en\") response = self.client.get(url) #", "page.get_absolute_url(language=\"fr\") response = self.client.get(url) self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(),", "PlaintextPlugin, \"en\", **{\"body\": \"A short resume\"} ) add_plugin( resume_placeholder, PlaintextPlugin,", "\"description du portrait\"}} ) # A resume to related placeholder", "court\"} ) # Create a page to add the plugin", "checks in French url = page.get_absolute_url(language=\"fr\") response = self.client.get(url) self.assertContains(", "person pages in the select box. \"\"\" class PersonPluginModelForm(forms.ModelForm): \"\"\"A", "UserFactory(is_staff=True, is_superuser=True) image = FilerImageFactory(owner=staff) # Create a Person person", "should be in title attribute of the link self.assertContains( response,", "\"A short resume\"} ) add_plugin( resume_placeholder, PlaintextPlugin, \"fr\", **{\"body\": \"Un", "class PersonPluginTestCase(TestCase): \"\"\" Test that PersonPlugin correctly displays a Person's", "html=True) # Person's portrait and its properties should be present", "# -*- coding: utf-8 -*- \"\"\" Unit tests for the", "richie.apps.persons.factories import PersonFactory from richie.apps.persons.models import PersonPluginModel class PersonPluginTestCase(TestCase): \"\"\"", "portrait\"}} ) # A resume to related placeholder resume_placeholder =", "class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name() ), html=True, ) # Same checks in French", "\"\"\" from django import forms from django.conf import settings from", "tests for the Person plugin and its model \"\"\" from", "from richie.apps.persons.cms_plugins import PersonPlugin from richie.apps.persons.factories import PersonFactory from richie.apps.persons.models", "other_page_title = \"other page\" create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE) plugin_form = PersonPluginModelForm()", "image.file.name) # Short resume should be present self.assertContains( response, '<div", "plugin_form.as_table()) def test_cms_plugins_person_render(self): \"\"\" Test that a PersonPlugin correctly renders", "the Person plugin and its model \"\"\" from django import", "a Person's page placeholders content \"\"\" def test_cms_plugins_person_form_page_choices(self): \"\"\" The", "\"\"\" def test_cms_plugins_person_form_page_choices(self): \"\"\" The form to create a person", "PlaintextPlugin from djangocms_picture.cms_plugins import PicturePlugin from richie.apps.core.factories import FilerImageFactory, UserFactory", "= self.client.get(url) self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ),", "# A resume to related placeholder resume_placeholder = person_page.placeholders.get(slot=\"resume\") add_plugin(", "that PersonPlugin correctly displays a Person's page placeholders content \"\"\"", "\"\"\" Unit tests for the Person plugin and its model", ") self.assertContains(response, person.get_full_name(), html=True) # Person's portrait and its properties", "# pylint: disable=no-member self.assertContains(response, image.file.name) # Short resume should be", "image, \"attributes\": {\"alt\": \"portrait description\"}} ) add_plugin( portrait_placeholder, PicturePlugin, \"fr\",", "its properties should be present # pylint: disable=no-member self.assertContains(response, image.file.name)", "h2 self.assertContains( response, '<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name() ), html=True, ) #", "Test that a PersonPlugin correctly renders person's page specific information", "response = self.client.get(url) # Person's name should be present as", "add_plugin, create_page from cmsplugin_plain_text.cms_plugins import PlaintextPlugin from djangocms_picture.cms_plugins import PicturePlugin", "# Create a filer fake image staff = UserFactory(is_staff=True, is_superuser=True)", "person_page.placeholders.get(slot=\"resume\") add_plugin( resume_placeholder, PlaintextPlugin, \"en\", **{\"body\": \"A short resume\"} )", "\"en\", **{\"body\": \"A short resume\"} ) add_plugin( resume_placeholder, PlaintextPlugin, \"fr\",", "The form to create a person plugin should only list", "be present # pylint: disable=no-member self.assertContains(response, image.file.name) # Short resume", "import add_plugin, create_page from cmsplugin_plain_text.cms_plugins import PlaintextPlugin from djangocms_picture.cms_plugins import", "# Check the page content in English url = page.get_absolute_url(language=\"en\")", "FilerImageFactory(owner=staff) # Create a Person person = PersonFactory() person_page =", "resume_placeholder, PlaintextPlugin, \"en\", **{\"body\": \"A short resume\"} ) add_plugin( resume_placeholder,", "PersonFactory() person_page = person.extended_object # Add portrait to related placeholder", "page_title=person_page.get_title() ), status_code=200, ) # pylint: disable=no-member self.assertContains(response, image.file.name) self.assertContains(", "= self.client.get(url) # Person's name should be present as a", "\"fr\", **{\"picture\": image, \"attributes\": {\"alt\": \"description du portrait\"}} ) #", "disable=no-member self.assertContains(response, image.file.name) # Short resume should be present self.assertContains(", "to page = create_i18n_page({\"en\": \"A page\", \"fr\": \"Une page\"}) placeholder", "richie.apps.persons.cms_plugins import PersonPlugin from richie.apps.persons.factories import PersonFactory from richie.apps.persons.models import", "for the Person plugin and its model \"\"\" from django", "forms from django.conf import settings from django.test import TestCase from", "a person plugin should only list person pages in the", "html=True, ) # Same checks in French url = page.get_absolute_url(language=\"fr\")", "description\"}} ) add_plugin( portrait_placeholder, PicturePlugin, \"fr\", **{\"picture\": image, \"attributes\": {\"alt\":", "from richie.apps.core.factories import FilerImageFactory, UserFactory from richie.apps.core.helpers import create_i18n_page from", "\"Un résumé court\"} ) # Create a page to add", "= () person = PersonFactory() other_page_title = \"other page\" create_page(other_page_title,", "create_page from cmsplugin_plain_text.cms_plugins import PlaintextPlugin from djangocms_picture.cms_plugins import PicturePlugin from", "= PersonFactory() person_page = person.extended_object # Add portrait to related", "resume to related placeholder resume_placeholder = person_page.placeholders.get(slot=\"resume\") add_plugin( resume_placeholder, PlaintextPlugin,", "self.assertContains(response, image.file.name) self.assertContains( response, '<div class=\"person-plugin__content__text\">Un résumé court</div>', html=True, )", "response = self.client.get(url) self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title()", "self.assertNotIn(other_page_title, plugin_form.as_table()) def test_cms_plugins_person_render(self): \"\"\" Test that a PersonPlugin correctly", "PersonFactory from richie.apps.persons.models import PersonPluginModel class PersonPluginTestCase(TestCase): \"\"\" Test that", "the cms page # And CMS page title should be", "\"fr\": \"Une page\"}) placeholder = page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder, PersonPlugin, \"en\", **{\"person\":", "full name should be wrapped in a h2 self.assertContains( response,", "\"richie/fullwidth.html\", settings.LANGUAGE_CODE) plugin_form = PersonPluginModelForm() self.assertIn(person.get_full_name(), plugin_form.as_table()) self.assertNotIn(other_page_title, plugin_form.as_table()) def", "PersonPlugin from richie.apps.persons.factories import PersonFactory from richie.apps.persons.models import PersonPluginModel class", "= person_page.placeholders.get(slot=\"resume\") add_plugin( resume_placeholder, PlaintextPlugin, \"en\", **{\"body\": \"A short resume\"}", "\"attributes\": {\"alt\": \"description du portrait\"}} ) # A resume to", "def test_cms_plugins_person_render(self): \"\"\" Test that a PersonPlugin correctly renders person's", "the link self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ),", "French url = page.get_absolute_url(language=\"fr\") response = self.client.get(url) self.assertContains( response, '<a", "form to create a person plugin should only list person", "as a link to the cms page # And CMS", "href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) # pylint: disable=no-member", "response, '<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name() ), html=True, ) # Same checks", "should be present self.assertContains( response, '<div class=\"person-plugin__content__text\">A short resume</div>', html=True,", "def test_cms_plugins_person_form_page_choices(self): \"\"\" The form to create a person plugin", "FilerImageFactory, UserFactory from richie.apps.core.helpers import create_i18n_page from richie.apps.persons.cms_plugins import PersonPlugin", "is_superuser=True) image = FilerImageFactory(owner=staff) # Create a Person person =", "the select box. \"\"\" class PersonPluginModelForm(forms.ModelForm): \"\"\"A form for testing", "# The person's full name should be wrapped in a", "= page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder, PersonPlugin, \"en\", **{\"person\": person}) add_plugin(placeholder, PersonPlugin, \"fr\",", "box\"\"\" class Meta: model = PersonPluginModel exclude = () person", ") # Same checks in French url = page.get_absolute_url(language=\"fr\") response", "wrapped in a h2 self.assertContains( response, '<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name() ),", "attribute of the link self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(),", "PersonPluginTestCase(TestCase): \"\"\" Test that PersonPlugin correctly displays a Person's page", "import settings from django.test import TestCase from cms.api import add_plugin,", "image, \"attributes\": {\"alt\": \"description du portrait\"}} ) # A resume", "should be present # pylint: disable=no-member self.assertContains(response, image.file.name) # Short", "TestCase from cms.api import add_plugin, create_page from cmsplugin_plain_text.cms_plugins import PlaintextPlugin", "PicturePlugin, \"fr\", **{\"picture\": image, \"attributes\": {\"alt\": \"description du portrait\"}} )", "pages in the select box. \"\"\" class PersonPluginModelForm(forms.ModelForm): \"\"\"A form", "\"\"\" class PersonPluginModelForm(forms.ModelForm): \"\"\"A form for testing the choices in", "self.client.get(url) self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200,", "exclude = () person = PersonFactory() other_page_title = \"other page\"", "be present self.assertContains( response, '<div class=\"person-plugin__content__text\">A short resume</div>', html=True, )", "plugin_form = PersonPluginModelForm() self.assertIn(person.get_full_name(), plugin_form.as_table()) self.assertNotIn(other_page_title, plugin_form.as_table()) def test_cms_plugins_person_render(self): \"\"\"", "page.get_absolute_url(language=\"en\") response = self.client.get(url) # Person's name should be present", "add_plugin( portrait_placeholder, PicturePlugin, \"en\", **{\"picture\": image, \"attributes\": {\"alt\": \"portrait description\"}}", "be in title attribute of the link self.assertContains( response, '<a", "be present as a link to the cms page #", "name should be wrapped in a h2 self.assertContains( response, '<h2", "correctly renders person's page specific information \"\"\" # Create a", "in a h2 self.assertContains( response, '<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name() ), html=True,", "Person's portrait and its properties should be present # pylint:", "\"\"\" Test that a PersonPlugin correctly renders person's page specific", "\"\"\" # Create a filer fake image staff = UserFactory(is_staff=True,", "page\" create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE) plugin_form = PersonPluginModelForm() self.assertIn(person.get_full_name(), plugin_form.as_table()) self.assertNotIn(other_page_title,", "related placeholder resume_placeholder = person_page.placeholders.get(slot=\"resume\") add_plugin( resume_placeholder, PlaintextPlugin, \"en\", **{\"body\":", "page content in English url = page.get_absolute_url(language=\"en\") response = self.client.get(url)", "The person's full name should be wrapped in a h2", "from cmsplugin_plain_text.cms_plugins import PlaintextPlugin from djangocms_picture.cms_plugins import PicturePlugin from richie.apps.core.factories", "should only list person pages in the select box. \"\"\"", "related placeholder portrait_placeholder = person_page.placeholders.get(slot=\"portrait\") add_plugin( portrait_placeholder, PicturePlugin, \"en\", **{\"picture\":", "\"en\", **{\"person\": person}) add_plugin(placeholder, PersonPlugin, \"fr\", **{\"person\": person}) page.publish(\"en\") page.publish(\"fr\")", "**{\"person\": person}) page.publish(\"en\") page.publish(\"fr\") # Check the page content in", "renders person's page specific information \"\"\" # Create a filer", "properties should be present # pylint: disable=no-member self.assertContains(response, image.file.name) #", "Create a filer fake image staff = UserFactory(is_staff=True, is_superuser=True) image", "resume_placeholder = person_page.placeholders.get(slot=\"resume\") add_plugin( resume_placeholder, PlaintextPlugin, \"en\", **{\"body\": \"A short", "# Person's name should be present as a link to", "Person's page placeholders content \"\"\" def test_cms_plugins_person_form_page_choices(self): \"\"\" The form", "page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder, PersonPlugin, \"en\", **{\"person\": person}) add_plugin(placeholder, PersonPlugin, \"fr\", **{\"person\":", "= FilerImageFactory(owner=staff) # Create a Person person = PersonFactory() person_page", "the plugin to page = create_i18n_page({\"en\": \"A page\", \"fr\": \"Une", "= page.get_absolute_url(language=\"en\") response = self.client.get(url) # Person's name should be", ") add_plugin( portrait_placeholder, PicturePlugin, \"fr\", **{\"picture\": image, \"attributes\": {\"alt\": \"description", "Create a Person person = PersonFactory() person_page = person.extended_object #", "self.assertContains(response, image.file.name) # Short resume should be present self.assertContains( response,", "status_code=200, ) # pylint: disable=no-member self.assertContains(response, image.file.name) self.assertContains( response, '<div", "plugin_form.as_table()) self.assertNotIn(other_page_title, plugin_form.as_table()) def test_cms_plugins_person_render(self): \"\"\" Test that a PersonPlugin", "), status_code=200, ) self.assertContains(response, person.get_full_name(), html=True) # Person's portrait and", "richie.apps.core.factories import FilerImageFactory, UserFactory from richie.apps.core.helpers import create_i18n_page from richie.apps.persons.cms_plugins", "import create_i18n_page from richie.apps.persons.cms_plugins import PersonPlugin from richie.apps.persons.factories import PersonFactory", "person = PersonFactory() other_page_title = \"other page\" create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE)", "content \"\"\" def test_cms_plugins_person_form_page_choices(self): \"\"\" The form to create a", "filer fake image staff = UserFactory(is_staff=True, is_superuser=True) image = FilerImageFactory(owner=staff)", "portrait_placeholder, PicturePlugin, \"en\", **{\"picture\": image, \"attributes\": {\"alt\": \"portrait description\"}} )", "displays a Person's page placeholders content \"\"\" def test_cms_plugins_person_form_page_choices(self): \"\"\"", "\"Une page\"}) placeholder = page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder, PersonPlugin, \"en\", **{\"person\": person})", "that a PersonPlugin correctly renders person's page specific information \"\"\"", "link self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200,", "short resume\"} ) add_plugin( resume_placeholder, PlaintextPlugin, \"fr\", **{\"body\": \"Un résumé", "coding: utf-8 -*- \"\"\" Unit tests for the Person plugin", "**{\"body\": \"Un résumé court\"} ) # Create a page to", "to related placeholder resume_placeholder = person_page.placeholders.get(slot=\"resume\") add_plugin( resume_placeholder, PlaintextPlugin, \"en\",", "page specific information \"\"\" # Create a filer fake image", "résumé court\"} ) # Create a page to add the", "= create_i18n_page({\"en\": \"A page\", \"fr\": \"Une page\"}) placeholder = page.placeholders.get(slot=\"maincontent\")", "PersonPluginModelForm() self.assertIn(person.get_full_name(), plugin_form.as_table()) self.assertNotIn(other_page_title, plugin_form.as_table()) def test_cms_plugins_person_render(self): \"\"\" Test that", "page to add the plugin to page = create_i18n_page({\"en\": \"A", ") # The person's full name should be wrapped in", "\"attributes\": {\"alt\": \"portrait description\"}} ) add_plugin( portrait_placeholder, PicturePlugin, \"fr\", **{\"picture\":", "page.publish(\"fr\") # Check the page content in English url =", "page # And CMS page title should be in title", "url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) self.assertContains(response, person.get_full_name(), html=True) # Person's", "self.assertContains( response, '<div class=\"person-plugin__content__text\">A short resume</div>', html=True, ) # The", "\"\"\" Test that PersonPlugin correctly displays a Person's page placeholders", "from cms.api import add_plugin, create_page from cmsplugin_plain_text.cms_plugins import PlaintextPlugin from", "add the plugin to page = create_i18n_page({\"en\": \"A page\", \"fr\":", "() person = PersonFactory() other_page_title = \"other page\" create_page(other_page_title, \"richie/fullwidth.html\",", "create_i18n_page({\"en\": \"A page\", \"fr\": \"Une page\"}) placeholder = page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder,", "information \"\"\" # Create a filer fake image staff =", "and its properties should be present # pylint: disable=no-member self.assertContains(response,", "page\", \"fr\": \"Une page\"}) placeholder = page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder, PersonPlugin, \"en\",", "-*- \"\"\" Unit tests for the Person plugin and its", "plugin to page = create_i18n_page({\"en\": \"A page\", \"fr\": \"Une page\"})", "page = create_i18n_page({\"en\": \"A page\", \"fr\": \"Une page\"}) placeholder =", "to related placeholder portrait_placeholder = person_page.placeholders.get(slot=\"portrait\") add_plugin( portrait_placeholder, PicturePlugin, \"en\",", "in the select box. \"\"\" class PersonPluginModelForm(forms.ModelForm): \"\"\"A form for", "Unit tests for the Person plugin and its model \"\"\"", "select box\"\"\" class Meta: model = PersonPluginModel exclude = ()", "resume_placeholder, PlaintextPlugin, \"fr\", **{\"body\": \"Un résumé court\"} ) # Create", "should be present as a link to the cms page", "person}) page.publish(\"en\") page.publish(\"fr\") # Check the page content in English", ") # A resume to related placeholder resume_placeholder = person_page.placeholders.get(slot=\"resume\")", "person's page specific information \"\"\" # Create a filer fake", "image staff = UserFactory(is_staff=True, is_superuser=True) image = FilerImageFactory(owner=staff) # Create", "PersonPlugin, \"fr\", **{\"person\": person}) page.publish(\"en\") page.publish(\"fr\") # Check the page", "page title should be in title attribute of the link", "self.assertContains( response, '<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, )", "UserFactory from richie.apps.core.helpers import create_i18n_page from richie.apps.persons.cms_plugins import PersonPlugin from", "PersonPlugin correctly renders person's page specific information \"\"\" # Create", "# Same checks in French url = page.get_absolute_url(language=\"fr\") response =", "choices in the select box\"\"\" class Meta: model = PersonPluginModel", "url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) # pylint: disable=no-member self.assertContains(response, image.file.name)", "= person.extended_object # Add portrait to related placeholder portrait_placeholder =", "\"A page\", \"fr\": \"Une page\"}) placeholder = page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder, PersonPlugin,", "\"en\", **{\"picture\": image, \"attributes\": {\"alt\": \"portrait description\"}} ) add_plugin( portrait_placeholder,", "# Create a page to add the plugin to page", "present self.assertContains( response, '<div class=\"person-plugin__content__text\">A short resume</div>', html=True, ) #", "Add portrait to related placeholder portrait_placeholder = person_page.placeholders.get(slot=\"portrait\") add_plugin( portrait_placeholder,", "utf-8 -*- \"\"\" Unit tests for the Person plugin and", "cms.api import add_plugin, create_page from cmsplugin_plain_text.cms_plugins import PlaintextPlugin from djangocms_picture.cms_plugins", "**{\"body\": \"A short resume\"} ) add_plugin( resume_placeholder, PlaintextPlugin, \"fr\", **{\"body\":", "plugin and its model \"\"\" from django import forms from", "PersonPlugin, \"en\", **{\"person\": person}) add_plugin(placeholder, PersonPlugin, \"fr\", **{\"person\": person}) page.publish(\"en\")", "in the select box\"\"\" class Meta: model = PersonPluginModel exclude", "settings from django.test import TestCase from cms.api import add_plugin, create_page", "placeholder = page.placeholders.get(slot=\"maincontent\") add_plugin(placeholder, PersonPlugin, \"en\", **{\"person\": person}) add_plugin(placeholder, PersonPlugin,", "add_plugin(placeholder, PersonPlugin, \"fr\", **{\"person\": person}) page.publish(\"en\") page.publish(\"fr\") # Check the", "only list person pages in the select box. \"\"\" class", ") add_plugin( resume_placeholder, PlaintextPlugin, \"fr\", **{\"body\": \"Un résumé court\"} )", "PicturePlugin, \"en\", **{\"picture\": image, \"attributes\": {\"alt\": \"portrait description\"}} ) add_plugin(", "correctly displays a Person's page placeholders content \"\"\" def test_cms_plugins_person_form_page_choices(self):", "person.get_full_name(), html=True) # Person's portrait and its properties should be", "short resume</div>', html=True, ) # The person's full name should", "# Short resume should be present self.assertContains( response, '<div class=\"person-plugin__content__text\">A", "PersonFactory() other_page_title = \"other page\" create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE) plugin_form =", "in title attribute of the link self.assertContains( response, '<a href=\"{url}\"", "'<a href=\"{url}\" title=\"{page_title}\">'.format( url=person_page.get_absolute_url(), page_title=person_page.get_title() ), status_code=200, ) self.assertContains(response, person.get_full_name(),", "person_page.placeholders.get(slot=\"portrait\") add_plugin( portrait_placeholder, PicturePlugin, \"en\", **{\"picture\": image, \"attributes\": {\"alt\": \"portrait", "**{\"person\": person}) add_plugin(placeholder, PersonPlugin, \"fr\", **{\"person\": person}) page.publish(\"en\") page.publish(\"fr\") #", "= PersonPluginModelForm() self.assertIn(person.get_full_name(), plugin_form.as_table()) self.assertNotIn(other_page_title, plugin_form.as_table()) def test_cms_plugins_person_render(self): \"\"\" Test", "create a person plugin should only list person pages in", "a filer fake image staff = UserFactory(is_staff=True, is_superuser=True) image =", "person.extended_object # Add portrait to related placeholder portrait_placeholder = person_page.placeholders.get(slot=\"portrait\")", "a h2 self.assertContains( response, '<h2 class=\"person-plugin__content__title\">{:s}</h2>'.format( person.get_full_name() ), html=True, )", "# Add portrait to related placeholder portrait_placeholder = person_page.placeholders.get(slot=\"portrait\") add_plugin(", "**{\"picture\": image, \"attributes\": {\"alt\": \"portrait description\"}} ) add_plugin( portrait_placeholder, PicturePlugin,", "resume should be present self.assertContains( response, '<div class=\"person-plugin__content__text\">A short resume</div>',", "status_code=200, ) self.assertContains(response, person.get_full_name(), html=True) # Person's portrait and its", "add_plugin( resume_placeholder, PlaintextPlugin, \"en\", **{\"body\": \"A short resume\"} ) add_plugin(", "django.test import TestCase from cms.api import add_plugin, create_page from cmsplugin_plain_text.cms_plugins", "page.publish(\"en\") page.publish(\"fr\") # Check the page content in English url", "for testing the choices in the select box\"\"\" class Meta:", "= PersonFactory() other_page_title = \"other page\" create_page(other_page_title, \"richie/fullwidth.html\", settings.LANGUAGE_CODE) plugin_form", "placeholder portrait_placeholder = person_page.placeholders.get(slot=\"portrait\") add_plugin( portrait_placeholder, PicturePlugin, \"en\", **{\"picture\": image,", "person's full name should be wrapped in a h2 self.assertContains(", "import PlaintextPlugin from djangocms_picture.cms_plugins import PicturePlugin from richie.apps.core.factories import FilerImageFactory,", "-*- coding: utf-8 -*- \"\"\" Unit tests for the Person", "model = PersonPluginModel exclude = () person = PersonFactory() other_page_title", "staff = UserFactory(is_staff=True, is_superuser=True) image = FilerImageFactory(owner=staff) # Create a", "class PersonPluginModelForm(forms.ModelForm): \"\"\"A form for testing the choices in the", "name should be present as a link to the cms", "resume</div>', html=True, ) # The person's full name should be", "\"\"\" The form to create a person plugin should only", "\"\"\"A form for testing the choices in the select box\"\"\"", "form for testing the choices in the select box\"\"\" class", "specific information \"\"\" # Create a filer fake image staff", "from django.conf import settings from django.test import TestCase from cms.api", "# And CMS page title should be in title attribute" ]
[ "in an expression. Supports a minimal part of the basic", "self.position if pos is None: return self.parent.is_atom() elif pos ==", "position is None: parent = parent.parent continue pos.append(parent.position) parent =", "cls).__new__(cls) self._headp = ExpressionPointer(expr.head, 0) self._elementsp = [ SubExpression(ExpressionPointer(expr, k", "be an Expression, a Symbol, or another ExpressionPointer pos: int", "from mathics.core.symbols import Atom, Symbol from mathics.core.atoms import Integer from", "leaves = pspec.leaves if len(leaves) > 3: raise MessageException(\"Part\", \"span\",", "`Expression`, a `ExpressionPointer` or another `SubExpression` `pos` can be `None`,", "-*- from mathics.core.expression import Expression from mathics.core.symbols import Atom, Symbol", "it points out the whole expression. \"\"\" if pos is", "in (tuple, list): pos, rem_pos = pos[0], pos[1:] if len(rem_pos)", "head(self, value): raise ValueError(\"SubExpression.head is write protected.\") def get_head_name(self): return", "index 0 is undefined raise MessageException(\"Part\", \"span\", Integer(0)) if start", "is Integer: pos = pos.get_int_value() # pos == `System`All` elif", "= None else: rem_pos = None # Trivial conversion: if", "new): \"\"\" This method replaces the value pointed out by", "`Span` Expression and returns a tuple with the positions of", "then the pointer points to the `head` of the expression.", "elif pos == 0: self.parent.head.leaves return self.parent.leaves[pos - 1].leaves @leaves.setter", "leaves. \"\"\" start = 1 stop = None step =", "sub_new in zip(self._elementsp, new.leaves): leaf.replace(sub_new) else: for leaf in self._elementsp:", "stop = None step = 1 leaves = pspec.leaves if", "expression. \"\"\" if pos is None: if type(expr) is ExpressionPointer:", "\"span\", pspec) else: stop = stop - 1 if stop", "[self.position] while type(parent) is ExpressionPointer: position = parent.position if position", "stop - 1 if stop > 0 else len(expr.leaves) +", "__repr__(self): return self.__str__() @property def head(self): return self._headp @head.setter def", "\",\\n\".join([\"\\t \" + leaf.__str__() for leaf in self.leaves]) + \"\\n\\t]\"", "is_atom(self): return False def __str__(self): return ( self.head.__str__() + \"[\\n\"", "stop == 0: # index 0 is undefined raise MessageException(\"Part\",", "-> str: return \"%s[[%s]]\" % (self.parent, self.position) def __repr__(self) ->", "method replaces the value pointed out by a `new` value.", "point, we hit the expression, and we have # the", "interface of `mathics.core.symbols.BaseElement`. \"\"\" def __init__(self, expr, pos=None): \"\"\" Initializes", "0 or stop == 0: # index 0 is undefined", "is None: parent = parent.parent continue pos.append(parent.position) parent = parent.parent", "== \"System`All\": pos = None elif type(pos) is Expression: if", "== len(self._elementsp): for leaf, sub_new in zip(self._elementsp, new.leaves): leaf.replace(sub_new) else:", "\"\"\" def __init__(self, expr, pos=None): \"\"\" Initializes a ExpressionPointer pointing", "1 stop = None step = 1 leaves = pspec.leaves", "else: raise MessageException(\"Part\", \"pspec\", pos) if pos is None or", "new) class SubExpression(object): \"\"\" This class represents a Subexpression of", "of `expr`, then returns an `ExpressionPointer`. \"\"\" # If pos", "0: start = leaves[0].get_int_value() if len(leaves) > 1: stop =", "replace(self, new): \"\"\" This method replaces the value pointed out", "= pos.pop() except Exception: raise MessageException(\"Part\", \"span\", pos) # Now,", "step)) class ExpressionPointer(object): \"\"\" This class represents a reference to", "@property def head(self): return self._headp @head.setter def head(self, value): raise", "@property def leaves(self): return self._elementsp @leaves.setter def leaves(self, value): raise", "start else: start = start - 1 if stop is", "of the basic interface of `mathics.core.symbols.BaseElement`. \"\"\" def __init__(self, expr,", "to a single whole leaf of `expr`, then returns an", "MessageException(\"Part\", \"pspec\", pos) pos = tuple_pos elif pos.has_form(\"System`Span\", None): pos", "def leaves(self): return self._elementsp @leaves.setter def leaves(self, value): raise ValueError(\"SubExpression.leaves", "Supports a minimal part of the basic interface of `mathics.core.symbols.BaseElement`.", "for leaf in self.leaves]) + \"\\n\\t]\" ) def __repr__(self): return", "stop is None: stop = 0 if step < 0", "is an `Integer`, convert # to a Python native int", "parent.head.copy() else: leaf = self.parent.leaves[p - 1] if isinstance(leaf, Atom):", "for i in tuple_pos]): raise MessageException(\"Part\", \"pspec\", pos) pos =", "elif pos.has_form(\"System`Span\", None): pos = _pspec_span_to_tuple(pos, expr) else: raise MessageException(\"Part\",", "def head(self, value): raise ValueError(\"SubExpression.head is write protected.\") def get_head_name(self):", "`pos` points out to a single whole leaf of `expr`,", "expr.position else: self.parent = expr self.position = None else: self.parent", "None else: self.parent = expr self.position = pos def __str__(self)", "Python native int if type(pos) is Integer: pos = pos.get_int_value()", "= len(expr.leaves) - start else: start = start - 1", "that indicates a subset of leaves in the original `Expression`.", "self._elementsp) ) def replace(self, new): \"\"\" Asigns `new` to the", "if leaves[1].get_name() == \"System`All\": stop = None else: raise MessageException(\"Part\",", "range(start, stop, step)) class ExpressionPointer(object): \"\"\" This class represents a", "i = pos.pop() try: while pos: if i == 0:", "0: # index 0 is undefined raise MessageException(\"Part\", \"span\", Integer(0))", "if rem_pos is None: return ExpressionPointer(expr, pos) else: return SubExpression(ExpressionPointer(expr,", "of the original Expression. \"\"\" def __new__(cls, expr, pos=None): \"\"\"", "def replace(self, new): \"\"\" Asigns `new` to the subexpression, according", "true `Expression`. # Now, set it to the new value.", "an `Expression`, a `ExpressionPointer` or another `SubExpression` `pos` can be", "return \"%s[[%s]]\" % (self.parent, self.position) def __repr__(self) -> str: return", "= super(SubExpression, cls).__new__(cls) self._headp = ExpressionPointer(expr.head, 0) self._elementsp = [", "Expression( self._headp.to_expression(), *(leaf.to_expression() for leaf in self._elementsp) ) def replace(self,", "# At this point, we hit the expression, and we", "ExpressionPointer: self.parent = expr.parent self.position = expr.position else: self.parent =", "for i in pos.leaves] if any([i is None for i", "MessageException(\"Part\", \"span\", Integer(0)) if start < 0: start = len(expr.leaves)", "0: parent = parent._head else: parent = parent.elements[i - 1]", "Expression: if pos.has_form(\"System`List\", None): tuple_pos = [i.get_int_value() for i in", "pos.get_int_value() # pos == `System`All` elif isinstance(pos, Symbol) and pos.get_name()", "expression. Supports a minimal part of the basic interface of", "pos == 0: return self.parent.head.is_atom() return self.parent.leaves[pos - 1].is_atom() def", "@head.setter def head(self, value): raise ValueError(\"SubExpression.head is write protected.\") def", "of `expr`. expr: can be an Expression, a Symbol, or", "the value pointed out by a `new` value. \"\"\" #", "def __repr__(self) -> str: return self.__str__() @property def original(self): return", "len(rem_pos) == 0: rem_pos = None else: rem_pos = None", "elif type(pos) is tuple: self = super(SubExpression, cls).__new__(cls) self._headp =", "can be `None`, an integer value or an `Expression` that", "pos.get_name() == \"System`All\": pos = None elif type(pos) is Expression:", "from mathics.builtin.base import MessageException \"\"\" This module provides some infrastructure", "head(self): return self._headp @head.setter def head(self, value): raise ValueError(\"SubExpression.head is", "- 1 stop = stop + 1 if step >", "ValueError(\"ExpressionPointer.head is write protected.\") @property def leaves(self): pos = self.position", "def original(self, value): raise ValueError(\"Expression.original is write protected.\") @property def", "return self.parent.leaves elif pos == 0: self.parent.head.leaves return self.parent.leaves[pos -", "leaves(self): return self._elementsp @leaves.setter def leaves(self, value): raise ValueError(\"SubExpression.leaves is", "Subexpression of an existing Expression. Assignment to a subexpression results", "= _pspec_span_to_tuple(pos, expr) else: raise MessageException(\"Part\", \"pspec\", pos) if pos", "in pos.leaves] if any([i is None for i in tuple_pos]):", "start is None or step is None: raise MessageException(\"Part\", \"span\",", "str: return \"%s[[%s]]\" % (self.parent, self.position) def __repr__(self) -> str:", "\"\"\" This method replaces the value pointed out by a", "to a Python native int if type(pos) is Integer: pos", "self._elementsp @elements.setter def elements(self, value): raise ValueError(\"SubExpression.leaves is write protected.\")", "protected.\") @property def head(self): pos = self.position if pos is", "1 if step > 0 else stop - 1 return", "ExpressionPointer(object): \"\"\" This class represents a reference to a leaf", "the new value. if i == 0: parent.set_head(new) else: parent.set_element(i", "value pointed out by a `new` value. \"\"\" # First,", "\"\"\" if (new.has_form(\"List\", None) or new.get_head_name() == \"System`List\") and len(", "stop = None else: raise MessageException(\"Part\", \"span\", pspec) else: stop", "is None: if type(expr) is ExpressionPointer: self.parent = expr.parent self.position", "int or None If `pos==0`, then the pointer points to", "is None: return self.parent.head elif pos == 0: return self.parent.head.head", "to_expression(self): parent = self.parent p = self.position if p ==", "pos == `System`All` elif isinstance(pos, Symbol) and pos.get_name() == \"System`All\":", "the basic interface of `mathics.core.symbols.BaseElement`. \"\"\" def __init__(self, expr, pos=None):", "class SubExpression(object): \"\"\" This class represents a Subexpression of an", "raise MessageException(\"Part\", \"span\", pos) # Now, we have a pointer", "== 0: parent.set_head(new) else: parent.set_element(i - 1, new) class SubExpression(object):", "len(leaves) > 1: stop = leaves[1].get_int_value() if stop is None:", "Asigns `new` to the subexpression, according to the logic of", "hit the expression, and we have # the path to", "None: return self.parent.is_atom() elif pos == 0: return self.parent.head.is_atom() return", "protected.\") def get_head_name(self): return self.head.get_name() def is_atom(self): pos = self.position", "mathics.builtin.base import MessageException \"\"\" This module provides some infrastructure to", "return SubExpression(ExpressionPointer(expr, pos), rem_pos) elif type(pos) is tuple: self =", "self.parent = expr self.position = pos def __str__(self) -> str:", "protected.\") @property def leaves(self): pos = self.position if pos is", "tuple_pos elif pos.has_form(\"System`Span\", None): pos = _pspec_span_to_tuple(pos, expr) else: raise", "in range(start, stop, step)) class ExpressionPointer(object): \"\"\" This class represents", "return self.__str__() @property def head(self): return self._headp @head.setter def head(self,", "to the subexpression, according to the logic of `mathics.core.walk_parts` \"\"\"", "> 3: raise MessageException(\"Part\", \"span\", leaves) if len(leaves) > 0:", "- 1].leaves @leaves.setter def leaves(self, value): raise ValueError(\"ExpressionPointer.leaves is write", "the subexpression, according to the logic of `mathics.core.walk_parts` \"\"\" if", "( self.head.__str__() + \"[\\n\" + \",\\n\".join([\"\\t \" + leaf.__str__() for", "be an `Expression`, a `ExpressionPointer` or another `SubExpression` `pos` can", "step: parent = self.parent pos = [self.position] while type(parent) is", "if step < 0 else len(expr.leaves) - 1 stop =", "is write protected.\") @property def leaves(self): return self._elementsp @leaves.setter def", "parent = self.parent pos = [self.position] while type(parent) is ExpressionPointer:", "def leaves(self, value): raise ValueError(\"SubExpression.leaves is write protected.\") def to_expression(self):", "start = start - 1 if stop is None: stop", "pos def __str__(self) -> str: return \"%s[[%s]]\" % (self.parent, self.position)", "0) self._elementsp = [ SubExpression(ExpressionPointer(expr, k + 1), rem_pos) for", "len(expr.leaves) - 1 stop = stop + 1 if step", "expression and a Mathics `Span` Expression and returns a tuple", "represents a reference to a leaf in an expression. Supports", "try: while pos: if i == 0: parent = parent._head", "the logic of `mathics.core.walk_parts` \"\"\" if (new.has_form(\"List\", None) or new.get_head_name()", "== 0: parent = parent._head else: parent = parent.elements[i -", "i == 0: parent.set_head(new) else: parent.set_element(i - 1, new) class", "self.position if p == 0: if isinstance(parent, Symbol): return parent", "out by a `new` value. \"\"\" # First, look for", "tuple_pos]): raise MessageException(\"Part\", \"pspec\", pos) pos = tuple_pos elif pos.has_form(\"System`Span\",", "raise ValueError(\"SubExpression.leaves is write protected.\") def to_expression(self): return Expression( self._headp.to_expression(),", "original `Expression`. If `pos` points out to a single whole", "= pos def __str__(self) -> str: return \"%s[[%s]]\" % (self.parent,", "if pos is None or type(pos) is int: if rem_pos", "a subset of leaves in the original `Expression`. If `pos`", "parent._head else: parent = parent.elements[i - 1] i = pos.pop()", "ExpressionPointer(expr, pos) else: return SubExpression(ExpressionPointer(expr, pos), rem_pos) elif type(pos) is", "else: self.parent = expr self.position = pos def __str__(self) ->", "self.parent.leaves[pos - 1].is_atom() def to_expression(self): parent = self.parent p =", "self.position if pos is None: return self.parent.leaves elif pos ==", "new.leaves ) == len(self._elementsp): for leaf, sub_new in zip(self._elementsp, new.leaves):", "list): pos, rem_pos = pos[0], pos[1:] if len(rem_pos) == 0:", "new.get_head_name() == \"System`List\") and len( new.leaves ) == len(self._elementsp): for", "pos is an `Integer`, convert # to a Python native", "is int: if rem_pos is None: return ExpressionPointer(expr, pos) else:", "the expression. If `pos` is `None`, it points out the", "return None @original.setter def original(self, value): raise ValueError(\"Expression.original is write", "self.parent.leaves[p - 1] if isinstance(leaf, Atom): return leaf else: return", "= parent._head else: parent = parent.elements[i - 1] i =", "def __init__(self, expr, pos=None): \"\"\" Initializes a ExpressionPointer pointing to", "# keeping the positions of each step: parent = self.parent", "the leaves. \"\"\" start = 1 stop = None step", "return tuple(k for k in range(start, stop, step)) class ExpressionPointer(object):", "Symbol) and pos.get_name() == \"System`All\": pos = None elif type(pos)", "raise MessageException(\"Part\", \"pspec\", pos) if pos is None or type(pos)", "__str__(self): return ( self.head.__str__() + \"[\\n\" + \",\\n\".join([\"\\t \" +", "1].leaves @leaves.setter def leaves(self, value): raise ValueError(\"ExpressionPointer.leaves is write protected.\")", "the pointer points to the `head` of the expression. If", "value): raise ValueError(\"ExpressionPointer.leaves is write protected.\") def get_head_name(self): return self.head.get_name()", "@property def head(self): pos = self.position if pos is None:", "is undefined raise MessageException(\"Part\", \"span\", Integer(0)) if start < 0:", "Integer: pos = pos.get_int_value() # pos == `System`All` elif isinstance(pos,", "leaf in self.leaves]) + \"\\n\\t]\" ) def __repr__(self): return self.__str__()", "provides some infrastructure to deal with SubExpressions. \"\"\" def _pspec_span_to_tuple(pspec,", "raise ValueError(\"SubExpression.head is write protected.\") def get_head_name(self): return self._headp.parent.get_head_name() @property", "or new.get_head_name() == \"System`List\") and len( new.leaves ) == len(self._elementsp):", "parent.set_head(new) else: parent.set_element(i - 1, new) class SubExpression(object): \"\"\" This", "else: return leaf.copy() def replace(self, new): \"\"\" This method replaces", "def get_head_name(self): return self.head.get_name() def is_atom(self): pos = self.position if", "while pos: if i == 0: parent = parent._head else:", "tuple with the positions of the leaves. \"\"\" start =", "pos.leaves] if any([i is None for i in tuple_pos]): raise", "= 1 stop = None step = 1 leaves =", "== 0: self.parent.head.leaves return self.parent.leaves[pos - 1].leaves @leaves.setter def leaves(self,", "look for the ancestor that is not an ExpressionPointer, #", "rem_pos = None else: rem_pos = None # Trivial conversion:", "pos = tuple_pos elif pos.has_form(\"System`Span\", None): pos = _pspec_span_to_tuple(pos, expr)", "if len(pspec.leaves) > 2: step = leaves[2].get_int_value() if start is", "self.__str__() @property def head(self): return self._headp @head.setter def head(self, value):", "self.parent.leaves[pos - 1].leaves @leaves.setter def leaves(self, value): raise ValueError(\"ExpressionPointer.leaves is", "pos.has_form(\"System`Span\", None): pos = _pspec_span_to_tuple(pos, expr) else: raise MessageException(\"Part\", \"pspec\",", "(new.has_form(\"List\", None) or new.get_head_name() == \"System`List\") and len( new.leaves )", "# -*- coding: utf-8 -*- from mathics.core.expression import Expression from", "mathics.core.expression import Expression from mathics.core.symbols import Atom, Symbol from mathics.core.atoms", "`ExpressionPointer` or another `SubExpression` `pos` can be `None`, an integer", "return ExpressionPointer(expr, pos) else: return SubExpression(ExpressionPointer(expr, pos), rem_pos) elif type(pos)", "return self._elementsp @elements.setter def elements(self, value): raise ValueError(\"SubExpression.leaves is write", "pos is None: if type(expr) is ExpressionPointer: self.parent = expr.parent", "1 stop = stop + 1 if step > 0", "stop if len(pspec.leaves) > 2: step = leaves[2].get_int_value() if start", "= self.position if pos is None: return self.parent.is_atom() elif pos", "leaves[0].get_int_value() if len(leaves) > 1: stop = leaves[1].get_int_value() if stop", "< 0: start = len(expr.leaves) - start else: start =", "each step: parent = self.parent pos = [self.position] while type(parent)", "an integer value or an `Expression` that indicates a subset", "else: return SubExpression(ExpressionPointer(expr, pos), rem_pos) elif type(pos) is tuple: self", "the leaf in position `pos` of `expr`. expr: can be", "have a pointer to an element in a true `Expression`.", "elif pos == 0: return self.parent.head.head return self.parent.leaves[pos - 1].head", "leaves[1].get_name() == \"System`All\": stop = None else: raise MessageException(\"Part\", \"span\",", "replaces the value pointed out by a `new` value. \"\"\"", "write protected.\") @property def leaves(self): pos = self.position if pos", "self.parent.leaves[pos - 1].head @head.setter def head(self, value): raise ValueError(\"ExpressionPointer.head is", "len( new.leaves ) == len(self._elementsp): for leaf, sub_new in zip(self._elementsp,", "if pos is None: return self.parent.head elif pos == 0:", "a leaf in an expression. Supports a minimal part of", "= expr self.position = pos def __str__(self) -> str: return", "element in a true `Expression`. # Now, set it to", "or stop == 0: # index 0 is undefined raise", "and we have # the path to reach the position", "return self._headp @head.setter def head(self, value): raise ValueError(\"SubExpression.head is write", "type(pos) is Integer: pos = pos.get_int_value() # pos == `System`All`", "or another ExpressionPointer pos: int or None If `pos==0`, then", "Assignment to a subexpression results in the change of the", "step is None: raise MessageException(\"Part\", \"span\", pspec) if start ==", "self.head.get_name() def is_atom(self): pos = self.position if pos is None:", "`new` to the subexpression, according to the logic of `mathics.core.walk_parts`", "function takes an expression and a Mathics `Span` Expression and", "\"span\", pspec) if start == 0 or stop == 0:", "raise MessageException(\"Part\", \"span\", Integer(0)) if start < 0: start =", "original(self, value): raise ValueError(\"Expression.original is write protected.\") @property def head(self):", "= parent.parent continue pos.append(parent.position) parent = parent.parent # At this", "to the logic of `mathics.core.walk_parts` \"\"\" if (new.has_form(\"List\", None) or", "return self.parent.leaves[pos - 1].leaves @leaves.setter def leaves(self, value): raise ValueError(\"ExpressionPointer.leaves", "for k in pos ] return self def is_atom(self): return", "undefined raise MessageException(\"Part\", \"span\", Integer(0)) if start < 0: start", "ExpressionPointer, # keeping the positions of each step: parent =", "write protected.\") @property def leaves(self): return self._elementsp @leaves.setter def leaves(self,", "while type(parent) is ExpressionPointer: position = parent.position if position is", "mathics.core.atoms import Integer from mathics.builtin.base import MessageException \"\"\" This module", "raise MessageException(\"Part\", \"span\", leaves) if len(leaves) > 0: start =", "parent.position if position is None: parent = parent.parent continue pos.append(parent.position)", "write protected.\") def get_head_name(self): return self._headp.parent.get_head_name() @property def elements(self): return", "+ \",\\n\".join([\"\\t \" + leaf.__str__() for leaf in self.leaves]) +", "if position is None: parent = parent.parent continue pos.append(parent.position) parent", "except Exception: raise MessageException(\"Part\", \"span\", pos) # Now, we have", "if pos is None: if type(expr) is ExpressionPointer: self.parent =", "SubExpression(ExpressionPointer(expr, pos), rem_pos) elif type(pos) is tuple: self = super(SubExpression,", "and # store the remainder. if type(pos) in (tuple, list):", "pos.has_form(\"System`List\", None): tuple_pos = [i.get_int_value() for i in pos.leaves] if", "0: rem_pos = None else: rem_pos = None # Trivial", "0: return self.parent.head.is_atom() return self.parent.leaves[pos - 1].is_atom() def to_expression(self): parent", "1] if isinstance(leaf, Atom): return leaf else: return leaf.copy() def", "self def is_atom(self): return False def __str__(self): return ( self.head.__str__()", "of `mathics.core.walk_parts` \"\"\" if (new.has_form(\"List\", None) or new.get_head_name() == \"System`List\")", "`pos` of `expr`. expr: can be an Expression, a Symbol,", "def is_atom(self): return False def __str__(self): return ( self.head.__str__() +", "= 1 leaves = pspec.leaves if len(leaves) > 3: raise", "a pointer to an element in a true `Expression`. #", "language_level=3 # -*- coding: utf-8 -*- from mathics.core.expression import Expression", "or another `SubExpression` `pos` can be `None`, an integer value", "pointer points to the `head` of the expression. If `pos`", "return self.parent.head elif pos == 0: return self.parent.head.head return self.parent.leaves[pos", "# Trivial conversion: if pos is an `Integer`, convert #", "# Now, we have a pointer to an element in", "else: parent.set_element(i - 1, new) class SubExpression(object): \"\"\" This class", "that is not an ExpressionPointer, # keeping the positions of", "return self.parent.leaves[pos - 1].is_atom() def to_expression(self): parent = self.parent p", "len(pspec.leaves) > 2: step = leaves[2].get_int_value() if start is None", "cython: language_level=3 # -*- coding: utf-8 -*- from mathics.core.expression import", "1 return tuple(k for k in range(start, stop, step)) class", "the path to reach the position i = pos.pop() try:", "value. \"\"\" # First, look for the ancestor that is", "= self.position if pos is None: return self.parent.head elif pos", "self._headp.parent.get_head_name() @property def elements(self): return self._elementsp @elements.setter def elements(self, value):", "we have # the path to reach the position i", "conversion: if pos is an `Integer`, convert # to a", "@elements.setter def elements(self, value): raise ValueError(\"SubExpression.leaves is write protected.\") @property", "1), rem_pos) for k in pos ] return self def", "an ExpressionPointer, # keeping the positions of each step: parent", "+ leaf.__str__() for leaf in self.leaves]) + \"\\n\\t]\" ) def", "leaf.__str__() for leaf in self.leaves]) + \"\\n\\t]\" ) def __repr__(self):", "ValueError(\"SubExpression.leaves is write protected.\") @property def leaves(self): return self._elementsp @leaves.setter", "p = self.position if p == 0: if isinstance(parent, Symbol):", "`Expression`. # Now, set it to the new value. if", "MessageException(\"Part\", \"pspec\", pos) if pos is None or type(pos) is", "\" + leaf.__str__() for leaf in self.leaves]) + \"\\n\\t]\" )", "value): raise ValueError(\"Expression.original is write protected.\") @property def head(self): pos", "This class represents a Subexpression of an existing Expression. Assignment", "\"span\", Integer(0)) if start < 0: start = len(expr.leaves) -", "= 0 if step < 0 else len(expr.leaves) - 1", "return ( self.head.__str__() + \"[\\n\" + \",\\n\".join([\"\\t \" + leaf.__str__()", "pos = _pspec_span_to_tuple(pos, expr) else: raise MessageException(\"Part\", \"pspec\", pos) if", "`pos==0`, then the pointer points to the `head` of the", "tuple(k for k in range(start, stop, step)) class ExpressionPointer(object): \"\"\"", "class ExpressionPointer(object): \"\"\" This class represents a reference to a", "is None: stop = 0 if step < 0 else", "else len(expr.leaves) + stop if len(pspec.leaves) > 2: step =", "- 1 if stop is None: stop = 0 if", "parent = parent._head else: parent = parent.elements[i - 1] i", "value): raise ValueError(\"SubExpression.leaves is write protected.\") @property def leaves(self): return", "self.parent pos = [self.position] while type(parent) is ExpressionPointer: position =", "def __str__(self) -> str: return \"%s[[%s]]\" % (self.parent, self.position) def", "continue pos.append(parent.position) parent = parent.parent # At this point, we", "return self.__str__() @property def original(self): return None @original.setter def original(self,", "is ExpressionPointer: self.parent = expr.parent self.position = expr.position else: self.parent", "\"\"\" `expr` can be an `Expression`, a `ExpressionPointer` or another", "another `SubExpression` `pos` can be `None`, an integer value or", "MessageException \"\"\" This module provides some infrastructure to deal with", "leaves) if len(leaves) > 0: start = leaves[0].get_int_value() if len(leaves)", "= self.parent.leaves[p - 1] if isinstance(leaf, Atom): return leaf else:", "Now, we have a pointer to an element in a", "len(self._elementsp): for leaf, sub_new in zip(self._elementsp, new.leaves): leaf.replace(sub_new) else: for", "# cython: language_level=3 # -*- coding: utf-8 -*- from mathics.core.expression", "in the change of the original Expression. \"\"\" def __new__(cls,", "= pos.get_int_value() # pos == `System`All` elif isinstance(pos, Symbol) and", "i = pos.pop() except Exception: raise MessageException(\"Part\", \"span\", pos) #", "ExpressionPointer pointing to the leaf in position `pos` of `expr`.", "self.position if pos is None: return self.parent.head elif pos ==", "def __str__(self): return ( self.head.__str__() + \"[\\n\" + \",\\n\".join([\"\\t \"", "= parent.parent # At this point, we hit the expression,", "get_head_name(self): return self.head.get_name() def is_atom(self): pos = self.position if pos", "1 leaves = pspec.leaves if len(leaves) > 3: raise MessageException(\"Part\",", "parent = parent.parent # At this point, we hit the", "stop is None: if leaves[1].get_name() == \"System`All\": stop = None", "< 0 else len(expr.leaves) - 1 stop = stop +", "> 2: step = leaves[2].get_int_value() if start is None or", "@leaves.setter def leaves(self, value): raise ValueError(\"SubExpression.leaves is write protected.\") def", "else len(expr.leaves) - 1 stop = stop + 1 if", "of `mathics.core.symbols.BaseElement`. \"\"\" def __init__(self, expr, pos=None): \"\"\" Initializes a", "= [i.get_int_value() for i in pos.leaves] if any([i is None", "tuple: self = super(SubExpression, cls).__new__(cls) self._headp = ExpressionPointer(expr.head, 0) self._elementsp", "leaves(self): pos = self.position if pos is None: return self.parent.leaves", "in a true `Expression`. # Now, set it to the", "leaf in an expression. Supports a minimal part of the", "expr self.position = pos def __str__(self) -> str: return \"%s[[%s]]\"", "have # the path to reach the position i =", "\"System`All\": pos = None elif type(pos) is Expression: if pos.has_form(\"System`List\",", "and a Mathics `Span` Expression and returns a tuple with", "None @original.setter def original(self, value): raise ValueError(\"Expression.original is write protected.\")", "= self.position if p == 0: if isinstance(parent, Symbol): return", "another ExpressionPointer pos: int or None If `pos==0`, then the", "return parent.head.copy() else: leaf = self.parent.leaves[p - 1] if isinstance(leaf,", "-*- coding: utf-8 -*- from mathics.core.expression import Expression from mathics.core.symbols", "0: self.parent.head.leaves return self.parent.leaves[pos - 1].leaves @leaves.setter def leaves(self, value):", "Integer from mathics.builtin.base import MessageException \"\"\" This module provides some", "`Expression` that indicates a subset of leaves in the original", "a Subexpression of an existing Expression. Assignment to a subexpression", "a single whole leaf of `expr`, then returns an `ExpressionPointer`.", "write protected.\") @property def head(self): pos = self.position if pos", "expression, and we have # the path to reach the", "stop = leaves[1].get_int_value() if stop is None: if leaves[1].get_name() ==", "`mathics.core.symbols.BaseElement`. \"\"\" def __init__(self, expr, pos=None): \"\"\" Initializes a ExpressionPointer", "# First, look for the ancestor that is not an", "leaves(self, value): raise ValueError(\"SubExpression.leaves is write protected.\") def to_expression(self): return", "Initializes a ExpressionPointer pointing to the leaf in position `pos`", "whole leaf of `expr`, then returns an `ExpressionPointer`. \"\"\" #", "a Symbol, or another ExpressionPointer pos: int or None If", "return self._headp.parent.get_head_name() @property def elements(self): return self._elementsp @elements.setter def elements(self,", "If pos is a list, take the first element, and", "of the expression. If `pos` is `None`, it points out", "1, new) class SubExpression(object): \"\"\" This class represents a Subexpression", "[i.get_int_value() for i in pos.leaves] if any([i is None for", "if type(pos) is Integer: pos = pos.get_int_value() # pos ==", "elif pos == 0: return self.parent.head.is_atom() return self.parent.leaves[pos - 1].is_atom()", "Expression. Assignment to a subexpression results in the change of", "None for i in tuple_pos]): raise MessageException(\"Part\", \"pspec\", pos) pos", "self.leaves]) + \"\\n\\t]\" ) def __repr__(self): return self.__str__() @property def", "get_head_name(self): return self._headp.parent.get_head_name() @property def elements(self): return self._elementsp @elements.setter def", "is write protected.\") @property def leaves(self): pos = self.position if", "minimal part of the basic interface of `mathics.core.symbols.BaseElement`. \"\"\" def", "+ \"[\\n\" + \",\\n\".join([\"\\t \" + leaf.__str__() for leaf in", ") == len(self._elementsp): for leaf, sub_new in zip(self._elementsp, new.leaves): leaf.replace(sub_new)", "write protected.\") def to_expression(self): return Expression( self._headp.to_expression(), *(leaf.to_expression() for leaf", "else: raise MessageException(\"Part\", \"span\", pspec) else: stop = stop -", "i == 0: parent = parent._head else: parent = parent.elements[i", "type(expr) is ExpressionPointer: self.parent = expr.parent self.position = expr.position else:", "ancestor that is not an ExpressionPointer, # keeping the positions", "Integer(0)) if start < 0: start = len(expr.leaves) - start", "the original Expression. \"\"\" def __new__(cls, expr, pos=None): \"\"\" `expr`", "type(parent) is ExpressionPointer: position = parent.position if position is None:", "self.__str__() @property def original(self): return None @original.setter def original(self, value):", "def to_expression(self): return Expression( self._headp.to_expression(), *(leaf.to_expression() for leaf in self._elementsp)", "(self.parent, self.position) def __repr__(self) -> str: return self.__str__() @property def", "step = 1 leaves = pspec.leaves if len(leaves) > 3:", "value): raise ValueError(\"ExpressionPointer.head is write protected.\") @property def leaves(self): pos", "return self.head.get_name() def is_atom(self): pos = self.position if pos is", "= pos.pop() try: while pos: if i == 0: parent", "then returns an `ExpressionPointer`. \"\"\" # If pos is a", "tuple_pos = [i.get_int_value() for i in pos.leaves] if any([i is", "`None`, an integer value or an `Expression` that indicates a", "+ 1), rem_pos) for k in pos ] return self", "for leaf in self._elementsp) ) def replace(self, new): \"\"\" Asigns", "MessageException(\"Part\", \"span\", pos) # Now, we have a pointer to", "the `head` of the expression. If `pos` is `None`, it", "is_atom(self): pos = self.position if pos is None: return self.parent.is_atom()", "None or step is None: raise MessageException(\"Part\", \"span\", pspec) if", "This module provides some infrastructure to deal with SubExpressions. \"\"\"", "reference to a leaf in an expression. Supports a minimal", "some infrastructure to deal with SubExpressions. \"\"\" def _pspec_span_to_tuple(pspec, expr):", "stop, step)) class ExpressionPointer(object): \"\"\" This class represents a reference", "set it to the new value. if i == 0:", "else: stop = stop - 1 if stop > 0", "ExpressionPointer: position = parent.position if position is None: parent =", "\"%s[[%s]]\" % (self.parent, self.position) def __repr__(self) -> str: return self.__str__()", "a reference to a leaf in an expression. Supports a", "= self.position if pos is None: return self.parent.leaves elif pos", "pos is a list, take the first element, and #", "Symbol from mathics.core.atoms import Integer from mathics.builtin.base import MessageException \"\"\"", "self = super(SubExpression, cls).__new__(cls) self._headp = ExpressionPointer(expr.head, 0) self._elementsp =", "if type(pos) in (tuple, list): pos, rem_pos = pos[0], pos[1:]", "i in tuple_pos]): raise MessageException(\"Part\", \"pspec\", pos) pos = tuple_pos", "return leaf else: return leaf.copy() def replace(self, new): \"\"\" This", "leaf, sub_new in zip(self._elementsp, new.leaves): leaf.replace(sub_new) else: for leaf in", "position i = pos.pop() try: while pos: if i ==", "pos = self.position if pos is None: return self.parent.leaves elif", "else: return parent.head.copy() else: leaf = self.parent.leaves[p - 1] if", "integer value or an `Expression` that indicates a subset of", "raise ValueError(\"SubExpression.leaves is write protected.\") @property def leaves(self): return self._elementsp", "pspec) if start == 0 or stop == 0: #", "pos.pop() except Exception: raise MessageException(\"Part\", \"span\", pos) # Now, we", "= [ SubExpression(ExpressionPointer(expr, k + 1), rem_pos) for k in", "None If `pos==0`, then the pointer points to the `head`", "Expression. \"\"\" def __new__(cls, expr, pos=None): \"\"\" `expr` can be", "if pos is None: return self.parent.is_atom() elif pos == 0:", "rem_pos = pos[0], pos[1:] if len(rem_pos) == 0: rem_pos =", "to_expression(self): return Expression( self._headp.to_expression(), *(leaf.to_expression() for leaf in self._elementsp) )", "a Mathics `Span` Expression and returns a tuple with the", "if stop > 0 else len(expr.leaves) + stop if len(pspec.leaves)", "head(self): pos = self.position if pos is None: return self.parent.head", "parent.elements[i - 1] i = pos.pop() except Exception: raise MessageException(\"Part\",", "\"System`List\") and len( new.leaves ) == len(self._elementsp): for leaf, sub_new", "pos=None): \"\"\" `expr` can be an `Expression`, a `ExpressionPointer` or", "native int if type(pos) is Integer: pos = pos.get_int_value() #", "rem_pos = None # Trivial conversion: if pos is an", "if type(expr) is ExpressionPointer: self.parent = expr.parent self.position = expr.position", "\"\"\" # First, look for the ancestor that is not", "def leaves(self): pos = self.position if pos is None: return", "for k in range(start, stop, step)) class ExpressionPointer(object): \"\"\" This", "def leaves(self, value): raise ValueError(\"ExpressionPointer.leaves is write protected.\") def get_head_name(self):", "This class represents a reference to a leaf in an", "- 1].is_atom() def to_expression(self): parent = self.parent p = self.position", "an expression and a Mathics `Span` Expression and returns a", "a ExpressionPointer pointing to the leaf in position `pos` of", "k in range(start, stop, step)) class ExpressionPointer(object): \"\"\" This class", "- 1] i = pos.pop() except Exception: raise MessageException(\"Part\", \"span\",", "step < 0 else len(expr.leaves) - 1 stop = stop", "with the positions of the leaves. \"\"\" start = 1", "None: return self.parent.leaves elif pos == 0: self.parent.head.leaves return self.parent.leaves[pos", "to deal with SubExpressions. \"\"\" def _pspec_span_to_tuple(pspec, expr): \"\"\" This", "ValueError(\"SubExpression.leaves is write protected.\") def to_expression(self): return Expression( self._headp.to_expression(), *(leaf.to_expression()", "return self.parent.head.is_atom() return self.parent.leaves[pos - 1].is_atom() def to_expression(self): parent =", "pos.pop() try: while pos: if i == 0: parent =", "isinstance(leaf, Atom): return leaf else: return leaf.copy() def replace(self, new):", "len(leaves) > 0: start = leaves[0].get_int_value() if len(leaves) > 1:", "def is_atom(self): pos = self.position if pos is None: return", "`expr`, then returns an `ExpressionPointer`. \"\"\" # If pos is", "start = 1 stop = None step = 1 leaves", "MessageException(\"Part\", \"span\", pspec) else: stop = stop - 1 if", "and pos.get_name() == \"System`All\": pos = None elif type(pos) is", "to the new value. if i == 0: parent.set_head(new) else:", "# store the remainder. if type(pos) in (tuple, list): pos,", "This method replaces the value pointed out by a `new`", "is tuple: self = super(SubExpression, cls).__new__(cls) self._headp = ExpressionPointer(expr.head, 0)", "value): raise ValueError(\"SubExpression.head is write protected.\") def get_head_name(self): return self._headp.parent.get_head_name()", "ValueError(\"SubExpression.head is write protected.\") def get_head_name(self): return self._headp.parent.get_head_name() @property def", "leaf in position `pos` of `expr`. expr: can be an", "value. if i == 0: parent.set_head(new) else: parent.set_element(i - 1,", "be `None`, an integer value or an `Expression` that indicates", "to a subexpression results in the change of the original", "an `ExpressionPointer`. \"\"\" # If pos is a list, take", "pos=None): \"\"\" Initializes a ExpressionPointer pointing to the leaf in", "1: stop = leaves[1].get_int_value() if stop is None: if leaves[1].get_name()", "rem_pos) for k in pos ] return self def is_atom(self):", "- start else: start = start - 1 if stop", "`pos` is `None`, it points out the whole expression. \"\"\"", "pspec) else: stop = stop - 1 if stop >", "pos[1:] if len(rem_pos) == 0: rem_pos = None else: rem_pos", "or type(pos) is int: if rem_pos is None: return ExpressionPointer(expr,", "leaves[2].get_int_value() if start is None or step is None: raise", "any([i is None for i in tuple_pos]): raise MessageException(\"Part\", \"pspec\",", "pos: if i == 0: parent = parent._head else: parent", "if stop is None: if leaves[1].get_name() == \"System`All\": stop =", "None: stop = 0 if step < 0 else len(expr.leaves)", "stop = stop + 1 if step > 0 else", "stop - 1 return tuple(k for k in range(start, stop,", "pos.append(parent.position) parent = parent.parent # At this point, we hit", "basic interface of `mathics.core.symbols.BaseElement`. \"\"\" def __init__(self, expr, pos=None): \"\"\"", "rem_pos) elif type(pos) is tuple: self = super(SubExpression, cls).__new__(cls) self._headp", "pos is None or type(pos) is int: if rem_pos is", "expr): \"\"\" This function takes an expression and a Mathics", "self.position) def __repr__(self) -> str: return self.__str__() @property def original(self):", "(tuple, list): pos, rem_pos = pos[0], pos[1:] if len(rem_pos) ==", "if start < 0: start = len(expr.leaves) - start else:", "@leaves.setter def leaves(self, value): raise ValueError(\"ExpressionPointer.leaves is write protected.\") def", "protected.\") def get_head_name(self): return self._headp.parent.get_head_name() @property def elements(self): return self._elementsp", "> 0: start = leaves[0].get_int_value() if len(leaves) > 1: stop", "mathics.core.symbols import Atom, Symbol from mathics.core.atoms import Integer from mathics.builtin.base", "leaf = self.parent.leaves[p - 1] if isinstance(leaf, Atom): return leaf", "parent.parent continue pos.append(parent.position) parent = parent.parent # At this point,", "points out the whole expression. \"\"\" if pos is None:", "is write protected.\") def get_head_name(self): return self.head.get_name() def is_atom(self): pos", "= [self.position] while type(parent) is ExpressionPointer: position = parent.position if", "is None: if leaves[1].get_name() == \"System`All\": stop = None else:", "self.position = pos def __str__(self) -> str: return \"%s[[%s]]\" %", "None: parent = parent.parent continue pos.append(parent.position) parent = parent.parent #", "== \"System`List\") and len( new.leaves ) == len(self._elementsp): for leaf,", "return leaf.copy() def replace(self, new): \"\"\" This method replaces the", "parent = parent.parent continue pos.append(parent.position) parent = parent.parent # At", "module provides some infrastructure to deal with SubExpressions. \"\"\" def", "by a `new` value. \"\"\" # First, look for the", "else: parent = parent.elements[i - 1] i = pos.pop() except", "= leaves[2].get_int_value() if start is None or step is None:", "Expression and returns a tuple with the positions of the", "Symbol, or another ExpressionPointer pos: int or None If `pos==0`,", "= stop + 1 if step > 0 else stop", "3: raise MessageException(\"Part\", \"span\", leaves) if len(leaves) > 0: start", "0: parent.set_head(new) else: parent.set_element(i - 1, new) class SubExpression(object): \"\"\"", "`SubExpression` `pos` can be `None`, an integer value or an", "if len(rem_pos) == 0: rem_pos = None else: rem_pos =", "= tuple_pos elif pos.has_form(\"System`Span\", None): pos = _pspec_span_to_tuple(pos, expr) else:", "if stop is None: stop = 0 if step <", "positions of each step: parent = self.parent pos = [self.position]", "start = leaves[0].get_int_value() if len(leaves) > 1: stop = leaves[1].get_int_value()", "raise MessageException(\"Part\", \"span\", pspec) if start == 0 or stop", "At this point, we hit the expression, and we have", "== 0 or stop == 0: # index 0 is", "False def __str__(self): return ( self.head.__str__() + \"[\\n\" + \",\\n\".join([\"\\t", "convert # to a Python native int if type(pos) is", "import MessageException \"\"\" This module provides some infrastructure to deal", "len(expr.leaves) - start else: start = start - 1 if", "Atom, Symbol from mathics.core.atoms import Integer from mathics.builtin.base import MessageException", "@original.setter def original(self, value): raise ValueError(\"Expression.original is write protected.\") @property", "class represents a reference to a leaf in an expression.", "\"\"\" This function takes an expression and a Mathics `Span`", "k + 1), rem_pos) for k in pos ] return", "def head(self): return self._headp @head.setter def head(self, value): raise ValueError(\"SubExpression.head", "protected.\") def to_expression(self): return Expression( self._headp.to_expression(), *(leaf.to_expression() for leaf in", "in zip(self._elementsp, new.leaves): leaf.replace(sub_new) else: for leaf in self._elementsp: leaf.replace(new)", "2: step = leaves[2].get_int_value() if start is None or step", "0: return self.parent.head.head return self.parent.leaves[pos - 1].head @head.setter def head(self,", "import Expression from mathics.core.symbols import Atom, Symbol from mathics.core.atoms import", "import Integer from mathics.builtin.base import MessageException \"\"\" This module provides", "position `pos` of `expr`. expr: can be an Expression, a", "= self.parent p = self.position if p == 0: if", "parent = parent.elements[i - 1] i = pos.pop() except Exception:", "self.parent.leaves elif pos == 0: self.parent.head.leaves return self.parent.leaves[pos - 1].leaves", "__str__(self) -> str: return \"%s[[%s]]\" % (self.parent, self.position) def __repr__(self)", "\"\"\" Initializes a ExpressionPointer pointing to the leaf in position", "list, take the first element, and # store the remainder.", "pos = None elif type(pos) is Expression: if pos.has_form(\"System`List\", None):", "in pos ] return self def is_atom(self): return False def", "def __repr__(self): return self.__str__() @property def head(self): return self._headp @head.setter", "reach the position i = pos.pop() try: while pos: if", "of the leaves. \"\"\" start = 1 stop = None", "a subexpression results in the change of the original Expression.", "the ancestor that is not an ExpressionPointer, # keeping the", "raise MessageException(\"Part\", \"span\", pspec) else: stop = stop - 1", "the positions of each step: parent = self.parent pos =", "expr: can be an Expression, a Symbol, or another ExpressionPointer", "we have a pointer to an element in a true", "leaves(self, value): raise ValueError(\"ExpressionPointer.leaves is write protected.\") def get_head_name(self): return", "or step is None: raise MessageException(\"Part\", \"span\", pspec) if start", "this point, we hit the expression, and we have #", "return self._elementsp @leaves.setter def leaves(self, value): raise ValueError(\"SubExpression.leaves is write", "0 if step < 0 else len(expr.leaves) - 1 stop", "leaf in self._elementsp) ) def replace(self, new): \"\"\" Asigns `new`", "\"[\\n\" + \",\\n\".join([\"\\t \" + leaf.__str__() for leaf in self.leaves])", "= leaves[0].get_int_value() if len(leaves) > 1: stop = leaves[1].get_int_value() if", "= expr.parent self.position = expr.position else: self.parent = expr self.position", "_pspec_span_to_tuple(pos, expr) else: raise MessageException(\"Part\", \"pspec\", pos) if pos is", "else: self.parent = expr self.position = None else: self.parent =", "% (self.parent, self.position) def __repr__(self) -> str: return self.__str__() @property", "`ExpressionPointer`. \"\"\" # If pos is a list, take the", "= start - 1 if stop is None: stop =", "pos == 0: return self.parent.head.head return self.parent.leaves[pos - 1].head @head.setter", "# to a Python native int if type(pos) is Integer:", "\"pspec\", pos) if pos is None or type(pos) is int:", "None: return self.parent.head elif pos == 0: return self.parent.head.head return", "_pspec_span_to_tuple(pspec, expr): \"\"\" This function takes an expression and a", "1 if stop > 0 else len(expr.leaves) + stop if", "is Expression: if pos.has_form(\"System`List\", None): tuple_pos = [i.get_int_value() for i", "leaves in the original `Expression`. If `pos` points out to", "subset of leaves in the original `Expression`. If `pos` points", "or None If `pos==0`, then the pointer points to the", "len(leaves) > 3: raise MessageException(\"Part\", \"span\", leaves) if len(leaves) >", "is None or type(pos) is int: if rem_pos is None:", "== 0: if isinstance(parent, Symbol): return parent else: return parent.head.copy()", "leaf.copy() def replace(self, new): \"\"\" This method replaces the value", "SubExpression(ExpressionPointer(expr, k + 1), rem_pos) for k in pos ]", "\"\"\" start = 1 stop = None step = 1", "indicates a subset of leaves in the original `Expression`. If", "in the original `Expression`. If `pos` points out to a", "in self.leaves]) + \"\\n\\t]\" ) def __repr__(self): return self.__str__() @property", "- 1, new) class SubExpression(object): \"\"\" This class represents a", "is None for i in tuple_pos]): raise MessageException(\"Part\", \"pspec\", pos)", "\"\"\" Asigns `new` to the subexpression, according to the logic", "This function takes an expression and a Mathics `Span` Expression", "parent.parent # At this point, we hit the expression, and", "to the leaf in position `pos` of `expr`. expr: can", "elements(self, value): raise ValueError(\"SubExpression.leaves is write protected.\") @property def leaves(self):", "existing Expression. Assignment to a subexpression results in the change", "0: start = len(expr.leaves) - start else: start = start", "- 1].head @head.setter def head(self, value): raise ValueError(\"ExpressionPointer.head is write", "Trivial conversion: if pos is an `Integer`, convert # to", "pos) pos = tuple_pos elif pos.has_form(\"System`Span\", None): pos = _pspec_span_to_tuple(pos,", "@head.setter def head(self, value): raise ValueError(\"ExpressionPointer.head is write protected.\") @property", "if isinstance(leaf, Atom): return leaf else: return leaf.copy() def replace(self,", "the positions of the leaves. \"\"\" start = 1 stop", "the change of the original Expression. \"\"\" def __new__(cls, expr,", "1].head @head.setter def head(self, value): raise ValueError(\"ExpressionPointer.head is write protected.\")", "self.parent.is_atom() elif pos == 0: return self.parent.head.is_atom() return self.parent.leaves[pos -", "If `pos` is `None`, it points out the whole expression.", "leaf of `expr`, then returns an `ExpressionPointer`. \"\"\" # If", "super(SubExpression, cls).__new__(cls) self._headp = ExpressionPointer(expr.head, 0) self._elementsp = [ SubExpression(ExpressionPointer(expr,", "return self.parent.leaves[pos - 1].head @head.setter def head(self, value): raise ValueError(\"ExpressionPointer.head", "len(expr.leaves) + stop if len(pspec.leaves) > 2: step = leaves[2].get_int_value()", "== 0: # index 0 is undefined raise MessageException(\"Part\", \"span\",", "the original `Expression`. If `pos` points out to a single", "# If pos is a list, take the first element,", "*(leaf.to_expression() for leaf in self._elementsp) ) def replace(self, new): \"\"\"", "an expression. Supports a minimal part of the basic interface", "deal with SubExpressions. \"\"\" def _pspec_span_to_tuple(pspec, expr): \"\"\" This function", "if step > 0 else stop - 1 return tuple(k", "stop = 0 if step < 0 else len(expr.leaves) -", "the position i = pos.pop() try: while pos: if i", "1 if stop is None: stop = 0 if step", "self.position = expr.position else: self.parent = expr self.position = None", "self.parent p = self.position if p == 0: if isinstance(parent,", "from mathics.core.atoms import Integer from mathics.builtin.base import MessageException \"\"\" This", "start < 0: start = len(expr.leaves) - start else: start", "keeping the positions of each step: parent = self.parent pos", "points to the `head` of the expression. If `pos` is", "isinstance(pos, Symbol) and pos.get_name() == \"System`All\": pos = None elif", "== 0: return self.parent.head.is_atom() return self.parent.leaves[pos - 1].is_atom() def to_expression(self):", "raise ValueError(\"Expression.original is write protected.\") @property def head(self): pos =", "else: start = start - 1 if stop is None:", "if isinstance(parent, Symbol): return parent else: return parent.head.copy() else: leaf", "raise MessageException(\"Part\", \"pspec\", pos) pos = tuple_pos elif pos.has_form(\"System`Span\", None):", "take the first element, and # store the remainder. if", "is `None`, it points out the whole expression. \"\"\" if", "parent = self.parent p = self.position if p == 0:", "class represents a Subexpression of an existing Expression. Assignment to", "is None or step is None: raise MessageException(\"Part\", \"span\", pspec)", "= self.parent pos = [self.position] while type(parent) is ExpressionPointer: position", "str: return self.__str__() @property def original(self): return None @original.setter def", "else: leaf = self.parent.leaves[p - 1] if isinstance(leaf, Atom): return", "= None step = 1 leaves = pspec.leaves if len(leaves)", "MessageException(\"Part\", \"span\", pspec) if start == 0 or stop ==", "element, and # store the remainder. if type(pos) in (tuple,", "= pos[0], pos[1:] if len(rem_pos) == 0: rem_pos = None", "if pos.has_form(\"System`List\", None): tuple_pos = [i.get_int_value() for i in pos.leaves]", "utf-8 -*- from mathics.core.expression import Expression from mathics.core.symbols import Atom,", "if pos is an `Integer`, convert # to a Python", "an `Expression` that indicates a subset of leaves in the", "self.parent = expr.parent self.position = expr.position else: self.parent = expr", "None else: rem_pos = None # Trivial conversion: if pos", "single whole leaf of `expr`, then returns an `ExpressionPointer`. \"\"\"", "__new__(cls, expr, pos=None): \"\"\" `expr` can be an `Expression`, a", "- 1] if isinstance(leaf, Atom): return leaf else: return leaf.copy()", "`expr` can be an `Expression`, a `ExpressionPointer` or another `SubExpression`", "pos = pos.get_int_value() # pos == `System`All` elif isinstance(pos, Symbol)", "Symbol): return parent else: return parent.head.copy() else: leaf = self.parent.leaves[p", "whole expression. \"\"\" if pos is None: if type(expr) is", "\"span\", pos) # Now, we have a pointer to an", "represents a Subexpression of an existing Expression. Assignment to a", "`head` of the expression. If `pos` is `None`, it points", "> 0 else len(expr.leaves) + stop if len(pspec.leaves) > 2:", "def original(self): return None @original.setter def original(self, value): raise ValueError(\"Expression.original", "SubExpression(object): \"\"\" This class represents a Subexpression of an existing", "returns an `ExpressionPointer`. \"\"\" # If pos is a list,", "if (new.has_form(\"List\", None) or new.get_head_name() == \"System`List\") and len( new.leaves", "change of the original Expression. \"\"\" def __new__(cls, expr, pos=None):", "logic of `mathics.core.walk_parts` \"\"\" if (new.has_form(\"List\", None) or new.get_head_name() ==", "i in pos.leaves] if any([i is None for i in", "self._headp.to_expression(), *(leaf.to_expression() for leaf in self._elementsp) ) def replace(self, new):", "[ SubExpression(ExpressionPointer(expr, k + 1), rem_pos) for k in pos", "MessageException(\"Part\", \"span\", leaves) if len(leaves) > 0: start = leaves[0].get_int_value()", "the expression, and we have # the path to reach", "with SubExpressions. \"\"\" def _pspec_span_to_tuple(pspec, expr): \"\"\" This function takes", "coding: utf-8 -*- from mathics.core.expression import Expression from mathics.core.symbols import", "if i == 0: parent.set_head(new) else: parent.set_element(i - 1, new)", "pos is None: return self.parent.is_atom() elif pos == 0: return", "type(pos) is int: if rem_pos is None: return ExpressionPointer(expr, pos)", "def elements(self, value): raise ValueError(\"SubExpression.leaves is write protected.\") @property def", "p == 0: if isinstance(parent, Symbol): return parent else: return", "parent.set_element(i - 1, new) class SubExpression(object): \"\"\" This class represents", "\"System`All\": stop = None else: raise MessageException(\"Part\", \"span\", pspec) else:", "@property def original(self): return None @original.setter def original(self, value): raise", "returns a tuple with the positions of the leaves. \"\"\"", "pos is None: return self.parent.leaves elif pos == 0: self.parent.head.leaves", "to a leaf in an expression. Supports a minimal part", "None step = 1 leaves = pspec.leaves if len(leaves) >", "`new` value. \"\"\" # First, look for the ancestor that", "\"pspec\", pos) pos = tuple_pos elif pos.has_form(\"System`Span\", None): pos =", "import Atom, Symbol from mathics.core.atoms import Integer from mathics.builtin.base import", "if pos is None: return self.parent.leaves elif pos == 0:", "protected.\") @property def leaves(self): return self._elementsp @leaves.setter def leaves(self, value):", "self.parent.head.head return self.parent.leaves[pos - 1].head @head.setter def head(self, value): raise", "write protected.\") def get_head_name(self): return self.head.get_name() def is_atom(self): pos =", "== `System`All` elif isinstance(pos, Symbol) and pos.get_name() == \"System`All\": pos", "= leaves[1].get_int_value() if stop is None: if leaves[1].get_name() == \"System`All\":", "ValueError(\"ExpressionPointer.leaves is write protected.\") def get_head_name(self): return self.head.get_name() def is_atom(self):", "is None: return self.parent.is_atom() elif pos == 0: return self.parent.head.is_atom()", "0: if isinstance(parent, Symbol): return parent else: return parent.head.copy() else:", "if len(leaves) > 3: raise MessageException(\"Part\", \"span\", leaves) if len(leaves)", "Atom): return leaf else: return leaf.copy() def replace(self, new): \"\"\"", "SubExpressions. \"\"\" def _pspec_span_to_tuple(pspec, expr): \"\"\" This function takes an", "and returns a tuple with the positions of the leaves.", "is None: raise MessageException(\"Part\", \"span\", pspec) if start == 0", "parent else: return parent.head.copy() else: leaf = self.parent.leaves[p - 1]", "original(self): return None @original.setter def original(self, value): raise ValueError(\"Expression.original is", "0 else len(expr.leaves) + stop if len(pspec.leaves) > 2: step", "to the `head` of the expression. If `pos` is `None`,", "Expression from mathics.core.symbols import Atom, Symbol from mathics.core.atoms import Integer", "to an element in a true `Expression`. # Now, set", "we hit the expression, and we have # the path", "# pos == `System`All` elif isinstance(pos, Symbol) and pos.get_name() ==", "is not an ExpressionPointer, # keeping the positions of each", "in tuple_pos]): raise MessageException(\"Part\", \"pspec\", pos) pos = tuple_pos elif", "subexpression results in the change of the original Expression. \"\"\"", "self.head.__str__() + \"[\\n\" + \",\\n\".join([\"\\t \" + leaf.__str__() for leaf", "None) or new.get_head_name() == \"System`List\") and len( new.leaves ) ==", "pspec.leaves if len(leaves) > 3: raise MessageException(\"Part\", \"span\", leaves) if", "value or an `Expression` that indicates a subset of leaves", "the first element, and # store the remainder. if type(pos)", "rem_pos is None: return ExpressionPointer(expr, pos) else: return SubExpression(ExpressionPointer(expr, pos),", "`None`, it points out the whole expression. \"\"\" if pos", "else stop - 1 return tuple(k for k in range(start,", "leaves[1].get_int_value() if stop is None: if leaves[1].get_name() == \"System`All\": stop", "ValueError(\"Expression.original is write protected.\") @property def head(self): pos = self.position", "return Expression( self._headp.to_expression(), *(leaf.to_expression() for leaf in self._elementsp) ) def", "__init__(self, expr, pos=None): \"\"\" Initializes a ExpressionPointer pointing to the", "def head(self): pos = self.position if pos is None: return", "\"\\n\\t]\" ) def __repr__(self): return self.__str__() @property def head(self): return", "first element, and # store the remainder. if type(pos) in", "start = len(expr.leaves) - start else: start = start -", "# the path to reach the position i = pos.pop()", "== 0: rem_pos = None else: rem_pos = None #", ") def __repr__(self): return self.__str__() @property def head(self): return self._headp", "0 else len(expr.leaves) - 1 stop = stop + 1", "self._elementsp = [ SubExpression(ExpressionPointer(expr, k + 1), rem_pos) for k", "for leaf, sub_new in zip(self._elementsp, new.leaves): leaf.replace(sub_new) else: for leaf", "infrastructure to deal with SubExpressions. \"\"\" def _pspec_span_to_tuple(pspec, expr): \"\"\"", "an element in a true `Expression`. # Now, set it", "value): raise ValueError(\"SubExpression.leaves is write protected.\") def to_expression(self): return Expression(", "is write protected.\") def to_expression(self): return Expression( self._headp.to_expression(), *(leaf.to_expression() for", "can be an `Expression`, a `ExpressionPointer` or another `SubExpression` `pos`", "of leaves in the original `Expression`. If `pos` points out", "according to the logic of `mathics.core.walk_parts` \"\"\" if (new.has_form(\"List\", None)", "First, look for the ancestor that is not an ExpressionPointer,", "if len(leaves) > 0: start = leaves[0].get_int_value() if len(leaves) >", "def __new__(cls, expr, pos=None): \"\"\" `expr` can be an `Expression`,", "None: if type(expr) is ExpressionPointer: self.parent = expr.parent self.position =", "points out to a single whole leaf of `expr`, then", "is a list, take the first element, and # store", "pos, rem_pos = pos[0], pos[1:] if len(rem_pos) == 0: rem_pos", "self._elementsp @leaves.setter def leaves(self, value): raise ValueError(\"SubExpression.leaves is write protected.\")", "an `Integer`, convert # to a Python native int if", "`System`All` elif isinstance(pos, Symbol) and pos.get_name() == \"System`All\": pos =", "None): pos = _pspec_span_to_tuple(pos, expr) else: raise MessageException(\"Part\", \"pspec\", pos)", "if any([i is None for i in tuple_pos]): raise MessageException(\"Part\",", "\"\"\" def __new__(cls, expr, pos=None): \"\"\" `expr` can be an", "= ExpressionPointer(expr.head, 0) self._elementsp = [ SubExpression(ExpressionPointer(expr, k + 1),", "step = leaves[2].get_int_value() if start is None or step is", "if i == 0: parent = parent._head else: parent =", "stop + 1 if step > 0 else stop -", "+ \"\\n\\t]\" ) def __repr__(self): return self.__str__() @property def head(self):", "self.parent = expr self.position = None else: self.parent = expr", "a `new` value. \"\"\" # First, look for the ancestor", "None or type(pos) is int: if rem_pos is None: return", "if start == 0 or stop == 0: # index", "expression. If `pos` is `None`, it points out the whole", "elements(self): return self._elementsp @elements.setter def elements(self, value): raise ValueError(\"SubExpression.leaves is", "None: raise MessageException(\"Part\", \"span\", pspec) if start == 0 or", "new): \"\"\" Asigns `new` to the subexpression, according to the", "out to a single whole leaf of `expr`, then returns", "head(self, value): raise ValueError(\"ExpressionPointer.head is write protected.\") @property def leaves(self):", "@property def leaves(self): pos = self.position if pos is None:", "def elements(self): return self._elementsp @elements.setter def elements(self, value): raise ValueError(\"SubExpression.leaves", "return self.parent.head.head return self.parent.leaves[pos - 1].head @head.setter def head(self, value):", "= None else: self.parent = expr self.position = pos def", "start - 1 if stop is None: stop = 0", "None: return ExpressionPointer(expr, pos) else: return SubExpression(ExpressionPointer(expr, pos), rem_pos) elif", "expr.parent self.position = expr.position else: self.parent = expr self.position =", "\"\"\" if pos is None: if type(expr) is ExpressionPointer: self.parent", "expr, pos=None): \"\"\" `expr` can be an `Expression`, a `ExpressionPointer`", "position = parent.position if position is None: parent = parent.parent", "self._headp = ExpressionPointer(expr.head, 0) self._elementsp = [ SubExpression(ExpressionPointer(expr, k +", "not an ExpressionPointer, # keeping the positions of each step:", "] return self def is_atom(self): return False def __str__(self): return", "+ stop if len(pspec.leaves) > 2: step = leaves[2].get_int_value() if", "= expr.position else: self.parent = expr self.position = None else:", "def head(self, value): raise ValueError(\"ExpressionPointer.head is write protected.\") @property def", "None else: raise MessageException(\"Part\", \"span\", pspec) else: stop = stop", "to reach the position i = pos.pop() try: while pos:", "part of the basic interface of `mathics.core.symbols.BaseElement`. \"\"\" def __init__(self,", "isinstance(parent, Symbol): return parent else: return parent.head.copy() else: leaf =", "None): tuple_pos = [i.get_int_value() for i in pos.leaves] if any([i", "is None: return self.parent.leaves elif pos == 0: self.parent.head.leaves return", "type(pos) in (tuple, list): pos, rem_pos = pos[0], pos[1:] if", "a minimal part of the basic interface of `mathics.core.symbols.BaseElement`. \"\"\"", "raise ValueError(\"ExpressionPointer.leaves is write protected.\") def get_head_name(self): return self.head.get_name() def", "self.parent.head elif pos == 0: return self.parent.head.head return self.parent.leaves[pos -", "int if type(pos) is Integer: pos = pos.get_int_value() # pos", "type(pos) is Expression: if pos.has_form(\"System`List\", None): tuple_pos = [i.get_int_value() for", "1] i = pos.pop() except Exception: raise MessageException(\"Part\", \"span\", pos)", "is write protected.\") def get_head_name(self): return self._headp.parent.get_head_name() @property def elements(self):", ") def replace(self, new): \"\"\" Asigns `new` to the subexpression,", "a Python native int if type(pos) is Integer: pos =", "# index 0 is undefined raise MessageException(\"Part\", \"span\", Integer(0)) if", "in self._elementsp) ) def replace(self, new): \"\"\" Asigns `new` to", "pos) if pos is None or type(pos) is int: if", "= stop - 1 if stop > 0 else len(expr.leaves)", "self._headp @head.setter def head(self, value): raise ValueError(\"SubExpression.head is write protected.\")", "None elif type(pos) is Expression: if pos.has_form(\"System`List\", None): tuple_pos =", "type(pos) is tuple: self = super(SubExpression, cls).__new__(cls) self._headp = ExpressionPointer(expr.head,", "a tuple with the positions of the leaves. \"\"\" start", "expr, pos=None): \"\"\" Initializes a ExpressionPointer pointing to the leaf", "pos), rem_pos) elif type(pos) is tuple: self = super(SubExpression, cls).__new__(cls)", "# Now, set it to the new value. if i", "0 else stop - 1 return tuple(k for k in", "`Integer`, convert # to a Python native int if type(pos)", "pointed out by a `new` value. \"\"\" # First, look", "for the ancestor that is not an ExpressionPointer, # keeping", "the remainder. if type(pos) in (tuple, list): pos, rem_pos =", "replace(self, new): \"\"\" Asigns `new` to the subexpression, according to", "== 0: return self.parent.head.head return self.parent.leaves[pos - 1].head @head.setter def", "pos ] return self def is_atom(self): return False def __str__(self):", "or an `Expression` that indicates a subset of leaves in", "an Expression, a Symbol, or another ExpressionPointer pos: int or", "new value. if i == 0: parent.set_head(new) else: parent.set_element(i -", "+ 1 if step > 0 else stop - 1", "= None elif type(pos) is Expression: if pos.has_form(\"System`List\", None): tuple_pos", "pos is None: return self.parent.head elif pos == 0: return", "an existing Expression. Assignment to a subexpression results in the", "if start is None or step is None: raise MessageException(\"Part\",", "def replace(self, new): \"\"\" This method replaces the value pointed", "- 1 if stop > 0 else len(expr.leaves) + stop", "None: if leaves[1].get_name() == \"System`All\": stop = None else: raise", "Mathics `Span` Expression and returns a tuple with the positions", "it to the new value. if i == 0: parent.set_head(new)", "pointing to the leaf in position `pos` of `expr`. expr:", "\"span\", leaves) if len(leaves) > 0: start = leaves[0].get_int_value() if", "pos = [self.position] while type(parent) is ExpressionPointer: position = parent.position", "`pos` can be `None`, an integer value or an `Expression`", "\"\"\" This class represents a reference to a leaf in", "can be an Expression, a Symbol, or another ExpressionPointer pos:", "return self def is_atom(self): return False def __str__(self): return (", "self.position = None else: self.parent = expr self.position = pos", "positions of the leaves. \"\"\" start = 1 stop =", "\"\"\" # If pos is a list, take the first", "`Expression`. If `pos` points out to a single whole leaf", "`mathics.core.walk_parts` \"\"\" if (new.has_form(\"List\", None) or new.get_head_name() == \"System`List\") and", "a `ExpressionPointer` or another `SubExpression` `pos` can be `None`, an", "def get_head_name(self): return self._headp.parent.get_head_name() @property def elements(self): return self._elementsp @elements.setter", "pos == 0: self.parent.head.leaves return self.parent.leaves[pos - 1].leaves @leaves.setter def", "ExpressionPointer(expr.head, 0) self._elementsp = [ SubExpression(ExpressionPointer(expr, k + 1), rem_pos)", "> 0 else stop - 1 return tuple(k for k", "0 is undefined raise MessageException(\"Part\", \"span\", Integer(0)) if start <", "\"\"\" def _pspec_span_to_tuple(pspec, expr): \"\"\" This function takes an expression", "1].is_atom() def to_expression(self): parent = self.parent p = self.position if", "of each step: parent = self.parent pos = [self.position] while", "ExpressionPointer pos: int or None If `pos==0`, then the pointer", "\"\"\" This module provides some infrastructure to deal with SubExpressions.", "expr) else: raise MessageException(\"Part\", \"pspec\", pos) if pos is None", "k in pos ] return self def is_atom(self): return False", "Expression, a Symbol, or another ExpressionPointer pos: int or None", "If `pos==0`, then the pointer points to the `head` of", "pos = self.position if pos is None: return self.parent.head elif", "= parent.position if position is None: parent = parent.parent continue", "return False def __str__(self): return ( self.head.__str__() + \"[\\n\" +", "else: rem_pos = None # Trivial conversion: if pos is", "== \"System`All\": stop = None else: raise MessageException(\"Part\", \"span\", pspec)", "pointer to an element in a true `Expression`. # Now,", "elif type(pos) is Expression: if pos.has_form(\"System`List\", None): tuple_pos = [i.get_int_value()", "is None: return ExpressionPointer(expr, pos) else: return SubExpression(ExpressionPointer(expr, pos), rem_pos)", "results in the change of the original Expression. \"\"\" def", "= pspec.leaves if len(leaves) > 3: raise MessageException(\"Part\", \"span\", leaves)", "the whole expression. \"\"\" if pos is None: if type(expr)", "= expr self.position = None else: self.parent = expr self.position", "is write protected.\") @property def head(self): pos = self.position if", "def _pspec_span_to_tuple(pspec, expr): \"\"\" This function takes an expression and", "expr self.position = None else: self.parent = expr self.position =", "int: if rem_pos is None: return ExpressionPointer(expr, pos) else: return", "stop > 0 else len(expr.leaves) + stop if len(pspec.leaves) >", "step > 0 else stop - 1 return tuple(k for", "-> str: return self.__str__() @property def original(self): return None @original.setter", "store the remainder. if type(pos) in (tuple, list): pos, rem_pos", "\"\"\" This class represents a Subexpression of an existing Expression.", "takes an expression and a Mathics `Span` Expression and returns", "self.parent.head.is_atom() return self.parent.leaves[pos - 1].is_atom() def to_expression(self): parent = self.parent", "original Expression. \"\"\" def __new__(cls, expr, pos=None): \"\"\" `expr` can", "@property def elements(self): return self._elementsp @elements.setter def elements(self, value): raise", "> 1: stop = leaves[1].get_int_value() if stop is None: if", "Exception: raise MessageException(\"Part\", \"span\", pos) # Now, we have a", "subexpression, according to the logic of `mathics.core.walk_parts` \"\"\" if (new.has_form(\"List\",", "pos) else: return SubExpression(ExpressionPointer(expr, pos), rem_pos) elif type(pos) is tuple:", "start == 0 or stop == 0: # index 0", "`expr`. expr: can be an Expression, a Symbol, or another", "pos = self.position if pos is None: return self.parent.is_atom() elif", "Now, set it to the new value. if i ==", "If `pos` points out to a single whole leaf of", "None # Trivial conversion: if pos is an `Integer`, convert", "a true `Expression`. # Now, set it to the new", "pos[0], pos[1:] if len(rem_pos) == 0: rem_pos = None else:", "= None else: raise MessageException(\"Part\", \"span\", pspec) else: stop =", "out the whole expression. \"\"\" if pos is None: if", "- 1 return tuple(k for k in range(start, stop, step))", "if len(leaves) > 1: stop = leaves[1].get_int_value() if stop is", "from mathics.core.expression import Expression from mathics.core.symbols import Atom, Symbol from", "remainder. if type(pos) in (tuple, list): pos, rem_pos = pos[0],", "pos) # Now, we have a pointer to an element", "= parent.elements[i - 1] i = pos.pop() except Exception: raise", "leaf else: return leaf.copy() def replace(self, new): \"\"\" This method", "stop = stop - 1 if stop > 0 else", "self.parent.head.leaves return self.parent.leaves[pos - 1].leaves @leaves.setter def leaves(self, value): raise", "pos: int or None If `pos==0`, then the pointer points", "elif isinstance(pos, Symbol) and pos.get_name() == \"System`All\": pos = None", "raise ValueError(\"ExpressionPointer.head is write protected.\") @property def leaves(self): pos =", "return self.parent.is_atom() elif pos == 0: return self.parent.head.is_atom() return self.parent.leaves[pos", "a list, take the first element, and # store the", "= None # Trivial conversion: if pos is an `Integer`,", "def to_expression(self): parent = self.parent p = self.position if p", "and len( new.leaves ) == len(self._elementsp): for leaf, sub_new in", "path to reach the position i = pos.pop() try: while", "in position `pos` of `expr`. expr: can be an Expression,", "return parent else: return parent.head.copy() else: leaf = self.parent.leaves[p -", "is ExpressionPointer: position = parent.position if position is None: parent", "of an existing Expression. Assignment to a subexpression results in", "if p == 0: if isinstance(parent, Symbol): return parent else:", "__repr__(self) -> str: return self.__str__() @property def original(self): return None" ]
[ "import GetRequest from pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.configuration.configuration_command import ConfigurationCommand", "<filename>pyopenproject/business/services/command/configuration/find.py<gh_stars>1-10 from pyopenproject.api_connection.exceptions.request_exception import RequestError from pyopenproject.api_connection.requests.get_request import GetRequest from", "The connection data \"\"\" super().__init__(connection) def execute(self): try: json_obj =", "from pyopenproject.business.services.command.configuration.configuration_command import ConfigurationCommand from pyopenproject.model.configuration import Configuration class Find(ConfigurationCommand):", "from pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.configuration.configuration_command import ConfigurationCommand from pyopenproject.model.configuration", "import ConfigurationCommand from pyopenproject.model.configuration import Configuration class Find(ConfigurationCommand): def __init__(self,", "from ConfigurationCommand. :param connection: The connection data \"\"\" super().__init__(connection) def", "import Configuration class Find(ConfigurationCommand): def __init__(self, connection): \"\"\"Constructor for class", "import RequestError from pyopenproject.api_connection.requests.get_request import GetRequest from pyopenproject.business.exception.business_error import BusinessError", "Find(ConfigurationCommand): def __init__(self, connection): \"\"\"Constructor for class Find, from ConfigurationCommand.", "f\"{self.CONTEXT}\").execute() return Configuration(json_obj) except RequestError as re: raise BusinessError(\"Error listing", "Find, from ConfigurationCommand. :param connection: The connection data \"\"\" super().__init__(connection)", "pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.configuration.configuration_command import ConfigurationCommand from pyopenproject.model.configuration import", "GetRequest from pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.configuration.configuration_command import ConfigurationCommand from", "\"\"\"Constructor for class Find, from ConfigurationCommand. :param connection: The connection", "return Configuration(json_obj) except RequestError as re: raise BusinessError(\"Error listing configuration\")", "data \"\"\" super().__init__(connection) def execute(self): try: json_obj = GetRequest(self.connection, f\"{self.CONTEXT}\").execute()", "def execute(self): try: json_obj = GetRequest(self.connection, f\"{self.CONTEXT}\").execute() return Configuration(json_obj) except", "except RequestError as re: raise BusinessError(\"Error listing configuration\") from re", "pyopenproject.api_connection.requests.get_request import GetRequest from pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.configuration.configuration_command import", "ConfigurationCommand. :param connection: The connection data \"\"\" super().__init__(connection) def execute(self):", "try: json_obj = GetRequest(self.connection, f\"{self.CONTEXT}\").execute() return Configuration(json_obj) except RequestError as", "GetRequest(self.connection, f\"{self.CONTEXT}\").execute() return Configuration(json_obj) except RequestError as re: raise BusinessError(\"Error", "super().__init__(connection) def execute(self): try: json_obj = GetRequest(self.connection, f\"{self.CONTEXT}\").execute() return Configuration(json_obj)", ":param connection: The connection data \"\"\" super().__init__(connection) def execute(self): try:", "from pyopenproject.api_connection.exceptions.request_exception import RequestError from pyopenproject.api_connection.requests.get_request import GetRequest from pyopenproject.business.exception.business_error", "Configuration(json_obj) except RequestError as re: raise BusinessError(\"Error listing configuration\") from", "def __init__(self, connection): \"\"\"Constructor for class Find, from ConfigurationCommand. :param", "connection: The connection data \"\"\" super().__init__(connection) def execute(self): try: json_obj", "\"\"\" super().__init__(connection) def execute(self): try: json_obj = GetRequest(self.connection, f\"{self.CONTEXT}\").execute() return", "execute(self): try: json_obj = GetRequest(self.connection, f\"{self.CONTEXT}\").execute() return Configuration(json_obj) except RequestError", "Configuration class Find(ConfigurationCommand): def __init__(self, connection): \"\"\"Constructor for class Find,", "RequestError from pyopenproject.api_connection.requests.get_request import GetRequest from pyopenproject.business.exception.business_error import BusinessError from", "ConfigurationCommand from pyopenproject.model.configuration import Configuration class Find(ConfigurationCommand): def __init__(self, connection):", "pyopenproject.api_connection.exceptions.request_exception import RequestError from pyopenproject.api_connection.requests.get_request import GetRequest from pyopenproject.business.exception.business_error import", "connection): \"\"\"Constructor for class Find, from ConfigurationCommand. :param connection: The", "from pyopenproject.model.configuration import Configuration class Find(ConfigurationCommand): def __init__(self, connection): \"\"\"Constructor", "class Find(ConfigurationCommand): def __init__(self, connection): \"\"\"Constructor for class Find, from", "pyopenproject.business.services.command.configuration.configuration_command import ConfigurationCommand from pyopenproject.model.configuration import Configuration class Find(ConfigurationCommand): def", "BusinessError from pyopenproject.business.services.command.configuration.configuration_command import ConfigurationCommand from pyopenproject.model.configuration import Configuration class", "class Find, from ConfigurationCommand. :param connection: The connection data \"\"\"", "for class Find, from ConfigurationCommand. :param connection: The connection data", "= GetRequest(self.connection, f\"{self.CONTEXT}\").execute() return Configuration(json_obj) except RequestError as re: raise", "json_obj = GetRequest(self.connection, f\"{self.CONTEXT}\").execute() return Configuration(json_obj) except RequestError as re:", "from pyopenproject.api_connection.requests.get_request import GetRequest from pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.configuration.configuration_command", "import BusinessError from pyopenproject.business.services.command.configuration.configuration_command import ConfigurationCommand from pyopenproject.model.configuration import Configuration", "pyopenproject.model.configuration import Configuration class Find(ConfigurationCommand): def __init__(self, connection): \"\"\"Constructor for", "connection data \"\"\" super().__init__(connection) def execute(self): try: json_obj = GetRequest(self.connection,", "__init__(self, connection): \"\"\"Constructor for class Find, from ConfigurationCommand. :param connection:" ]
[ "@mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create', mock.Mock()) def test_create(self): \"\"\"Dummy test for", "class ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell tests.\"\"\" def setUp(self): self.cell = cell.API() def", "from __future__ import division from __future__ import print_function from __future__", "None))) @mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[])) def test_list(self): \"\"\"Dummy test for treadmill.api.cell._list()\"\"\" self.cell.list()", "absolute_import from __future__ import division from __future__ import print_function from", "\"\"\"Dummy test for treadmill.api.cell._list()\"\"\" self.cell.list() cell_admin = admin.Cell(None) self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn',", "for treadmill.api.cell.get()\"\"\" cell_admin = admin.Cell(None) self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None)))", "@mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create', mock.Mock()) def test_create(self):", "= admin.Cell(None) self.cell.create('some-cell', {'location': 'ny', 'treadmillid': 'treadmld', 'version': 'v3'}) cell_admin.get.assert_called_with('some-cell',", "mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create', mock.Mock()) def test_create(self): \"\"\"Dummy", "@mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[])) def test_list(self): \"\"\"Dummy test for", "mock.Mock(return_value={'cell': 'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create', mock.Mock()) def test_create(self): \"\"\"Dummy test for treadmill.api.cell.create()\"\"\"", "import unicode_literals import unittest import mock from treadmill import admin", "tests.\"\"\" def setUp(self): self.cell = cell.API() def tearDown(self): pass @mock.patch('treadmill.context.AdminContext.conn',", "'ny', 'treadmillid': 'treadmld', 'version': 'v3'}) cell_admin.get.assert_called_with('some-cell', dirty=True) if __name__ ==", "pass @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[])) def test_list(self): \"\"\"Dummy test", "= admin.Cell(None) self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'}))", "None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) def test_get(self): \"\"\"Dummy test for treadmill.api.cell.get()\"\"\"", "for treadmill.api.cell._list()\"\"\" self.cell.list() cell_admin = admin.Cell(None) self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None)))", "= admin.Cell(None) self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) def", "__future__ import unicode_literals import unittest import mock from treadmill import", "= cell.API() def tearDown(self): pass @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[]))", "test for treadmill.api.cell.create()\"\"\" cell_admin = admin.Cell(None) self.cell.create('some-cell', {'location': 'ny', 'treadmillid':", "cell_admin = admin.Cell(None) self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell':", "self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) def test_get(self): \"\"\"Dummy", "import print_function from __future__ import unicode_literals import unittest import mock", "def test_create(self): \"\"\"Dummy test for treadmill.api.cell.create()\"\"\" cell_admin = admin.Cell(None) self.cell.create('some-cell',", "test_get(self): \"\"\"Dummy test for treadmill.api.cell.get()\"\"\" cell_admin = admin.Cell(None) self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell')", "tearDown(self): pass @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[])) def test_list(self): \"\"\"Dummy", "tests. \"\"\" from __future__ import absolute_import from __future__ import division", "unicode_literals import unittest import mock from treadmill import admin from", "test_create(self): \"\"\"Dummy test for treadmill.api.cell.create()\"\"\" cell_admin = admin.Cell(None) self.cell.create('some-cell', {'location':", "self.cell.create('some-cell', {'location': 'ny', 'treadmillid': 'treadmld', 'version': 'v3'}) cell_admin.get.assert_called_with('some-cell', dirty=True) if", "cell class ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell tests.\"\"\" def setUp(self): self.cell = cell.API()", "__future__ import division from __future__ import print_function from __future__ import", "admin.Cell(None) self.cell.create('some-cell', {'location': 'ny', 'treadmillid': 'treadmld', 'version': 'v3'}) cell_admin.get.assert_called_with('some-cell', dirty=True)", "\"\"\"Dummy test for treadmill.api.cell.create()\"\"\" cell_admin = admin.Cell(None) self.cell.create('some-cell', {'location': 'ny',", "__future__ import print_function from __future__ import unicode_literals import unittest import", "admin.Cell(None) self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create',", "@mock.patch('treadmill.admin.Cell.create', mock.Mock()) def test_create(self): \"\"\"Dummy test for treadmill.api.cell.create()\"\"\" cell_admin =", "import admin from treadmill.api import cell class ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell tests.\"\"\"", "ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell tests.\"\"\" def setUp(self): self.cell = cell.API() def tearDown(self):", "\"\"\"Dummy test for treadmill.api.cell.get()\"\"\" cell_admin = admin.Cell(None) self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn',", "from __future__ import print_function from __future__ import unicode_literals import unittest", "self.cell.list() cell_admin = admin.Cell(None) self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell':", "setUp(self): self.cell = cell.API() def tearDown(self): pass @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None)))", "self.cell = cell.API() def tearDown(self): pass @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.list',", "treadmill.api.cell._list()\"\"\" self.cell.list() cell_admin = admin.Cell(None) self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get',", "\"\"\"Cell API tests. \"\"\" from __future__ import absolute_import from __future__", "from __future__ import absolute_import from __future__ import division from __future__", "@mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) def test_get(self): \"\"\"Dummy test for treadmill.api.cell.get()\"\"\" cell_admin", "def test_list(self): \"\"\"Dummy test for treadmill.api.cell._list()\"\"\" self.cell.list() cell_admin = admin.Cell(None)", "{'location': 'ny', 'treadmillid': 'treadmld', 'version': 'v3'}) cell_admin.get.assert_called_with('some-cell', dirty=True) if __name__", "@mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) def test_get(self): \"\"\"Dummy test", "mock from treadmill import admin from treadmill.api import cell class", "cell_admin = admin.Cell(None) self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'}))", "self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create', mock.Mock())", "import unittest import mock from treadmill import admin from treadmill.api", "admin from treadmill.api import cell class ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell tests.\"\"\" def", "@mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[])) def test_list(self): \"\"\"Dummy test for treadmill.api.cell._list()\"\"\" self.cell.list() cell_admin", "'treadmillid': 'treadmld', 'version': 'v3'}) cell_admin.get.assert_called_with('some-cell', dirty=True) if __name__ == '__main__':", "mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[])) def test_list(self): \"\"\"Dummy test for treadmill.api.cell._list()\"\"\"", "test_list(self): \"\"\"Dummy test for treadmill.api.cell._list()\"\"\" self.cell.list() cell_admin = admin.Cell(None) self.assertTrue(cell_admin.list.called)", "None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create', mock.Mock()) def test_create(self): \"\"\"Dummy test", "<gh_stars>1-10 \"\"\"Cell API tests. \"\"\" from __future__ import absolute_import from", "'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create', mock.Mock()) def test_create(self): \"\"\"Dummy test for treadmill.api.cell.create()\"\"\" cell_admin", "from treadmill.api import cell class ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell tests.\"\"\" def setUp(self):", "cell_admin = admin.Cell(None) self.cell.create('some-cell', {'location': 'ny', 'treadmillid': 'treadmld', 'version': 'v3'})", "admin.Cell(None) self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) def test_get(self):", "division from __future__ import print_function from __future__ import unicode_literals import", "API tests. \"\"\" from __future__ import absolute_import from __future__ import", "unittest import mock from treadmill import admin from treadmill.api import", "\"\"\" from __future__ import absolute_import from __future__ import division from", "def test_get(self): \"\"\"Dummy test for treadmill.api.cell.get()\"\"\" cell_admin = admin.Cell(None) self.cell.get('some-cell')", "test for treadmill.api.cell._list()\"\"\" self.cell.list() cell_admin = admin.Cell(None) self.assertTrue(cell_admin.list.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None,", "test for treadmill.api.cell.get()\"\"\" cell_admin = admin.Cell(None) self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None,", "import division from __future__ import print_function from __future__ import unicode_literals", "__future__ import absolute_import from __future__ import division from __future__ import", "'ny-999-cell'})) def test_get(self): \"\"\"Dummy test for treadmill.api.cell.get()\"\"\" cell_admin = admin.Cell(None)", "treadmill import admin from treadmill.api import cell class ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell", "import cell class ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell tests.\"\"\" def setUp(self): self.cell =", "treadmill.api.cell.get()\"\"\" cell_admin = admin.Cell(None) self.cell.get('some-cell') cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get',", "import mock from treadmill import admin from treadmill.api import cell", "from treadmill import admin from treadmill.api import cell class ApiCellTest(unittest.TestCase):", "for treadmill.api.cell.create()\"\"\" cell_admin = admin.Cell(None) self.cell.create('some-cell', {'location': 'ny', 'treadmillid': 'treadmld',", "cell_admin.get.assert_called_with('some-cell') @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) @mock.patch('treadmill.admin.Cell.create', mock.Mock()) def", "print_function from __future__ import unicode_literals import unittest import mock from", "treadmill.api.cell.create()\"\"\" cell_admin = admin.Cell(None) self.cell.create('some-cell', {'location': 'ny', 'treadmillid': 'treadmld', 'version':", "def setUp(self): self.cell = cell.API() def tearDown(self): pass @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None,", "from __future__ import unicode_literals import unittest import mock from treadmill", "mock.Mock(return_value=[])) def test_list(self): \"\"\"Dummy test for treadmill.api.cell._list()\"\"\" self.cell.list() cell_admin =", "'treadmld', 'version': 'v3'}) cell_admin.get.assert_called_with('some-cell', dirty=True) if __name__ == '__main__': unittest.main()", "def tearDown(self): pass @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[])) def test_list(self):", "\"\"\"treadmill.api.cell tests.\"\"\" def setUp(self): self.cell = cell.API() def tearDown(self): pass", "treadmill.api import cell class ApiCellTest(unittest.TestCase): \"\"\"treadmill.api.cell tests.\"\"\" def setUp(self): self.cell", "import absolute_import from __future__ import division from __future__ import print_function", "mock.Mock()) def test_create(self): \"\"\"Dummy test for treadmill.api.cell.create()\"\"\" cell_admin = admin.Cell(None)", "mock.Mock(return_value={'cell': 'ny-999-cell'})) def test_get(self): \"\"\"Dummy test for treadmill.api.cell.get()\"\"\" cell_admin =", "cell.API() def tearDown(self): pass @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.list', mock.Mock(return_value=[])) def", "mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.admin.Cell.get', mock.Mock(return_value={'cell': 'ny-999-cell'})) def test_get(self): \"\"\"Dummy test for" ]
[ "# ------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", "for information. # ------------------------------------------------------------- \"\"\"Python Package Template\"\"\" from __future__ import", "------------------------------------------------------------- \"\"\"Python Package Template\"\"\" from __future__ import annotations __version__ =", "the MIT License. See LICENSE in project root for information.", "Microsoft Corporation. All rights reserved. # Licensed under the MIT", "# ------------------------------------------------------------- \"\"\"Python Package Template\"\"\" from __future__ import annotations __version__", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed", "information. # ------------------------------------------------------------- \"\"\"Python Package Template\"\"\" from __future__ import annotations", "LICENSE in project root for information. # ------------------------------------------------------------- \"\"\"Python Package", "root for information. # ------------------------------------------------------------- \"\"\"Python Package Template\"\"\" from __future__", "reserved. # Licensed under the MIT License. See LICENSE in", "<filename>src/python_package/__init__.py<gh_stars>1-10 # ------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights", "project root for information. # ------------------------------------------------------------- \"\"\"Python Package Template\"\"\" from", "in project root for information. # ------------------------------------------------------------- \"\"\"Python Package Template\"\"\"", "Licensed under the MIT License. See LICENSE in project root", "------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #", "under the MIT License. See LICENSE in project root for", "MIT License. See LICENSE in project root for information. #", "\"\"\"Python Package Template\"\"\" from __future__ import annotations __version__ = \"0.0.2\"", "Corporation. All rights reserved. # Licensed under the MIT License.", "(c) Microsoft Corporation. All rights reserved. # Licensed under the", "All rights reserved. # Licensed under the MIT License. See", "# Licensed under the MIT License. See LICENSE in project", "rights reserved. # Licensed under the MIT License. See LICENSE", "License. See LICENSE in project root for information. # -------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "See LICENSE in project root for information. # ------------------------------------------------------------- \"\"\"Python" ]
[ "class MultiNodeTestPartition(MultiNodeTest): def test_scenario30_partition(self): self.start_processes_with_test_scenario(30, 5) time.sleep(8) self.terminate_processes() node0_blocks =", "nodes. Note: run tests with default setting values in config.py.", "node3_blocks = self.extract_committed_blocks_single_process(3) node4_blocks = self.extract_committed_blocks_single_process(4) assert len(node0_blocks) > 0", "node1_blocks def test_scenario31_partition(self): self.start_processes_with_test_scenario(31, 5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0)", "time from tests.util import MultiNodeTest class MultiNodeTestPartition(MultiNodeTest): def test_scenario30_partition(self): self.start_processes_with_test_scenario(30,", "self.extract_committed_blocks_single_process(1) node2_blocks = self.extract_committed_blocks_single_process(2) node3_blocks = self.extract_committed_blocks_single_process(3) node4_blocks = self.extract_committed_blocks_single_process(4)", "of piChain nodes. Note: run tests with default setting values", "node4_blocks = self.extract_committed_blocks_single_process(4) assert len(node0_blocks) > 0 assert node0_blocks ==", "node1_blocks assert node3_blocks == node1_blocks assert node4_blocks == node1_blocks def", "test_scenario30_partition(self): self.start_processes_with_test_scenario(30, 5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks =", "node1_blocks assert node4_blocks == node1_blocks def test_scenario32_partition(self): self.start_processes_with_test_scenario(32, 5) time.sleep(15)", "node3_blocks == node1_blocks assert node4_blocks == node1_blocks def test_scenario32_partition(self): self.start_processes_with_test_scenario(32,", "== node1_blocks assert node4_blocks == node1_blocks def test_scenario32_partition(self): self.start_processes_with_test_scenario(32, 5)", "= self.extract_committed_blocks_single_process(2) node3_blocks = self.extract_committed_blocks_single_process(3) node4_blocks = self.extract_committed_blocks_single_process(4) assert len(node0_blocks)", "assert node3_blocks == node1_blocks assert node4_blocks == node1_blocks def test_scenario32_partition(self):", "run tests with default setting values in config.py. \"\"\" import", "len(node0_blocks) > 0 assert node0_blocks == node1_blocks assert node2_blocks ==", "def test_scenario31_partition(self): self.start_processes_with_test_scenario(31, 5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks", "node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks = self.extract_committed_blocks_single_process(2) node3_blocks", "Test partition of piChain nodes. Note: run tests with default", "self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks = self.extract_committed_blocks_single_process(2)", "assert node4_blocks == node1_blocks def test_scenario31_partition(self): self.start_processes_with_test_scenario(31, 5) time.sleep(8) self.terminate_processes()", "node1_blocks assert node2_blocks == node1_blocks assert node3_blocks == node1_blocks assert", "def test_scenario32_partition(self): self.start_processes_with_test_scenario(32, 5) time.sleep(15) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks", "node4_blocks == node1_blocks def test_scenario31_partition(self): self.start_processes_with_test_scenario(31, 5) time.sleep(8) self.terminate_processes() node0_blocks", "5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks", "5) time.sleep(15) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks", "test_scenario31_partition(self): self.start_processes_with_test_scenario(31, 5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks =", "self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks = self.extract_committed_blocks_single_process(2) node3_blocks = self.extract_committed_blocks_single_process(3)", "tests.util import MultiNodeTest class MultiNodeTestPartition(MultiNodeTest): def test_scenario30_partition(self): self.start_processes_with_test_scenario(30, 5) time.sleep(8)", "\"\"\" import time from tests.util import MultiNodeTest class MultiNodeTestPartition(MultiNodeTest): def", "import MultiNodeTest class MultiNodeTestPartition(MultiNodeTest): def test_scenario30_partition(self): self.start_processes_with_test_scenario(30, 5) time.sleep(8) self.terminate_processes()", "MultiNodeTestPartition(MultiNodeTest): def test_scenario30_partition(self): self.start_processes_with_test_scenario(30, 5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0)", "= self.extract_committed_blocks_single_process(4) assert len(node0_blocks) > 0 assert node0_blocks == node1_blocks", "0 assert node0_blocks == node1_blocks assert node2_blocks == node1_blocks assert", "Note: run tests with default setting values in config.py. \"\"\"", "self.extract_committed_blocks_single_process(4) assert len(node0_blocks) > 0 assert node0_blocks == node1_blocks assert", "test_scenario32_partition(self): self.start_processes_with_test_scenario(32, 5) time.sleep(15) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks =", "node4_blocks == node1_blocks def test_scenario32_partition(self): self.start_processes_with_test_scenario(32, 5) time.sleep(15) self.terminate_processes() node0_blocks", "node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks = self.extract_committed_blocks_single_process(2) node3_blocks = self.extract_committed_blocks_single_process(3) node4_blocks", "values in config.py. \"\"\" import time from tests.util import MultiNodeTest", "= self.extract_committed_blocks_single_process(3) node4_blocks = self.extract_committed_blocks_single_process(4) assert len(node0_blocks) > 0 assert", "test: Test partition of piChain nodes. Note: run tests with", "== node1_blocks assert node2_blocks == node1_blocks assert node3_blocks == node1_blocks", "== node1_blocks assert node3_blocks == node1_blocks assert node4_blocks == node1_blocks", "== node1_blocks def test_scenario32_partition(self): self.start_processes_with_test_scenario(32, 5) time.sleep(15) self.terminate_processes() node0_blocks =", "> 0 assert node0_blocks == node1_blocks assert node2_blocks == node1_blocks", "time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks =", "def test_scenario30_partition(self): self.start_processes_with_test_scenario(30, 5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks", "config.py. \"\"\" import time from tests.util import MultiNodeTest class MultiNodeTestPartition(MultiNodeTest):", "= self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks = self.extract_committed_blocks_single_process(2) node3_blocks =", "self.start_processes_with_test_scenario(32, 5) time.sleep(15) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1)", "setting values in config.py. \"\"\" import time from tests.util import", "in config.py. \"\"\" import time from tests.util import MultiNodeTest class", "= self.extract_committed_blocks_single_process(1) node2_blocks = self.extract_committed_blocks_single_process(2) node3_blocks = self.extract_committed_blocks_single_process(3) node4_blocks =", "\"\"\"Integration test: Test partition of piChain nodes. Note: run tests", "node1_blocks def test_scenario32_partition(self): self.start_processes_with_test_scenario(32, 5) time.sleep(15) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0)", "from tests.util import MultiNodeTest class MultiNodeTestPartition(MultiNodeTest): def test_scenario30_partition(self): self.start_processes_with_test_scenario(30, 5)", "node2_blocks == node1_blocks assert node3_blocks == node1_blocks assert node4_blocks ==", "time.sleep(15) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1) node2_blocks =", "assert node3_blocks == node1_blocks assert node4_blocks == node1_blocks def test_scenario31_partition(self):", "piChain nodes. Note: run tests with default setting values in", "self.extract_committed_blocks_single_process(2) node3_blocks = self.extract_committed_blocks_single_process(3) node4_blocks = self.extract_committed_blocks_single_process(4) assert len(node0_blocks) >", "partition of piChain nodes. Note: run tests with default setting", "self.extract_committed_blocks_single_process(3) node4_blocks = self.extract_committed_blocks_single_process(4) assert len(node0_blocks) > 0 assert node0_blocks", "node1_blocks assert node4_blocks == node1_blocks def test_scenario31_partition(self): self.start_processes_with_test_scenario(31, 5) time.sleep(8)", "node3_blocks == node1_blocks assert node4_blocks == node1_blocks def test_scenario31_partition(self): self.start_processes_with_test_scenario(31,", "node2_blocks = self.extract_committed_blocks_single_process(2) node3_blocks = self.extract_committed_blocks_single_process(3) node4_blocks = self.extract_committed_blocks_single_process(4) assert", "with default setting values in config.py. \"\"\" import time from", "self.start_processes_with_test_scenario(31, 5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1)", "== node1_blocks def test_scenario31_partition(self): self.start_processes_with_test_scenario(31, 5) time.sleep(8) self.terminate_processes() node0_blocks =", "tests with default setting values in config.py. \"\"\" import time", "default setting values in config.py. \"\"\" import time from tests.util", "assert node0_blocks == node1_blocks assert node2_blocks == node1_blocks assert node3_blocks", "self.start_processes_with_test_scenario(30, 5) time.sleep(8) self.terminate_processes() node0_blocks = self.extract_committed_blocks_single_process(0) node1_blocks = self.extract_committed_blocks_single_process(1)", "assert node2_blocks == node1_blocks assert node3_blocks == node1_blocks assert node4_blocks", "assert node4_blocks == node1_blocks def test_scenario32_partition(self): self.start_processes_with_test_scenario(32, 5) time.sleep(15) self.terminate_processes()", "assert len(node0_blocks) > 0 assert node0_blocks == node1_blocks assert node2_blocks", "== node1_blocks assert node4_blocks == node1_blocks def test_scenario31_partition(self): self.start_processes_with_test_scenario(31, 5)", "node0_blocks == node1_blocks assert node2_blocks == node1_blocks assert node3_blocks ==", "import time from tests.util import MultiNodeTest class MultiNodeTestPartition(MultiNodeTest): def test_scenario30_partition(self):", "<gh_stars>1-10 \"\"\"Integration test: Test partition of piChain nodes. Note: run", "MultiNodeTest class MultiNodeTestPartition(MultiNodeTest): def test_scenario30_partition(self): self.start_processes_with_test_scenario(30, 5) time.sleep(8) self.terminate_processes() node0_blocks" ]